Terraform 无法将模块作为 jenkins 管道的一部分拉取
·
问题:Terraform 无法将模块作为 jenkins 管道的一部分拉取
我有一个可以使用 terraform 自动部署一些基础设施的 jenkinsfile。不幸的是,在使用 git 源添加 terraform 模块后,它停止工作并出现以下错误:
+ terraform init -input=false -upgrade
Upgrading modules...
- module.logstash
Updating source "git::https://bitbucket.org/*****"
Error downloading modules: Error loading modules: error downloading 'https://bitbucket.org/*****': /usr/bin/git exited with 128: Cloning into '.terraform/modules/34024e811e7ce0e58ceae615c545a1f8'...
fatal: could not read Username for 'https://bitbucket.org': No such device or address
script returned exit code 1
上面的网址在事后被混淆了。以下是精简的模块语法:
module "logstash" {
source = "git::https://bitbucket.org/******"
...
}
下面是詹金斯文件:
pipeline {
agent {
label 'linux'
}
triggers {
pollSCM('*/5 * * * *')
}
stages {
stage ('init') {
steps {
sh 'terraform init -input=false -upgrade'
}
}
stage('validate') {
steps {
sh 'terraform validate -var-file="production.tfvars"'
}
}
stage('deploy') {
when {
branch 'master'
}
steps {
sh 'terraform apply -auto-approve -input=false -var-file=production.tfvars'
}
}
}
}
我认为这是内部使用 git 检出模块的 terraform 的问题,但 Jenkins 尚未在管道作业本身中配置 git 客户端。最好我能够以某种方式将多分支管道作业使用的凭据传递到作业本身并配置 git,但我不知道如何做到这一点。任何帮助,将不胜感激。
解答
所以我找到了一个不理想的解决方案,它要求您在 Jenkinsfile 中指定凭据,而不是自动使用作业使用的凭据进行结帐。
withCredentials([usernamePassword(credentialsId: 'bitbucketcreds', passwordVariable: 'GIT_PASS', usernameVariable: 'GIT_USER')]) {
sh "git config --global credential.helper '!f() { sleep 1; echo \"username=${env.GIT_USER}\\npassword=${env.GIT_PASS}\"; }; f'"
sh 'terraform init -input=false -upgrade'
sh 'git config --global --remove-section credential'
}
诀窍是使用withCredentials
块将凭据加载到环境变量中,然后我使用这个问题的答案来设置 git 的凭据帮助程序以读取这些凭据。然后你可以运行terraform init
它会拉下你的模块。最后,它会清除修改后的 git 设置,以避免污染其他构建。请注意,这里的--global
配置对于大多数人来说可能不是一个好主意,但由于我们的 Jenkins 代理的一个怪癖,我需要它。
如果有人有更顺畅的方式来做到这一点,我会非常有兴趣听到它。
更多推荐
所有评论(0)