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?
How can I make groovy on Jenkins mask the output of a variable the same way it does for credentials?
Asked
Active
Viewed 3,493 times
1 Answers
4
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

fredericrous
- 2,833
- 1
- 25
- 26
-
This doesn't do quite what I need. I need the variable to retain its actual value for use in the script, but to mask any and all occurrences of it in the console output - just as it does for values drawn from the credentials manager. – timcrall Jan 10 '20 at 15:12
-
The question title was clear but the question itself not so much, sorry I did not understand exactly what was the question about. I updated my solution – fredericrous Jan 13 '20 at 12:14