简体   繁体   English

Jenkins:在全局环境部分使用 withCredentials

[英]Jenkins : use withCredentials in global environment section

I have a Jenkins pipeline with multiple stages that all require the same environment variables, I run this like so:我有一个包含多个阶段的 Jenkins 管道,这些阶段都需要相同的环境变量,我这样运行:

script {
    withCredentials([usernamePassword(credentialsId: 'COMPOSER_REPO_MAGENTO', passwordVariable: 'MAGE_REPO_PASS', usernameVariable: 'MAGE_REPO_USER')]) {
        def composerAuth = """{
            "http-basic": {
                "repo.magento.com": {
                    "username": "${MAGE_REPO_USER}",
                    "password": "${MAGE_REPO_PASS}"
                }
            }
        }""";
        // do some stuff here that uses composerAuth
    }
}

I don't want to have to re-declare composerAuth every time, so I want to store the credentials in a global variable, so I can do something like:我不想每次都重新声明composerAuth ,所以我想将凭据存储在全局变量中,所以我可以执行以下操作:

script {
    // do some stuff here that uses global set composerAuth
}

I've tried putting it in the environment section:我试过把它放在环境部分:

environment {
    DOCKER_IMAGE_NAME = "magento2_website_sibo"
    withCredentials([usernamePassword(credentialsId: 'COMPOSER_REPO_MAGENTO', passwordVariable: 'MAGE_REPO_PASS', usernameVariable: 'MAGE_REPO_USER')]) {
        COMPOSER_AUTH = """{
            "http-basic": {
                "repo.magento.com": {
                    "username": "${MAGE_REPO_USER}",
                    "password": "${MAGE_REPO_PASS}"
                }
            }
        }""";
    }
}

But (groovy noob as I am) that doesn't work.但是(像我这样的groovy noob)那行不通。 So what's the best approach on setting a globally accessible variable with credentials but only have to declare it once?那么使用凭据设置全局可访问变量但只需声明一次的最佳方法是什么?

You can use credentials helper method of the environment section.您可以使用environment部分的credentials帮助器方法。 For "Username and passwrd" type of credentials it assigns 2 additional environment variables.对于“用户名和密码”类型的凭据,它分配了 2 个额外的环境变量。 Example:例子:

environment {
  MAGE_REPO_CREDENTIALS = credentials('COMPOSER_REPO_MAGENTO')
  COMPOSER_AUTH = """{
      "http-basic": {
          "repo.magento.com": {
              "username": "${env.MAGE_REPO_CREDENTIALS_USR}",
              "password": "${env.MAGE_REPO_CREDENTIALS_PSW}"
          }
      }
  }"""
}

Read more阅读更多

After a lot of search (and struggle), i came up with an easy workaround:经过大量搜索(和挣扎),我想出了一个简单的解决方法:

As better explained in the jenkins docs for Handling Credentials , when injecting a usernamePassword type credential into an environment variable named VAR_NAME , jenkins automatically generates two other variables ending with _USR and _PSW respectively for usernameVariable and passwordVariable parameters.正如在处理凭证的詹金斯文档中更好地解释的那样,当将usernamePassword类型的凭证注入名为VAR_NAME的环境变量时,詹金斯会自动为usernameVariablepasswordVariable参数分别生成另外两个以_USR_PSW结尾的变量。

What i did was to inject my variables with the values from both USR and PSW new variables.我所做的是将来自 USR 和 PSW 新变量的值注入我的变量。

In @Giel Berkers case, it should be something like this:在@Giel Berkers 的情况下,它应该是这样的:

environment {
    DOCKER_IMAGE_NAME = "magento2_website_sibo"
    COMPOSER_REPO_MAGENTO_CREDENTIAL = credentials('COMPOSER_REPO_MAGENTO')
    COMPOSER_AUTH = """{
        "http-basic": {
            "repo.magento.com": {
                "username": "${COMPOSER_REPO_MAGENTO_CREDENTIAL_USR}",
                "password": "${COMPOSER_REPO_MAGENTO_CREDENTIAL_PSW}"
            }
        }
    }""";
}

Here is how you can accomplish that以下是您如何做到这一点

