HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Passing a jenkins credential (global) to a python script

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
scriptglobaljenkinspassingcredentialpython

Problem

I have a global jenkins credential and a config script that includes the line

API_TOKEN = "Token XXX"


For security reasons we can't keep the token in the script itself as its in version control. Is there a way to pass the jenkins credential to the python config script from jenkins?

Solution

Specifically for credentials, CloudBees recommends using the Credentials Plugins, which inject the credentials in the environment available to the invoked scripts. From Injecting Secrets into Jenkins Build Jobs:



  • Credentials plugin - provides a centralized way to define credentials that can be used by your Jenkins instance, plugins and


build jobs.

  • Credentials Binding plugin - allows you to configure your build jobs to inject credentials as environment variables.



  • Plain Credentials plugin - a plugin dependency required by the Credentials Binding plugin.




Inside your script you'd pick up the variable from the script's environment:

API_TOKEN = os.getenv('API_TOKEN')


In a similar way you can pass any arbitrary variables (other than credentials), using the EnvInject Plugin (watch for the warnings, tho). See related:

  • Jenkins inject environment variable



  • Environment variables in Jenkins



Another possible approach is to configure Jenkins to pass the value as an argument to your script. Inside your script you'd pick up the value using your preferred method of processing the script arguments.

Code Snippets

API_TOKEN = os.getenv('API_TOKEN')

Context

StackExchange DevOps Q#4393, answer score: 6

Revisions (0)

No revisions yet.