Home How to always run local-exec with Terraform
Post
Cancel

How to always run local-exec with Terraform

Sometimes there is a need to always run some terraform local-exec, so we can always execute a null_resource when doing an apply or applying it as a target.

So, how can you make sure to invalidate state for the null resource, so it always runs the local-exec script.

Using timestamp.

The following example always builds a docker image locally, when running both terraform apply generically to the *.tf file, or when targeting the resource directly.

1
2
3
4
5
6
7
8
9
10
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

Or

1
terraform apply -target=null_resource.docker_build

The state will be invalid given the trigger block definition, with a variable that points to terraform’s timestamp method invocation that will invalidate previous state.

And that’s it.

Thank you for reading, hope it has been helpful.

This post is licensed under CC BY 4.0 by the author.