如何让Atlantis自动生成并提交Terraform local_file配置文件?
问题描述
使用Terraform的resource "local_file"生成应用配置文件,本地执行terraform apply可正常生成,相关代码示例如下:
# local_file.helm_values creates a set of helm values for this environment resource "local_file" "helm_values" { file_permission = "0666" filename = "config.yaml" content = <<EOT ${yamlencode({ endpoints = [ { name = "servicename" command = "command" path = "/path" env = { REDIS_URL = "redis://redishost:port" } }, { name = "servicename2" command = "docs" path = "/" } ] ... })} EOT }
集成Atlantis后,通过PR执行atlantis plan和atlantis apply时,其他基础设施资源可正常管理,但修改上述local_file资源后,无法自动重新生成配置文件并提交到PR,需解决该问题。
解决方案
方案1:调整Atlantis工作目录与Git提交配置
- 确保Atlantis运行的工作目录是Git仓库根目录,让生成的
config.yaml处于仓库范围内 - 在Atlantis的
apply阶段后添加自定义脚本,当local_file资源执行完成后,自动将文件加入Git暂存区并推送到PR分支,示例脚本可放在atlantis.yaml或自定义workflow中:
注意:需给Atlantis运行账号配置对应Git仓库的推送权限if [ -f config.yaml ]; then git add config.yaml git commit -m "chore: auto-update config.yaml via Atlantis" git push origin HEAD:<PR分支名> fi
方案2:用local-exec结合Git命令自动提交
修改local_file资源,添加provisioner "local-exec",在文件生成或更新后自动执行Git提交:
resource "local_file" "helm_values" { file_permission = "0666" filename = "config.yaml" content = <<EOT ${yamlencode({ endpoints = [ { name = "servicename" command = "command" path = "/path" env = { REDIS_URL = "redis://redishost:port" } }, { name = "servicename2" command = "docs" path = "/" } ] ... })} EOT provisioner "local-exec" { command = <<EOT git add config.yaml git commit -m "chore: update config.yaml via Terraform" git push origin HEAD EOT when = "update" on_failure = "continue" } }
- 需确保Atlantis运行环境的Git已配置好用户名、邮箱,且拥有仓库推送权限
when = "update"可覆盖文件更新场景,若需要创建时也执行,可改为when = "create"或移除该参数
方案3:改用Terraform输出+Atlantis自定义工作流
放弃local_file资源,改用Terraform输出配置内容,再通过Atlantis工作流写入文件并提交:
- 定义输出:
output "helm_values" { value = yamlencode({ endpoints = [ { name = "servicename" command = "command" path = "/path" env = { REDIS_URL = "redis://redishost:port" } }, { name = "servicename2" command = "docs" path = "/" } ] ... }) }
- 在
atlantis.yaml中配置自定义工作流:
workflows: generate-config: plan: steps: - run: terraform plan -out=tfplan apply: steps: - run: terraform apply tfplan - run: terraform output -raw helm_values > config.yaml - run: | git add config.yaml git commit -m "chore: auto-generate config.yaml" git pull --rebase origin <PR分支名> git push origin HEAD
关键注意事项
- 确保Atlantis运行账号拥有Git仓库读写权限,避免推送失败
- 提交时的commit信息需清晰,便于追踪变更来源
- 多人协作场景下,脚本中可添加
git pull --rebase逻辑处理潜在的Git冲突
内容的提问来源于stack exchange,提问作者Amit Upadhyay
相关产品推荐
相关产品推荐

