如何在 jenkins 文件中将 jenkins 用户名和密码加载为环境变量

Sim*_*ate 3 jenkins jenkins-pipeline

在 Jenkins 凭证中,我有几种类型的凭证。其中之一称为my_password“秘密文本”类型,在 Jenkinsfile 中,我可以像这样访问:

    environment {
        my_env_var = credentials('my_password')
    }
Run Code Online (Sandbox Code Playgroud)

现在,我创建了一个名为“用户名和密码”类型的凭证,user_and_pass在其中我可以在同一凭证中设置两个字段。如何同时访问两个参数并将它们加载到环境变量中?我在想这样的事情:

    environment {
        my_user = credentials('user_and_pass').someFunctionThatReturnsUser()
        my_pass = credentials('user_and_pass').someFunctionThatReturnsPass()

    }
Run Code Online (Sandbox Code Playgroud)

但我不认为它是这样工作的。

mdr*_*ich 5

据我所知,我们有两种方法从凭证类型中提取数据Username and Password

  1. 通过 Groovy 函数withCredentials()
  2. 通过帮手的方式credentials()

withCredentials()

通过以下方式提取信用的语法withCredentials

withCredentials([usernamePassword(credentialsId: 'your-credentials-id', passwordVariable: 'PASSWORD_VAR', usernameVariable: 'USERNAME')]) {
    // your script could access $PASSWORD_VAR and $USERNAME_VAR
    // as environment variables
    //
    // note: PASSWORD_VAR, USERNAME_VAR is just aliases, you may change it to whatever you like
}
Run Code Online (Sandbox Code Playgroud)

如果语法对您来说太复杂和无聊,请使用管道片段生成器,如下所示

证书()

通过以下方式提取信用的语法credentials()

environment {
    CREDS = credentials('your-credentials-id')
}
steps {
    // your code can access 
    // username as $CREDS_USR
    // and password as $CREDS_PSW
}
Run Code Online (Sandbox Code Playgroud)

使用哪种方法?

这取决于凭证类型。因为Username and Password您可以根据需要使用任何方法。

credentials()helper 支持以下类型(2022 年底):

  • 秘密文字
  • 用户名和密码;
  • 秘密文件

对于其余的凭据类型,您必须使用withCredentials().

查看官方文档了解更多详细信息。