Add a default value to a template attribute

Issue

  • I would like to assign a default value to a “variableX” once it is not passed any value for a Job based on a Template

Environment

Resolution

In your Job Template:

On the Attributes section, add a new one:

  • ID: variableX
  • Display Name: variableX
  • Type: Text-Field (for this example)

Groovy Transformation

On the Transformer section

  • Type: Groovy Template Transformation (for this example)
  • Script, as follows:
<project> 
<%
// Adding default value if variable is empty
if (variableX == "" || variableX == null) {
       variableX="default-value-TEMPLATE"
}
%>
<actions/> 
<description/> 
<keepDependencies>false</keepDependencies> 
<properties> 
<org.jenkinsci.plugins.gitbucket.GitBucketProjectProperty plugin="gitbucket@0.5.1"> 
<linkEnabled>false</linkEnabled> 
</org.jenkinsci.plugins.gitbucket.GitBucketProjectProperty> 
</properties> 
<scm class="hudson.scm.NullSCM"/> 
<canRoam>true</canRoam> 
<disabled>false</disabled> 
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding> 
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding> 
<triggers/> 
<concurrentBuild>false</concurrentBuild> 
<builders> 
<hudson.tasks.Shell> 
<command>echo This is the value of my <%=variableX%> </command> 
</hudson.tasks.Shell> 
</builders> 
<publishers/> 
<buildWrappers/> 
</project>

Jelly Transformation

On the Transformer section

  • Type: Jelly Template Transformation (for this example)
  • Script, as follows:
<?xml version='1.0' encoding='UTF-8'?>
<project>
    <j:if xmlns:j="jelly:core" test="${variableX == '' || variableX == null}">
        <j:set var="variableX" value="default-value-TEMPLATE"/>
    </j:if>
    <description></description>
    <actions/>
    <keepDependencies>false</keepDependencies>
    <properties/>
    <canRoam>true</canRoam>
    <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
    <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
    <triggers/>
    <concurrentBuild>false</concurrentBuild>
    <builders>
    <hudson.tasks.Shell>
        <command>echo This is the value of my ${variableX} </command>
    </hudson.tasks.Shell>
    </builders>
    <publishers/>
    <buildWrappers/>
</project>

Note: This example example has been tested on CloudBees Jenkins Enterprise 2.32.3.2-rolling with Templates plugin 4.26

Have more questions? Submit a request

2 Comments

  • 0
    Avatar
    Jagtar Singh

    The above code is not working. Please provide more details on this.

  • 0
    Avatar
    Allan Burdajewicz

    What issue are you facing ? Note that this script assumes that you have a Text attribute named 'variableX' added to your template.

Please sign in to leave a comment.