terraform - Terraform:depends_on 参数不首先创建指定的资源
问题描述
我想将 terraform 状态文件推送到 github 存储库。Terraform 中的文件功能无法读取 .tfstate 文件,因此我需要先将其扩展名更改为 .txt。现在为了自动化它,我创建了一个空资源,它有一个配置程序来运行命令以将 tfstate 文件复制为同一目录中的 txt 文件。我遇到了这个“depends_on”参数,它可以让你指定在运行当前资源之前是否需要先制作特定资源。但是,它不起作用,当文件功能需要它时,我立即收到“terraform.txt”文件不退出的错误。
provider "github" {
token = "TOKEN"
owner = "USERNAME"
}
resource "null_resource" "tfstate_to_txt" {
provisioner "local-exec" {
command = "copy terraform.tfstate terraform.txt"
}
}
resource "github_repository_file" "state_push" {
repository = "TerraformStates"
file = "terraform.tfstate"
content = file("terraform.txt")
depends_on = [null_resource.tfstate_to_txt]
}
解决方案
该file
函数的文档解释了这种行为:
此功能只能用于在 Terraform 运行开始时磁盘上已存在的文件。函数不参与依赖关系图,因此此函数不能与 Terraform 操作期间动态生成的文件一起使用。我们不建议在 Terraform 配置中使用动态本地文件,但在极少数情况下,您可以使用数据
local_file
源读取文件,同时尊重资源依赖关系。
本段还包括有关如何获得所需结果的建议:使用来自providerlocal_file
的数据源将hashicorp/local
文件作为资源操作(在应用阶段)读取,而不是作为配置加载的一部分:
resource "null_resource" "tfstate_to_txt" {
triggers = {
source_file = "terraform.tfstate"
dest_file = "terraform.txt"
}
provisioner "local-exec" {
command = "copy ${self.triggers.source_file} ${self.triggers.dest_file}"
}
}
data "local_file" "state" {
filename = null_resource.tfstate_to_txt.triggers.dest_file
}
resource "github_repository_file" "state_push" {
repository = "TerraformStates"
file = "terraform.tfstate"
content = data.local_file.state.content
}
请注意,尽管上面应该得到您询问的操作顺序,但terraform.tfstate
在 Terraform 运行时读取文件是一件非常不寻常的事情,并且可能导致未定义的行为,因为 Terraform 可以在整个过程中在不可预测的时刻重复更新该文件terraform apply
.
如果您的意图是让 Terraform 将状态保存在远程系统而不是本地磁盘上,通常的实现方式是配置remote state,这将导致 Terraform仅远程保存状态,而不使用本地terraform.tfstate
文件一点也不。
推荐阅读
- c# - 如何在 Startup 类中使用或解析服务(或依赖项)
- silverstripe - Silverstripe 4,如何解决映射到同一个数据库表的数据库表冲突
- c# - 有没有办法告诉 Visual Studio 在 .Net Core 解决方案中仅使用特定类型的引用?
- html - 如何使用“ng-show”切换错误消息,仅在文本区域达到其最大长度时显示?
- mongodb - 如何使用 mongodb 在 lambda 函数中获得组合输出?
- .net-core - @User.Identity.Name 在 Mac 上为空
- spring-integration - Spring Integration - 使用 http-outbound gateway (POST) 发送类型为“application/x-www-form-urlencoded”的表单参数
- javascript - Scaling mouse drawings elements on a html canvas
- twilio - 获取带有 twilio 会议参与者 sid 的电话号码
- java - React 和 Freemarker 集成