CI/CD / 系统课时
在流水线中临时注入凭据
在流水线中临时注入凭据
流水线需要访问镜像仓库、制品库或外部 API 时,不应把用户名、密码和令牌直接写进 Jenkinsfile。更安全的做法是由 Jenkins 保存凭据,只在真正需要秘密的步骤中注入环境变量,并在作用域结束后撤销绑定。
学习目标
- 使用
credentials和withCredentials将 Jenkins 凭据注入流水线 - 控制凭据暴露范围,避免秘密进入 Jenkinsfile、日志和长期环境变量
- 验证凭据只在指定作用域内可用
用 credentials 绑定阶段级凭据
Declarative Pipeline 的 environment 可以调用 credentials()。对于 Username with password 类型凭据,指定变量除了保存 用户名:密码 组合值,还会派生 _USR 和 _PSW 两个变量。
下面假设 Jenkins 中已经创建 ID 为 registry-login 的 Username with password 凭据。凭据只绑定到 Publish 阶段,而不是整个流水线。
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'echo "build without registry credentials"'
}
}
stage('Publish') {
environment {
REGISTRY_AUTH = credentials('registry-login')
}
steps {
sh '''
test -n "$REGISTRY_AUTH_USR"
test -n "$REGISTRY_AUTH_PSW"
echo "registry credentials are available in Publish"
'''
}
}
}
}预期输出
build without registry credentials
registry credentials are available in Publish这里没有打印秘密本身。REGISTRY_AUTH_USR 与 REGISTRY_AUTH_PSW 的实际内容由 Jenkins 凭据决定,因此验证时只检查变量是否存在。
用 withCredentials 缩小暴露范围
如果一个阶段只有一条命令需要秘密,withCredentials 更适合。它把绑定限制在代码块内部,代码块结束后 Jenkins 会撤销对应环境变量。
下面使用 Credentials Binding 提供的 usernamePassword 绑定。Shell 脚本使用单引号形式交给 sh,让 $REGISTRY_USER 和 $REGISTRY_PASSWORD 在执行节点的 Shell 中展开,而不是先由 Groovy 插值秘密。
pipeline {
agent any
stages {
stage('Authenticate') {
steps {
withCredentials([usernamePassword(
credentialsId: 'registry-login',
usernameVariable: 'REGISTRY_USER',
passwordVariable: 'REGISTRY_PASSWORD'
)]) {
sh '''
test -n "$REGISTRY_USER"
test -n "$REGISTRY_PASSWORD"
echo "temporary credentials are available"
'''
}
sh '''
test -z "${REGISTRY_PASSWORD:-}"
echo "credential binding has ended"
'''
}
}
}
}预期输出
temporary credentials are available
credential binding has ended第二个 sh 已位于 withCredentials 外,因此密码变量应为空。这个边界比在流水线顶层长期声明秘密更容易审计,也减少了无关步骤接触凭据的机会。
避免秘密进入日志
Jenkins 会尝试对已绑定秘密进行日志掩码,但掩码不是把日志当成安全存储的理由。脚本仍应避免 echo 密码、令牌或完整认证头,也不要开启会打印命令展开结果的调试模式。
凭据 ID 可以安全地保存在 Jenkinsfile 中,因为它只是 Jenkins 内部引用;真正的用户名、密码和令牌应继续由 Jenkins 凭据存储管理。实际调用外部系统时,还应根据目标工具选择不会把秘密暴露在命令输出或进程参数中的认证方式。
选择合适的注入范围
当同一阶段的多个步骤都需要凭据时,可以使用阶段级 environment;只有少量操作需要秘密时,优先使用 withCredentials。两种方式的关键原则相同:凭据只在必要时间、必要步骤中出现,并且流水线永远不保存秘密明文。