Add a default value to a template attribute

Article ID:204350810
1 minute readKnowledge base

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>
This example example has been tested on CloudBees Jenkins Enterprise 2.32.3.2-rolling with Templates plugin 4.26