问题
Is there a way in groovy on Jenkins to take an arbitrary String variable - say the result of an API call to another service - and make Jenkins mask it in console output as it does automatically for values read in from the Credentials Manager?
回答1:
UPDATED SOLUTION: To hide the output of a variable you can use the Mask Password Plugin
Here is an exemple:
String myPassword = 'toto'
node {
println "my password is displayed: ${myPassword}"
wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[password: "${myPassword}", var: 'PASSWORD']]]) {
println "my password is hidden by stars: ${myPassword}"
sh 'echo "my password wont display: ${myPassword}"'
sh "echo ${myPassword} > iCanUseHiddenPassword.txt"
}
// password was indeed saved into txt file
sh 'cat iCanUseHiddenPassword.txt'
}
https://wiki.jenkins.io/display/JENKINS/Mask+Passwords+Plugin
ORIGINAL ANSWER with regex solution:
Let's say you want to hide a password contained between quotes, the following code will output My password is "****"
import java.util.regex.Pattern
String myInput = 'My password is "password1"'
def regex = Pattern.compile( /(?<=\")[a-z0-9]+(?=\")/, Pattern.DOTALL);
def matchList = myInput =~ regex
matchList.each { m ->
myInput = myInput.replaceAll( m, '****')
}
println myInput
you need to replace a-z0-9
by the pattern of allowed characters in your password
来源:https://stackoverflow.com/questions/59669608/how-can-i-male-groovy-on-jenkins-mask-the-output-of-a-variable-the-same-way-it-d