Jenkins Global environment variables in Jenkinsfile

后端 未结 5 1128
深忆病人
深忆病人 2021-02-05 06:17

How do I invoke Global environment variables in Jenkinsfile?
For example, if I have a variable -

 name:credentialsId 
 value:xxxx-xxxx-xxxxx-xxxxxxxxx


        
相关标签:
5条回答
  • 2021-02-05 06:34

    Another syntax is $ENV:xxxx

    node {
    echo "Running $ENV.BUILD_ID on $ENV.JENKINS_URL" }
    

    This worked for me

    0 讨论(0)
  • 2021-02-05 06:36

    When referring to env in Groovy scope, simply use env.VARIABLE_NAME, for example to pass on BUILD_NUMBER of upstream job to a triggered job:

    stage ('Starting job') {
        build job: 'TriggerTest', parameters: [
            [$class: 'StringParameterValue', name: 'upstream_build_number', value: env.BUILD_NUMBER]
        ]
    }
    
    0 讨论(0)
  • 2021-02-05 06:42

    In a Jenkinsfile, you have the "Working with the Environment" which mentions:

    The full list of environment variables accessible from within Jenkins Pipeline is documented at localhost:8080/pipeline-syntax/globals#env,

    The syntax is ${env.xxx} as in:

    node {
        echo "Running ${env.BUILD_ID} on ${env.JENKINS_URL}"
    }
    

    See also "Managing the Environment".

    How can I pass the Global variables to the Jenkinsfile?
    When I say Global variables - I mean in

    Jenkins -> Manage Jenkins -> Configure System -> Global properties -> Environment variables
    

    See "Setting environment variables"

    Setting an environment variable within a Jenkins Pipeline can be done with the withEnv step, which allows overriding specified environment variables for a given block of Pipeline Script, for example:

    Jenkinsfile (Pipeline Script)

    node {
        /* .. snip .. */
        withEnv(["NAME=value"]) {
            ... your job
        }
    }
    
    0 讨论(0)
  • 2021-02-05 06:44

    Scripted pipeline To read an environment variable whose name you know, use env.NAME

    To read an environment variable whose name is not known until runtime use env.getProperty(name).

    For example, a value from a YAML config file represents an environment variable name:

    config.yaml (in workspace)

    myconfig:
      key: JOB_DISPLAY_URL
    

    Jenkinsfile

    node {
        println("Running job ${env.JOB_NAME}")
        def config = readYaml(file:'config.yaml')
        def value = env.getProperty(config.myconfig.key)
        println("Value of property ${config.myconfig.key} is ${value}")
    }
    
    0 讨论(0)
  • 2021-02-05 06:47

    For getting values all env.VAR, env['VAR'], env.getProperty('VAR') are fine.
    For setting values the only safe way at the moment is withEnv. If you try to assign values to env.VAR it may not work in some cases like for parallel pipelines (like in JENKINS-59871).

    0 讨论(0)
提交回复
热议问题