Jenkins Pipeline 流水线 - withCredentials 使用

添加凭证

image
image
Pipeline script

pipeline {
    agent any
 
    stages {  
        stage('withCredentials 使用凭证') { 
            steps {
                withCredentials([usernamePassword(credentialsId: 'DockerServer', 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
                  bat 'echo ${USERNAME}' //Linux 下 sh 'echo $USERNAME',TODO Windows 上怎么写,

                  // also available as a Groovy variable
                  echo USERNAME

                 // or inside double quotes for string interpolation
                  echo "username is $USERNAME"
                }  
                echo 'Credentials SUCCESS'
            }
        }

        //指定 Docker 服务器节点。用于编译、上传镜像,指定K8S节点,用于升级程序
        stage('指定节点中使用凭证') { 
            agent { label 'DockerAgent' }
            steps {  
                withCredentials([usernamePassword(credentialsId: 'DockerServer', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {                 
                    sh 'docker --version' 
                    sh "echo 'docker login -u ${USERNAME} -p ${PASSWORD} image_url'"
                }  
                echo 'Credentials SUCCESS'
            }
        }
    }
}

执行结果

Started by user admin
[Pipeline] Start of Pipeline (hide)
[Pipeline] node
Running on Jenkins in D:\ProgramData\Jenkins\.jenkins\workspace\PipelineDemo
[Pipeline] {
[Pipeline] stage
[Pipeline] { (withCredentials 使用凭证)
[Pipeline] withCredentials
Masking supported pattern matches of %PASSWORD%
[Pipeline] {
[Pipeline] bat

D:\ProgramData\Jenkins\.jenkins\workspace\PipelineDemo>echo $PASSWORD 
$PASSWORD
[Pipeline] echo
root
[Pipeline] echo
username is root
[Pipeline] }
[Pipeline] // withCredentials
[Pipeline] echo
Credentials SUCCESS
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (指定节点中使用凭证)
[Pipeline] node
Running on DockerAgent in /opt/jenkins/workspace/PipelineDemo
[Pipeline] {
[Pipeline] withCredentials
Masking supported pattern matches of $PASSWORD
[Pipeline] {
[Pipeline] sh
+ docker --version
Docker version 20.10.18, build b40c2f6
[Pipeline] sh
Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.
		 Affected argument(s) used the following variable(s): [PASSWORD]
		 See https://jenkins.io/redirect/groovy-string-interpolation for details.
+ echo 'docker login -u root -p **** image_url'
docker login -u root -p **** image_url
[Pipeline] }
[Pipeline] // withCredentials
[Pipeline] echo
Credentials SUCCESS
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
posted @ 2022-11-02 09:44  VipSoft  阅读(2703)  评论(0编辑  收藏  举报