首页 > 解决方案 > 在每个计划(刷新状态)terraform 上重新运行外部数据源的“程序”

问题描述

我正在使用外部数据源来使用程序参数执行 cURL 命令:

data "external" "curl_zip" {
    program = ["bash", "-c", "curl", ...]
}

我在管道中运行 Terraform,所以我需要检索每个 terraform 计划的数据。

在我创建一个需要执行 curl 的新资源之前,它似乎运行良好。但看起来 Terraform 只是在刷新,所以在第一个计划之后不执行程序命令:

data.external.curl_zip["something.json"]: Refreshing state... [id=-]

我的问题是:即使在刷新期间,有没有办法在每个计划上重新运行程序参数?

PS:我已经尝试使用 anull_resource而不是 a local-exec,结果不是这里的解决方案,因为(出于某种原因)我还需要使用 archive_file 数据源来创建 zips 文件,以便我的 GCP 应用程序引擎资源可以读取它们,并且正在local-exec应用 terraform 之后执行,这不起作用,因为在计划期间正在刷新或创建数据源。

标签: google-cloud-platformterraformterraform-provider-gcp

解决方案


在我看来,你把事情复杂化了。你到底想达到什么目的?对于 Terraform 的所有事情,通常how can I achieve so and so?比问好how can I get my Terraform code to work?

以下是你所追求的吗?

data "external" "hello" {
    program = ["bash", "-c", "echo 'Hello World!' > helloworld.txt; echo -n '{\"hello\":\"world!\"}'"]
}

resource "null_resource" "world" {
  provisioner "local-exec" {
    command = "echo '${data.external.hello.result["hello"]}'"
  }
}

从以下输出中的时间戳可以看出,helloworld.txt它被生成五次,每次Terraform调用计划一次:

jdsalaro$ for i in {1..5} ;do terraform plan; ls -lah --full-time helloworld.txt ;done \
| grep helloworld.txt | cut -d ' ' -f 7,9

00:04:18.610304219 helloworld.txt
00:04:19.902246088 helloworld.txt
00:04:21.226186506 helloworld.txt
00:04:22.574125835 helloworld.txt
00:04:23.886066774 helloworld.txt

为了以防万一,我在这里上传了整个示例。


推荐阅读