我想将 terraform 状态文件推送到 github 存储库。 Terraform 中的 file 函数无法读取 .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]
}
答案 0 :(得分:1)
depends_on
不适用于 null_resource.provisioner
。
这里有一个可以帮助您的解决方法:
resource "null_resource" "tfstate_to_txt" {
provisioner "local-exec" {
command = "copy terraform.tfstate terraform.txt"
}
}
resource "null_resource" "delay" {
provisioner "local-exec" {
command = "sleep 20"
}
triggers = {
"before" = null_resource.tfstate_to_txt.id
}
}
resource "github_repository_file" "state_push" {
repository = "TerraformStates"
file = "terraform.tfstate"
content = file("terraform.txt")
depends_on = ["null_resource.delay"]
}
如果复制命令需要更多时间,则延迟空资源将确保资源 2 在第一个之后运行,只需将睡眠更改为更高的数字
答案 1 :(得分:1)
The documentation for the file
function 解释了这种行为:
此函数只能用于在 Terraform 运行开始时磁盘上已存在的文件。函数不参与依赖关系图,因此此函数不能与 Terraform 操作期间动态生成的文件一起使用。我们不建议在 Terraform 配置中使用动态本地文件,但在极少数必要的情况下,您可以使用 the local_file
data source 读取文件,同时尊重资源依赖性。
这一段还包括一个关于如何得到你想要的结果的建议:使用 the hashicorp/local
provider 中的 local_file
数据源,将文件作为资源操作(在应用阶段)而不是而不是作为配置加载的一部分:
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 运行时读取 terraform.tfstate
文件是一件非常不寻常的事情,并且可能会导致未定义的行为,因为 Terraform 可以在整个 terraform apply
期间,在不可预测的时刻反复更新该文件。
如果您的目的是让 Terraform 将状态保存在远程系统中而不是本地磁盘上,通常的实现方法是配置 remote state,这将导致 Terraform 保持状态 仅远程使用,根本不使用本地 terraform.tfstate
文件。