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

前端 未结 1 579
臣服心动
臣服心动 2021-01-26 23:34

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 do

相关标签:
1条回答
  • 2021-01-26 23:37

    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

    0 讨论(0)
提交回复
热议问题