terraform: Refresh null_resource when a variable changes

2 min read

When using local-exec with the null_resource we might need to be able to update the resources that gets created like this. Let's assume we have the following terraform code to apply Kustomize to a kubernetes cluster:

resource "null_resource" "metrics-server" {
  provisioner "local-exec" {
    command = "kubectl apply -k 'https://github.com/jordiprats/django-ampa/deploy-${var.version}/'"
  }
}

Given this setup even though the var.version changed, the resource won't be updated if it was already applied

To be able to tell terraform that this resource need to be replaced we can use triggers: It is a map of arbitrary strings, so we can have multiple triggers for the same resource:

resource "null_resource" "metrics-server" {
  provisioner "local-exec" {
    command = "kubectl apply -k 'https://github.com/jordiprats/django-ampa/deploy-${var.version}/'"
  }
  triggers = {
    version = var.version
  }
}

Using this code, every time the var.version string changes, it will force the replacement of this resource, actually triggering the update using the kubectl apply:

  # module.setup.null_resource.metrics-server must be replaced
-/+ resource "null_resource" "metrics-server" {
      ~ id       = "7340063792707087874" -> (known after apply)
      ~ triggers = { # forces replacement
          ~ "version" = "v1" -> "v2"
        }
    }

Posted on 08/03/2021