Contents

How to always run local-exec with Terraform

Contents

To ensure that a certain terraform local-exec script runs consistently, you can use a null_resource in conjunction with a timestamp. This way, each time you execute terraform apply - either to the entire project or to a specific resource - the state of the null resource will be invalidated, triggering the local-exec script.

Here’s an example of how this can be done, in the context of building a local docker image:

1
2
3
4
5
6
7
8
resource "null_resource" "docker_build" {
  triggers = {
    always_run = "${timestamp()}"
  }
  provisioner "local-exec" {
    command = "docker build -t ${var.image_name}:${var.image_tag} ./path-to-docker-file-Folder"
    }
}

So now, whenever you run:

1
terraform apply

To invalidate previous state, you can utilize the trigger block definition in conjunction with a variable referencing the terraform timestamp method. This ensures that the state is always invalidated with each apply or targeted execution.

And that’s all there is to it! We hope this information was useful.

Thank you for reading!