0

I am trying to run a python script in my Jenkins job that relies on Jenkins environment variables that have been set earlier. The environment variables are set in my Jenkinsfile and when I echo them they are there.

But my python script fails when I try to access those variables with os.environ["VARIABLE"].

This is how it is being set in my python script:
svn_branch = os.environ["SVN_BRANCH"]

And it fails with this error as though it can't find that variable:

  File "c:\jenkins\workspace\test_jenkins_build.py", line 68, in <module>
    svn_branch = os.environ["SVN_BRANCH"]
  File "C:\Users\build\AppData\Local\Programs\Python\Python39\lib\os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'SVN_BRANCH'

Is there a way to have a python script access Jenkins environment variables? Thank you for any and all help!

1
  • Does the solution I provided work for you Commented May 28, 2021 at 14:37

1 Answer 1

3

Please see below example: Jenkinsfile

stage('stage 1') {
              steps {
           script {
           dir ("C:\\python-workspace\\"){
               def result
               // Set your environment variable
               env.SVN_BRANCH= "app"
               result = bat label: 'Execute python script..', returnStatus: true, script: "hello.py "
              }
           }         
         }
   }

Python script:

#!/usr/bin/python
import os
branch=os.environ['SVN_BRANCH']
print (branch)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @Altaf, that did work. The issue was that I wasn't setting my variables in jenkins with env., simply var=VAR, but I needed env.var=VAR. I'm still not totally sure of the difference between regular environment variables and ones set with env. but that worked. Thanks so much for the help.
Thanks @buffcat , if this worked then can you accept the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.