Danijel
Danijel

Reputation: 8616

Using env variables in a Jenkinsfile function?

I'm triggering one Jenkins job from the other, all via Jenkinsfiles.

stage("Trigger another job")
{
    build([job:"Job2", wait:true, propagate:true, parameters: [string(name:'branch_my',value:"${env.ghprbActualCommit}")]])
}

Note that parameter branch_my is sent to Job2. However, the pipeline Job2 needs to work even when branch_my is NOT defined, for example when it is triggered manually.

Jenkinsfile for Job2 looks like:

pipeline
{
  // ...
  steps
  {
    customBranches()
    // etc...
  }
}


def customBranches()
{
    if ( env.branch_my != null)
    {
        sh "switch_to ${env.branch_my}"
    }
}

However, the customBranches() if statement never evaluates to true. When I do

sh "echo 'Env branch_my is: ${env.branch_my} '"

I get Env branch_my is: some_value , which is OK, and if statement should evaluate to true - but it does not.

I tried adding ${} like so: if ( ${env.branch_my} != null), but that failed completely: No such DSL method "$" found.

What's wrong with my customBranches()?

Upvotes: 0

Views: 257

Answers (1)

Danijel
Danijel

Reputation: 8616

Problem isn't the Jenkinsfile syntax, but the Jenkins job configuration: it must be labeled as "parametrized" in the GUI and a string parameter branch_my needs to be defined:

Jenkins parametrized job

Note, the parameters can be added via the Jenkinsfile itself:

parameters { string(name: 'branch_my', defaultValue: 'master', description: '') }

However, this just adds the parameter to the GUI, so you end up with the same thing.

Upvotes: 1

Related Questions