【问题标题】:Executing same resource multiple times in Terraform在 Terraform 中多次执行相同的资源
【发布时间】:2021-12-19 06:27:11
【问题描述】:

我需要在 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 函数。

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

【问题讨论】:

    标签: terraform terraform0.12+ infrastructure-as-code terraform-template-file


    【解决方案1】:

    对于 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()}"
      }
    }
    

    【讨论】:

    • 非常感谢您的回复!是的,这将是解决问题的一种方法。有什么办法,从 8 行追索权鳕鱼到 1 行?喜欢打电话test_1 ..只是问题
    • @Sreevathsabr 您可以围绕您的空资源创建一个模块。但这不会节省多少行。
    • 有没有可能放样品。对不起,如果我要求太多!
    • @Sreevathsabr 不确定是什么样本?如果这是新问题,我会推荐带有相关细节的新问题。
    猜你喜欢
    • 1970-01-01
    • 2022-08-10
    • 2018-07-09
    • 1970-01-01
    • 2019-12-14
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    相关资源
    最近更新 更多