mystack
mystack

Reputation: 5492

Terraform local-exec to pass new resource( not hard-coding)

I'm executing a bash script using terraform. My null_resource configuration code is given below

resource "null_resource" "mytest" {

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

 provisioner "local-exec" {
  command = "sh test.sh"

 }
 }

Let us take git repo as an example resource. I'm doing bunch of operations using the batch script on the resource. This resource names are passed using terraform.tfvars

resource_list = ["RS1","RS2","RS3","RS4"]

If I want to add a new repo named RS5 then I can update the the above list by adding RS5 to it.

How I will pass the new resource name to the batch script. Here I'm not looking to hard code the parameter as given below

sh test.sh "RS5"

How i will pass the most recent resource to the batch script?

Upvotes: 0

Views: 1756

Answers (1)

pkatsourakis
pkatsourakis

Reputation: 1082

Use for_each to execute the batch script once per resource in the resource_list variable

resource "null_resource" "mytest" {
  for_each = toset(var.resource_list)

  # using timestamp() will cause the script to run again for every value on 
  # every run since the value changes every time. 
  # you probably don't want that behavior.

  # triggers = {
  #  run = "${timestamp()}"
  # }

  provisioner "local-exec" {
    command = "sh test.sh ${each.value}"
  }
}

When you run this the first time it will execute the script once for each of the resources in resource_list. Then the terraform state file will be updated to know what has already run, so any subsequent runs will only include new items added to resource_list.

Upvotes: 1

Related Questions