timcrall
timcrall

Reputation: 75

How can I make groovy on Jenkins mask the output of a variable the same way it does for credentials?

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?

Upvotes: 4

Views: 4214

Answers (1)

fredericrous
fredericrous

Reputation: 3038

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

Upvotes: 4

Related Questions