Conditionally triggering of Terraform local_exec provisioner based on local_file changes

Viewed 1314

I'm using terraform 0.14 and have 2 resources, one is a local_file that creates a file on the local machine based on a variable and the other is a null_resource with a local_exec provisioner.

This all works as intended but I can only get it to either always run the provisioner (using an always-changing trigger, like timestamp()) or only run it once. Now I'd like to get it to run every time (and only when) the local_file actually changes.

Does anybody know how I can set a trigger that changes when the local_file content has changed? e.g. a last-updated-timestamp or maybe a checksum value?

resource "local_file" "foo" {
  content  = var.foobar
  filename = "/tmp/foobar.txt"
}

resource "null_resource" "null" {
  triggers = {
    always_run = timestamp() # this will always run
  }

  provisioner "local-exec" {
    command = "/tmp/somescript.py"
  }
}
1 Answers

You can try using file hash to indicate its change:

resource "null_resource" "null" {
  triggers = {
    file_changed = md5(local_file.foo.content)
  }

  provisioner "local-exec" {
    command = "/tmp/somescript.py"
  }
}
Related