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

fumotvh3  于 2022-11-01  发布在  Jenkins
关注(0)|答案(5)|浏览(242)

我有一个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
    }
}

我不想每次都重新声明composerAuth,所以我想将凭据存储在一个全局变量中,这样我就可以执行如下操作:

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

我试着把它放在环境部分:

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}"
                }
            }
        }""";
    }
}

但是(像我这样的groovy noob)这是行不通的。那么,使用凭据设置一个全局可访问变量,但只需声明一次的最佳方法是什么呢?

sr4lhrrt

sr4lhrrt1#

您可以使用environment区段的credentials Helper方法。对于“Username and passwrd”类型的认证,它会指派2个额外的环境变量。范例:

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}"
          }
      }
  }"""
}

阅读更多信息

n7taea2i

n7taea2i2#

经过大量的搜索(和斗争),我想出了一个简单的变通办法:
正如jenkins文档中有关处理凭据的详细说明,当将usernamePassword类型的凭据注入名为VAR_NAME的环境变量时,jenkins会自动生成另外两个以**_USR_PSW结尾的变量,分别用于usernameVariablepasswordVariable**参数。
我所做的是将USR和PSW新变量的值注入到我的变量中。
在@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}"
            }
        }
    }""";
}
a9wyjsp7

a9wyjsp73#

以下是您可以实现这一点的方法

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
                }
            }
        }
    }
}
omjgkv6w

omjgkv6w4#

我发现了这个,它是有帮助的:来源: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}"
}
eanckbw9

eanckbw95#

您可能需要处理插件不支持的多字段凭据或特定于供应商的凭据类型。
在这种情况下,您有两种选择:
1.使用符合您要求的最接近的标准多字段凭据(例如,用户名和密码)。
1.使用字符串凭据,将所有字段序列化为机密值(例如,作为JSON或分隔字符串),并在作业脚本中解析它们。(当其他方法不起作用时,这是最后一种方法,例如,当机密轮转会导致多个字段更改时。)
示例:Jenkins使用主AWS凭据(来自环境)向Secrets Manager进行身份验证。您有一个在不同帐户中执行特定AWS操作的作业,该帐户使用辅助AWS凭据。您选择将辅助AWS凭据编码为字符串凭据foo中的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
    }
}

用户名密码类型凭据的典型示例(此处的示例)如下所示:

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
ReadMore2

相关问题