terraform 如何使用 time_sleep 资源正确实现延迟

Ale*_*kin 6 foreach delay terraform

terraform 创建的资源在创建后会消耗创建它的集群上的 CPU/RAM,因此在创建同一集群上的下一个资源之前需要某种延迟。

作为实现此目标的一个选项,决定使用 time_sleep terraform 资源在资源创建之前实现一些延迟。

还决定使用-parallelism=1,以便一一创建资源。

假设我们有一个模块(尽可能简单):

模块测试,main.tf

resource "time_sleep" "wait_3_seconds" {
  create_duration = "3s"
}

resource "null_resource" "topic_events" {
  triggers = {
    always_run = timestamp()
    topic = var.topic_name
  }
  depends_on = [time_sleep.wait_3_seconds]
}
Run Code Online (Sandbox Code Playgroud)

模块测试,变量.tf

variable topic_name {}
Run Code Online (Sandbox Code Playgroud)

主模块调用模块测试(见上文):

module "test" {
  for_each= tomap(var.environments[var.dim_arr].clusters.events.topics)
  source = "./test"
  topic_name = "${var.dim_arr}.${each.value.topic}"
}
Run Code Online (Sandbox Code Playgroud)

逻辑是输入值在循环中处理,但由于测试模块中的 time_sleep 资源,该循环中引入了一些延迟,这反过来又会减少服务器的负载。

然而 terraform 尝试在嵌套模块中创建所有 time_sleep 资源,然后遍历主模块中的对象并以这种方式创建它们:

a) 创建所有 time_sleep 资源

b) 创建所有依赖于它们的资源(参见 a))

有什么办法可以改变这个逻辑,以便

-创建使用睡眠时间的资源

-time_sleep资源导致延迟以减少集群上的负载

- 处理循环中的下一个对象

任何建议或想法表示赞赏。

谢谢。

Hel*_*eda 2

我发现的唯一方法是使用外部源来确定是否是运行的时间,如果不是,我们将等待,模块中的所有其他资源将必须依赖于此等待或依赖于等待的其他资源...

我这里有代码:
https ://github.com/heldersepu/hs-scripts/tree/master/TerraForm/sequential_wait

我们的想法是创建一个文件,该文件将为我们记录现在正在运行的人,其他人都在等待,我使用空资源创建该文件:

resource "null_resource" "set_initial_state" {
  provisioner "local-exec" {
    interpreter = ["bash", "-c"]
    command = "echo \"0\" > counter"
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的模块中我们检查该文件并等待:

resource "null_resource" "wait" {
  provisioner "local-exec" {
    interpreter = ["bash", "-c"]
    command = "while [[ $(cat counter) != \"${var.index}\" ]]; do sleep 5; done; sleep 3;"
  }
}
Run Code Online (Sandbox Code Playgroud)

这是一个的输出terraform apply

resource "null_resource" "set_initial_state" {
  provisioner "local-exec" {
    interpreter = ["bash", "-c"]
    command = "echo \"0\" > counter"
  }
}
Run Code Online (Sandbox Code Playgroud)