pipeline {
    agent any
    stages {
        stage('first') {
            steps {
                script {
                    withCredentials([usernamePassword(credentialsId: 'COMPOSER_REPO_MAGENTO', passwordVariable: 'MAGE_REPO_PASS', usernameVariable: 'MAGE_REPO_USER')]) {
                        def user = env.MAGE_REPO_USER
                        def password = env.MAGE_REPO_PASS
                        //Initializing a global variable. Notice there is no def here 
                        composerAuth = """{
                            "http-basic": {
                                "repo.magento.com": {
                                    "username": "${user}",
                                    "password": "${password}"
                                }
                            }
                        }"""
                    }
                }
            }
        }
        stage('second') {
            steps {
                script {
                    println composerAuth
                }
            }
        }
    }
}

I found this and it is helpful: Source: https://wiki.jenkins.io/display/JENKINS/Credentials+Binding+Plugin我发现这很有帮助:来源: https ://wiki.jenkins.io/display/JENKINS/Credentials+Binding+Plugin

   // Basic example
withCredentials([usernamePassword(credentialsId: 'amazon',
                     usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
    //available as an env variable, but will be masked if you try to print it out any which way
    sh 'echo $PASSWORD'
    echo "${env.USERNAME}"
}

// You can also request multiple credentials in a single call
withCredentials([usernamePassword(credentialsId: 'amazon',
                     usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD'),
                 string(credentialsId: 'slack-url',
                     variable: 'SLACK_URL'),]) {
    sh 'echo $PASSWORD'
    echo "${env.SLACK_URL}"
}

// Older code might not use the new syntax (usernamePassword, string, ...) yet, and directly call the class:
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'amazon',
                  usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
    //available as an env variable, but will be masked if you try to print it out any which way
    sh 'echo $PASSWORD'
    echo "${env.USERNAME}"
}

You may need to deal with multi-field credentials or vendor-specific credential types that the plugin does not (yet) support.您可能需要处理插件(尚)不支持的多字段凭据或特定于供应商的凭据类型。

In this situation you have a couple of choices:在这种情况下,您有两种选择:

  1. Use the closest standard multi-field credential (eg Username With Password) that fits your requirements.使用最接近您要求的标准多字段凭据(例如,带有密码的用户名)。
  2. Use a string credential, serialize all the fields into the secret value (eg as JSON or as a delimited string), and parse them in the job script.使用字符串凭证,将所有字段序列化为秘密值(例如,作为 JSON 或作为分隔字符串),并在作业脚本中解析它们。 (This is a last resort when other methods don't work, eg when secret rotation would cause multiple fields to change.) (当其他方法不起作用时,这是最后的手段,例如,当秘密轮换会导致多个字段发生变化时。)

Example: Jenkins authenticates to Secrets Manager using the primary AWS credential (from the environment).示例:Jenkins 使用主要 AWS 凭证(来自环境)向 Secrets Manager 进行身份验证。 You have a job that performs a particular AWS operation in a different account, which uses a secondary AWS credential.您有一个在不同账户中执行特定 AWS 操作的作业,该账户使用辅助 AWS 凭证。 You choose to encode the secondary AWS credential as JSON in the string credential foo:您选择在字符串凭证 foo 中将辅助 AWS 凭证编码为 JSON:

node {
    withCredentials([string(credentialsId: 'foo', variable: 'secret')]) {
        script {
            def creds = readJSON text: secret
            env.AWS_ACCESS_KEY_ID = creds['accessKeyId']
            env.AWS_SECRET_ACCESS_KEY = creds['secretAccessKey']
            env.AWS_REGION = 'us-east-1' // or whatever
        }
        sh "aws sts get-caller-identity" // or whatever
    }
}

A typical example of a username password type credential (example from here) would look like:用户名密码类型凭据的典型示例(来自此处的示例)如下所示:

withCredentials([usernamePassword(credentialsId: 'amazon', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
  // available as an env variable, but will be masked if you try to print it out any which way
  // note: single quotes prevent Groovy interpolation; expansion is by Bourne Shell, which is what you want
  sh 'echo $PASSWORD'
  // also available as a Groovy variable
  echo USERNAME
  // or inside double quotes for string interpolation
  echo "username is $USERNAME"
}

ReadMore1 阅读更多1

ReadMore2阅读更多2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM