3

I want to set quite a few variables in Jenkins. I have tried putting them in .bashrc, .bash_profile and .profile of the jenkins user but Jenkins cannot find them when a build is happening.

The only way that is working is to put all the env variables inside the Jenkinsfile like this:

env.INTERCOM_APP_ID = '12312' env.INTERCOM_PERSONAL_ACCESS_TOKEN = '1231' env.INTERCOM_IDENTITY_VERIFICATION_KEY='asadfas' 

But I don't think this is a good way of doing it.

What is the correct way of setting env variables in Jenkins?

3
  • Are you using Amazon Linux AMI? Commented Jul 19, 2018 at 4:22
  • @TalhaJunaid No, I am using GCP compute instance. Commented Jul 19, 2018 at 4:23
  • Previously I faced this issue using Amazon Linux AMI it flushes out the environment variables after a restart. Commented Jul 19, 2018 at 4:24

2 Answers 2

2

To me, it seems very normal. INTERCOM_PERSONAL_ACCESS_TOKEN and INTERCOM_IDENTITY_VERIFICATION_KEY should be considered as text credentials and you can use the environment directive to add environment variables.

stages { stage('Example') { environment { INTERCOM_APP_ID = '12312' INTERCOM_PERSONAL_ACCESS_TOKEN = credentials('TokenCrednetialsID') INTERCOM_IDENTITY_VERIFICATION_KEY = credentials('VerificationCrednetialsID') } steps { echo "Hello ${env.INTERCOM_APP_ID}" } } } 

If you need to keep environment variables separate from JenkinsFile you can create a groovy file which contains all of those and then load that file into Jenkinsfile using

load "$JENKINS_HOME/.envvars/stacktest-staging.groovy" 

For more information take a look at following links

https://jenkins.io/doc/pipeline/steps/workflow-cps/

SO: Load file with environment variables ...

Sign up to request clarification or add additional context in comments.

3 Comments

I don't think this is a good solution because I have lots of env variables, not just three. I don't want them to occupy most of my Jenkinsfile
Setting Jenkins specific environment variables at the system level is dangerous as it contains secret texts as well. You can create a groovy file which contains and load that into jenkinsFile. Please take a look at stackoverflow.com/a/39178479/3358570. to learn how to do that.
Yup. That's what I needed. If you add it to your answer, I will accept it. Thank you.
0

Jenkins resets environment variables to some defaults for their jobs. Best way to set them is in jenkins configuration. You can set global vars, local for project or local for node.

Now i do not remember if this feature is build in or provided by some plugin.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.