[jenkins] How to set and reference a variable in a Jenkinsfile

I have a declarative pipeline script for my multibranch project in which I would like to read a text file and store the result as a string variable to be accessed by a later step in the pipeline. Using the snippet generator I tried to do something like this:

filename = readFile 'output.txt'

For which filename would be my string.

I get an error in the Jenkins console output:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 30: Expected a step @ line 30, column 5.
            filename = readFile 'output.txt'

Do I need to use a withEnv step to set the output of readFile to a Jenkins environment variable? If so, how?

Thanks

The answer is


We got around this by adding functions to the environment step, i.e.:

environment {
    ENVIRONMENT_NAME = defineEnvironment() 
}
...
def defineEnvironment() {
    def branchName = "${env.BRANCH_NAME}"
    if (branchName == "master") {
        return 'staging'
    }
    else {
        return 'test'
    }
}

I can' t comment yet but, just a hint: use try/catch clauses to avoid breaking the pipeline (if you are sure the file exists, disregard)

    pipeline {
        agent any
            stages {
                stage("foo") {
                    steps {
                        script {
                            try {                    
                                env.FILENAME = readFile 'output.txt'
                                echo "${env.FILENAME}"
                            }
                            catch(Exception e) {
                                //do something, e.g. echo 'File not found'
                            }
                        }
                   }
    }

Another hint (this was commented by @hao, and think is worth to share): you may want to trim like this readFile('output.txt').trim()


A complete example for scripted pipepline:

       stage('Build'){
            withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
                sh 'bash build.sh'
            }
        }

According to the documentation, you can also set global environment variables if you later want to use the value of the variable in other parts of your script. In your case, it would be setting it in the root pipeline:

pipeline {
  ...
  environment {
    FILENAME = readFile ...
  }
  ...
}

Examples related to jenkins

Maven dependencies are failing with a 501 error Jenkins pipeline how to change to another folder Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding How to solve npm install throwing fsevents warning on non-MAC OS? Run bash command on jenkins pipeline Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Jenkins pipeline if else not working Error "The input device is not a TTY"

Examples related to groovy

Jenkins pipeline how to change to another folder groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding Run bash command on jenkins pipeline Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Jenkins pipeline if else not working How to set and reference a variable in a Jenkinsfile Jenkins: Can comments be added to a Jenkinsfile? How to define and use function inside Jenkins Pipeline config? Jenkins: Cannot define variable in pipeline stage

Examples related to jenkins-plugins

How to set and reference a variable in a Jenkinsfile Jenkins: Is there any way to cleanup Jenkins workspace? How to get build time stamp from Jenkins build variables? gpg: no valid OpenPGP data found How to install a plugin in Jenkins manually Execute Shell Script after post build in Jenkins Jenkins CI: How to trigger builds on SVN commit How to get a list of installed Jenkins plugins with name and version pair In Jenkins, how to checkout a project into a specific directory (using GIT)

Examples related to jenkins-pipeline

Jenkins pipeline how to change to another folder Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Error "The input device is not a TTY" How to set and reference a variable in a Jenkinsfile Get git branch name in Jenkins Pipeline/Jenkinsfile Jenkins: Can comments be added to a Jenkinsfile? How to define and use function inside Jenkins Pipeline config? Environment variable in Jenkins Pipeline

Examples related to multibranch-pipeline

How to set and reference a variable in a Jenkinsfile