Jenkins Pipeline accessing environment variables

后端 未结 4 2026
难免孤独
难免孤独 2020-12-24 11:45

I\'m trying to use DSL pipelines in Jenkins. I thought it\'d be nice if I could use the project name as part of my script.

git credentialsId: \'ffffffff-ffff         


        
相关标签:
4条回答
  • 2020-12-24 12:21

    All environment variables are accessible using env, e.g. ${env.JOB_NAME}.

    0 讨论(0)
  • Okay this really vexed me for a while today. Ultimately, I was being done in by a couple of things:

    • Single-quoted strings in Groovy mean "don't evaluate variables," just like it does in bash
    • Using $ interpolation is completely unnecessary if you're just referencing the variable, so you can just do env.JOB_NAME.

    This SO question proved to be the one that helped me crack the code: Jenkins Workflow Checkout Accessing BRANCH_NAME and GIT_COMMIT

    0 讨论(0)
  • 2020-12-24 12:30

    I had an issue with this not working. The globally set properties/environment variables were only available inside a node step. It's a bug in version 2.4 of Pipeline plugin. Upgrade to 2.5 if you face this issue and your global properties will be available anywhere in the script. I've posted this to the Jenkins wiki here with the test script I used.

    0 讨论(0)
  • 2020-12-24 12:40

    Indeed just use ${env.JOB_NAME} to access a known variable.

    However if you need to access environment variable where name is given by another variable (dynamic access), just use env["your-env-variable"].

    I had the problem where I configured 3 environment variables (in Jenkins -> Administer -> Configure System -> Environment variables), let's name them ENV_VAR_1, ENV_VAR_2, ENV_VAR_3. Now I want to dynamically access them, I can do as such :

    def envVarName = "ENV_VAR_" + count  // Suppose count is initialized in a loop somewhere above...
    
    def value = env[envVarName]  // Will be resolved to env["ENV_VAR_1"] depending on count value
    

    My environment variables in Jenkins configuration look like this :

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