Skip to content

Instantly share code, notes, and snippets.

@marcelaraujo
Forked from docwhat/Jenkinsfile
Created February 9, 2021 12:14
Show Gist options
  • Save marcelaraujo/2aad2b99f65676d13fbd74d389560a7b to your computer and use it in GitHub Desktop.
Save marcelaraujo/2aad2b99f65676d13fbd74d389560a7b to your computer and use it in GitHub Desktop.
Example pipeline usage of the Jenkins Mask Passwords plugin
// Requires https://plugins.jenkins.io/mask-passwords to run
/**
* Runs code with secret environment variables and hides the values.
*
* @param varAndPasswordList - A list of Maps with a 'var' and 'password' key. Example: `[[var: 'TOKEN', password: 'sekret']]`
* @param Closure - The code to run in
* @return {void}
*/
def withSecretEnv(List<Map> varAndPasswordList, Closure closure) {
wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: varAndPasswordList]) {
withEnv(varAndPasswordList.collect { "${it.var}=${it.password}" }) {
closure()
}
}
}
// Example code:
node {
withSecretEnv([[var: 'VAULT_TOKEN', password: 'toosekret']]) {
sh '''#!/bin/bash -eu
echo "with env use: ${VAULT_TOKEN}"
sleep 1
echo "without env use: toosekret"
sleep 1
echo "just the var name: VAULT_TOKEN"
'''
sleep 1
echo "Outside SH: VAULT_TOKEN=${VAULT_TOKEN}"
}
}
// Example output:
'''
[Pipeline] node
Running on magic-agent in /a/workspace/with-secret-env
[Pipeline] {
[Pipeline] wrap
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] sh
[with-secret-env] Running shell script
with env use: ********
without env use: ********
just the var name: VAULT_TOKEN
[Pipeline] sleep
Sleeping for 1 sec
[Pipeline] echo
Outside SH: VAULT_TOKEN=********
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // wrap
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment