How to assign a an env variable in the middle of a jenkins job

I have a Jenkinsfile containing a pipeline. I have set a parameter that can be optional to pass, and also a default value is set if no parameter is set:

parameters {
    string(name: 'MY_VAR', defaultValue: 'foo', description: 'my var that can be optional')
}

In the middle of the stages I would like to override (only some times, and only if some other specific parameters are passed) this 'my_var' with some other value.

So far this works:

        stage('Build') {
            steps {
                env.MY_VAR="foobar"
            }
        }

but I would like to read that variable from a file, so I would like to do something like:

        stage('Build') {
            steps {
                // Of course none of following work
                env.MY_VAR=$(cat /tmp/my-file)
               
                //or
                sh "new_var=$(cat /tmp/my-file)"
                env.MY_VAR=$new_var 
            }
        }

How can I achieve this?

Upvotes: 1

Views: 1459

Answers (2)

Catalin
Catalin

Reputation: 484

You can actually use any of the groovy libraries inside the script statement. For example, you can use the File class to read text files:


pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                script {
                    def filePath = "/tmp/my-file"
                    env.VAR = new File(filePath).text
                }
            }
        }
        stage('Test') {
            steps {
                echo env.VAR
            }
        }
    }
}

Upvotes: 1

Dmitriy Tarasevich
Dmitriy Tarasevich

Reputation: 1242

I suppose you need to use script block. Defining variables in script block will allow you to use them in entire pipeline, not only in a separate stage.

stage ('Build') {
  steps {
    script {
      env.MY_VAR=sh returnStdout: true, script: """ cat /tmp/my-file """
      echo "${env.MY_VAR}"
    }
  }
}

Upvotes: 1

Related Questions