Search code examples
terraformterraform0.12+infrastructure-as-codeterraform-template-file

Executing same resource multiple times in Terraform


I need to run a local-exec multiple times in my Terraform code.

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

As we can see in the above code, test_1 and test_3 we are calling the same python file. But I need to explicitly call it. Is there any way to simplify? Like how we do in the imperative coding, where we call the like function.

As we all know the problem here, we need to write the same line of code multiple times and if there is a change, I need to make sure need to change it in all places.


Solution

  • For your case with python test.py just use local variable:

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

    For more complex code, use templatefile where you put code in parametrized template:

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