如何根据 Jenkins 声明式管道中的参数使用不同的私有 docker 代理? [英] How can I use different private docker agents based on parameter in Jenkins declarative pipeline?
问题描述
我正在尝试根据 Jenkins 管道中的参数从私有容器注册表中选择不同的 docker 代理.对于我的示例,假设我在凭据存储中保存了credsProd"和credsTest".我的尝试如下:
I am trying to choose a different docker agent from a private container registry based on an a parameter in Jenkins pipeline. For my example let's say I have 'credsProd' and 'credsTest' saved in the credentials store. My attempt is as follows:
pipeline {
parameters {
choice(
name: 'registrySelection',
choices: ['TEST', 'PROD'],
description: 'Is this a deployment to STAGING or PRODUCTION environment?'
)
}
environment {
URL_VAR = "${env.registrySelection == "PROD" ? "urlProd.azure.io" : "urlTest.azure.io"}"
CREDS_VAR = "${env.registrySelection == "PROD" ? "credsProd" : "credsTest"}"
}
agent {
docker {
image "${env.URL_VAR}/image:tag"
registryUrl "https://${env.URL_VAR}"
registryCredentialsId "${env.CREDS_VAR}"
}
}
stages{
stage('test'){
steps{
echo "${env.URL_VAR}"
echo "${env.CREDS_VAR}"
}
}
}
}
出现错误:来自守护进程的错误响应:Get https://null/v2/: dial tcp: lookup null on
如果我对 registryUrl 进行硬编码,我会遇到与 registryCredentialsId 类似的问题:
If I hard code the registryUrl I get a similar issue with registryCredentialsId:
agent {
docker {
image "${env.URL_VAR}/image:tag"
registryUrl "https://urlTest.azure.io"
registryCredentialsId "${env.CREDS_VAR}"
}
}
错误:找不到匹配空值的凭据
如果我对 registryUrl 和 registryCredentialsId 进行硬编码,则成功.
It is successful if I hardcode both registryUrl and registryCredentialsId.
agent {
docker {
image "${env.URL_VAR}/image:tag"
registryUrl "https://urlTest.azure.io"
registryCredentialsId "credsTest"
}
}
agent{docker{}}
的 docker 登录阶段似乎无法访问/解析环境变量.
It appears that the docker login stage of the agent{docker{}}
cannot access/resolve environment variables.
有没有不涉及代码重复的方法来解决这个问题?我使用多分支管道管理更改,因此理想情况下不希望在同一文件中有单独的 Prod 和测试 groovy 文件或不同的连续步骤集.
Is there a way around this that does not involve code duplication? I manage changes with multi branch pipeline so ideally do not want to have separate Prod and test groovy files or different sets sequential steps in the same file.
推荐答案
尝试在声明之前运行脚本管道:
Try running a scripted pipeline before declarative:
URL_VAR = null
CREDS_VAR = null
node('master') {
stage('Choose') {
URL_VAR = params.registrySelection == "PROD" ? "urlProd.azure.io" : "urlTest.azure.io"
CREDS_VAR = params.registrySelection == "PROD" ? "credsProd" : "credsTest"
}
}
pipeline {
agent {
docker {
image "${URL_VAR}/image:tag"
registryUrl "https://${URL_VAR}"
registryCredentialsId "${CREDS_VAR}"
}
}
...
或者,您可以定义两个阶段(使用硬编码的 url 和 creds)但只运行其中一个阶段,并在两者中使用 when
.
Alternatively, you can define two stages (with hard-coded url and creds) but run only one of them, using when
in both.
这篇关于如何根据 Jenkins 声明式管道中的参数使用不同的私有 docker 代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!