Terraform Learnings

2020-10-08

A key feature of using Terraform is idempotency of Infrastructure as Code.
Use of depends_on pointed at a data source can result resources being redeployed. Today I solved a problem where this principal was a bit less intuitive, had the same effect. The module I was using leveraged a null_resource to execute a local command when a config file changed. The triggers block referenced a external data source to calculate the md5 checksum of the config file. Fortunately, I was able to solve the problem buy replacing the external data source with the native filemd5() terraform function. In my case, I was utilizing this module with for_each looping through a large map of objects. With every terraform apply, all resources associated config files would redeploy rendering the triggers block useless.

Before:

data "external" "configuration" {
  # get md5 checksum of config file and return it to terraform { “md5”: “hash result here” }
}

resource "null_resource" "something_changed" {
  triggers = {
    config_file = data.external.configuration.result.md5
  }

  provisioner "local-exec" {
    # do something if config file has changed 
  }
}

After:

resource "null_resource" "something_changed" {
  triggers = {
    config_file = filemd5(“${path.module}/file.conf”)
  }

  provisioner "local-exec" {
    # do something if config file has changed 
  }
}

In conclusion, terraform data sources are invaluable, however require extra careful placement within terraform code to avoid undesirable redeployment results.

Reference: https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source#example-usage https://registry.terraform.io/providers/hashicorp/null/latest/docs/resources/resource

comments powered by Disqus