在 Terraform 中多次执行相同的资源

Executing same resource multiple times in Terraform

我需要在我的 Terraform 代码中多次 运行 local-exec

resource "null_resource" "test_1" {
  provisioner "local-exec" {
    command = "python test.py"
  }
  triggers = {
    always_run = "${timestamp()}"
  }
}

resource "null_resource" "test_2" {
  depends_on =[null_resource.test]
  provisioner "local-exec" {
    command = "python run.py"
  }

    triggers = {
    always_run = "${timestamp()}"
  }

}

resource "null_resource" "test_3" {
  depends_on = [null_resource.test_2]
  provisioner "local-exec" {
    command = "python test.py"
  }
  triggers = {
    always_run = "${timestamp()}"
  }
}

正如我们在上面的代码中看到的,test_1test_3 我们正在调用同一个 python 文件。但我需要明确地调用它。有什么办法可以简化吗?就像我们在命令式编码中所做的那样,我们在其中调用 like 函数。

我们都知道这里的问题,我们需要多次编写同一行代码,如果有更改,我需要确保所有地方都需要更改。

对于 python test.py 的情况,只需使用局部变量:

locals {
    code_to_run = "python test.py"
}

resource "null_resource" "test_1" {
  provisioner "local-exec" {
    command = local.code_to_run
  }
  triggers = {
    always_run = "${timestamp()}"
  }
}

resource "null_resource" "test_2" {
  depends_on =[null_resource.test]
  provisioner "local-exec" {
    command = "python run.py"
  }

    triggers = {
    always_run = "${timestamp()}"
  }

}

resource "null_resource" "test_3" {
  depends_on = [null_resource.test_2]
  provisioner "local-exec" {
    command = local.code_to_run
  }
  triggers = {
    always_run = "${timestamp()}"
  }
}

对于更复杂的代码,请使用 templatefile 将代码放入 参数化模板:

resource "null_resource" "test_1" {
  provisioner "local-exec" {
    command = templatefile("code_to_run.tmpl", {some_parmeter = "test_1"})
  }
  triggers = {
    always_run = "${timestamp()}"
  }
}

resource "null_resource" "test_2" {
  depends_on =[null_resource.test]
  provisioner "local-exec" {
    command = templatefile("code_to_run.tmpl", {some_parmeter = "test_2"})
  }

    triggers = {
    always_run = "${timestamp()}"
  }

}

resource "null_resource" "test_3" {
  depends_on = [null_resource.test_2]
  provisioner "local-exec" {
    command = templatefile("code_to_run.tmpl", {some_parmeter = "test_3"})
  }
  triggers = {
    always_run = "${timestamp()}"
  }
}