Skip to content

Instantly share code, notes, and snippets.

@docwhat
Last active December 16, 2023 13:53
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save docwhat/21227d73501d3a30c99c150634e04024 to your computer and use it in GitHub Desktop.
Save docwhat/21227d73501d3a30c99c150634e04024 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
'''
@david-shepard
Copy link

david-shepard commented Jul 21, 2020

Good stuff, thanks for the example, the docs aren't too clear

@wladneto
Copy link

Great example!

@zhangguanzhang
Copy link

def pass="123456"
maskPasswords(varPasswordPairs: [[password: "${pass}"]]){
  sh "echo password is: ${pass}"
}

output:

password is: **********

or used var:

def pass="123456"
maskPasswords(varPasswordPairs: [[var: 'pass']]){
  sh "echo password is: ${pass}"
}

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