Skip to content

Instantly share code, notes, and snippets.

@alekpopovic
Forked from ju4nlu/JenkinsSecrets.md
Created October 11, 2023 10:01
Show Gist options
  • Save alekpopovic/18b4e03f430cc0e1b9e6644683cfb50a to your computer and use it in GitHub Desktop.
Save alekpopovic/18b4e03f430cc0e1b9e6644683cfb50a to your computer and use it in GitHub Desktop.
Using Jenkins Secrets and embedding them in a pipeline

1. Add new Secret to Jenkins Credentials

First of all we need to add the secret to the Jenkins Credentials management system. To do so, navigate through the menus to section

Jenkins > Credentials > System > Global credentials (unrestricted) > Add credentials

Then select the kind of secret that you need and specify its value. See an example in the next image:

Adding a new secret to Jenkins

2. Using the secret in a Pipeline

It's important to know that this example uses a Jenkins declarative pipeline. To load the contents of the secret we just need to use the function credentials(name_of_secret). Then, it can be assigned to any variable that can be used later on any stage. Here is an example below where we use a secret to handle a Codacy token of a Python project:

pipeline{
    agent any
    environment {
        CODACY_TOKEN = credentials('etl-pipelines-codacy-token')
        ...
    }
    stages{

    	...

    	stage("Execute codacy"){
            steps{
                sh "export CODACY_PROJECT_TOKEN=${CODACY_TOKEN};python-codacy-coverage -r coverage.xml"
            }
        }

        ...
        
    }
}

There you go, now you are correctly injection secrets to your Jenkins pipelines!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment