首页 > 解决方案 > 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]
}

标签: terraform

解决方案


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文件一点也不。


推荐阅读