问题描述
在 Jenkins 的 groovy 中是否有一种方法可以获取任意字符串变量——比如对另一个服务的 API 调用的结果——并让 Jenkins 在控制台输出中将其屏蔽,就像它自动为从凭据管理器读取的值所做的那样?
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?
推荐答案
更新解决方案:要隐藏变量的输出,您可以使用 Mask Password Plugin
UPDATED SOLUTION:To hide the output of a variable you can use the Mask Password Plugin
这是一个例子:
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+密码+插件
正则表达式解决方案的原始答案:
ORIGINAL ANSWER with regex solution:
假设你想隐藏一个包含在引号之间的密码,下面的代码会输出 My password is "****"
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
您需要将 a-z0-9
替换为密码中允许的字符模式
you need to replace a-z0-9
by the pattern of allowed characters in your password
这篇关于如何在 Jenkins 上制作 groovy 以与凭据相同的方式屏蔽变量的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!