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

问题描述 投票:0回答:6

我有一个具有多个阶段的 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}"
                }
            }
        }""";
    }
}

但是(像我这样的菜鸟)那是行不通的。那么,设置具有凭据的全局可访问变量但只需声明一次的最佳方法是什么?

jenkins groovy jenkins-pipeline credentials
6个回答
15
投票

您可以使用

credentials
部分的
environment
辅助方法。对于“用户名和密码”类型的凭据,它分配 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}"
          }
      }
  }"""
}

了解更多


14
投票

经过大量搜索(和挣扎),我想出了一个简单的解决方法:

正如 jenkins 文档中针对 Handling Credentials 的更好解释,当将 usernamePassword 类型凭证注入名为 VAR_NAME 的环境变量时,jenkins 会自动为 usernameVariable 生成分别以 _USR_PSW 结尾的另外两个变量passwordVariable 参数。

我所做的是将 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}"
            }
        }
    }""";
}

8
投票

以下是实现这一目标的方法

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

6
投票

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

1
投票

您可能需要处理插件尚不支持的多字段凭据或特定于供应商的凭据类型。

在这种情况下,您有几个选择:

  1. 使用符合您要求的最接近的标准多字段凭据(例如用户名和密码)。
  2. 使用字符串凭证,将所有字段序列化为秘密值(例如,作为 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"
}

阅读更多1

阅读更多2


0
投票

这是完成任务的简单方法:

pipeline {
    agent any    
    stages {
        
        stage('Hello') {
            steps {
                echo 'Hello World'
            }
        }
        stage('Test Python') {
            steps {
                sh 'python3 --version'
            }
        }
        stage('Test H DUT') {
            
            steps {
                sh 'pwd'
                sh 'ls'
                script {
                    withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'sfbk',usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
                        sh 'python3 test_h_file.py $USERNAME $PASSWORD'
                    }
                }
              
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.