首页 > 解决方案 > 如何在 Jenkins 控制台中屏蔽变量,以避免泄露我的令牌?

问题描述

在我的 Jenkins 管道中,我将withCredentials插件作为一个函数,这样我就可以传递变量来检索不同的秘密并让我的舞台管道干净。下面是我的代码。

def getCredentialsString(dsl, credentialsId) {
    def r;
    dsl.withCredentials([string(credentialsId: credentialsId, variable: 'CredentialsString')]) {
        r = "${env.CredentialsString}"
    }
    return r
}

阶段管道,my-jenkins-token并且my-jenkins-api-token是 jenkins 中用于存储我的 API 令牌的秘密。我隐藏了必要的命令并显示如下。

def project_token = credentials.getCredentialsString(this, "my-jenkins-token")
def api_token = credentials.getCredentialsString(this, "my-jenkins-api-token")

sh "mvn -Dsettings.security=${mavenSecuritySetting} -DprojectToken=${project_token} -DapiToken=${api_token} -Dcommit=${COMMIT_ID} -s ${mavenSetting}"

问题是,如果我选择分离withCredentials,令牌将打印为纯文本,我想知道一种掩盖变量的方法。只要它有助于屏蔽控制台中的输出,我就可以将变量设为 ENV 变量。

标签: jenkinsgroovy

解决方案


获取withCredentils块外秘密的值违背了安全存储秘密的目的。如果您拥有动态范围的凭据,我建议您使用以下方法。

node('master'){
    Map creds= [slack_token: 'Slack', aws_token: 'AWS'] // key is the local variable and value is the credentialsId from jenkins store
    runWithCredentials(creds){
        echo "${slack_token} and ${aws_token}"
    }
}

def runWithCredentials(Map credentials, def body){
    List credBlock = []
    credentials.each {credValue, credId ->
        credBlock.add(string(credentialsId: credId, variable: credValue))
    }
    withCredentials(credBlock){
        body()
    }
}

推荐阅读