Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Terraform watch a directory for changes?

Tags:

I want to monitor a directory of files, and if one of them changes, to re-upload and run some other tasks. My previous solution involved monitoring the individual files, but this is error-prone as some files may be forgotten:

resource "null_resource" "deploy_files" {    
  triggers = {
    file1 = "${sha1(file("my-dir/file1"))}"
    file2 = "${sha1(file("my-dir/file2"))}"
    file3 = "${sha1(file("my-dir/file3"))}"
    # have I forgotten one?
  }

  # Copy files then run a remote script.
  provisioner "file" { ... }
  provisioner "remote-exec: { ... }
}

My next solution is to take a hash of the directory structure in one resource, and use this hash as a trigger in the second:

resource "null_resource" "watch_dir" {
  triggers = {
    always = "${uuid()}"
  }

  provisioner "local-exec" {
    command = "find my-dir  -type f -print0 | xargs -0 sha1sum | sha1sum > mydir-checksum"
  }
}


resource "null_resource" "deploy_files" {    
  triggers = {
    file1 = "${sha1(file("mydir-checksum"))}"
  }

  # Copy files then run a remote script.
  provisioner "file" { ... }
  provisioner "remote-exec: { ... }
}

This works okay, except changes to mydir-checksum are only picked up after the first apply. So I need to apply twice, which isn't great. It's a bit of a kludge.

I can't see a more obvious way to monitor an entire directory for changes in content. Is there a standard way to do this?

like image 795
Joe Avatar asked Jul 02 '18 14:07

Joe


People also ask

What is .TF file in Terraform?

»File Extension Code in the Terraform language is stored in plain text files with the . tf file extension. There is also a JSON-based variant of the language that is named with the .

What is the .Terraform folder?

The . terraform directory is a local cache where Terraform retains some files it will need for subsequent operations against this configuration. Its contents are not intended to be included in version control.

Does Terraform run all TF files?

Terraform will find all the tf. -files, merge them and then executes.


1 Answers

You can use the "archive_file" data source:

data "archive_file" "init" {
  type        = "zip"
  source_dir = "data/"
  output_path = "data.zip"
}

resource "null_resource" "provision-builder" {
  triggers = {
    src_hash = "${data.archive_file.init.output_sha}"
  }

  provisioner "local-exec" {
    command = "echo Touché"
  }
}

The null resource will be reprovisioned if and only if the hash of the archive has changed. The archive will be rebuilt during refresh whenever the contents of source_dir (in this example data/) change.

like image 176
krlmlr Avatar answered Sep 19 '22 12:09

krlmlr