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

无人久伴 提交于 2021-02-17 03:59:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!