Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

Load file with environment variables Jenkins Pipeline

I am doing a simple pipeline:

Build -> Staging -> Production

I need different environment variables for staging and production, so i am trying to source variables.

sh 'source $JENKINS_HOME/.envvars/stacktest-staging.sh' 

But it returns Not found

[Stack Test] Running shell script
+ source /var/jenkins_home/.envvars/stacktest-staging.sh
/var/jenkins_home/workspace/Stack Test@tmp/durable-bcbe1515/script.sh: 2: /var/jenkins_home/workspace/Stack Test@tmp/durable-bcbe1515/script.sh: source: not found

The path is right, because i run the same command when i log via ssh, and it works fine.

Here is the pipeline idea:

node {
    stage name: 'Build'
    // git and gradle build OK
    echo 'My build stage'

    stage name: 'Staging'
    sh 'source $JENKINS_HOME/.envvars/stacktest-staging.sh' // PROBLEM HERE
    echo '$DB_URL' // Expects http://production_url/my_db
    sh 'gradle flywayMigrate' // To staging
    input message: "Does Staging server look good?"    

    stage name: 'Production'
    sh 'source $JENKINS_HOME/.envvars/stacktest-production.sh'
    echo '$DB_URL' // Expects http://production_url/my_db
    sh 'gradle flywayMigrate' // To production
    sh './deploy.sh'
}

What should i do?

  • I was thinking about not using pipeline (but i will not be able to use my Jenkinsfile).
  • Or make different jobs for staging and production, using EnvInject Plugin (But i lose my stage view)
  • Or make withEnv (but the code gets big, because today i am working with 12 env vars)
question from:https://stackoverflow.com/questions/39171341/load-file-with-environment-variables-jenkins-pipeline

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way you could load environment variables from a file is to load a Groovy file.

For example:

  1. Let's say you have a groovy file in '$JENKINS_HOME/.envvars' called 'stacktest-staging.groovy'.
  2. Inside this file, you define 2 environment variables you want to load

    env.DB_URL="hello"
    env.DB_URL2="hello2"
    
  3. You can then load this in using

    load "$JENKINS_HOME/.envvars/stacktest-staging.groovy"
    
  4. Then you can use them in subsequent echo/shell steps.

For example, here is a short pipeline script:

node {
   load "$JENKINS_HOME/.envvars/stacktest-staging.groovy"
   echo "${env.DB_URL}"
   echo "${env.DB_URL2}"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...