添加凭证

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

文章来源

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。