use timestamp for null resource local exec

Viewed 641

I want to perform the exec operation only once per hour. Meaning, if it's now 12 then don't exec again until it's 13 o'clock.

The timestamp in combination with the fomatdate will result in timestamps that only differ every hour.

resource "null_resource" "helm_login" {
  triggers = {
    hour = formatdate("YYYYMMDDhh", timestamp())
  }
  provisioner "local-exec" {
    command = <<-EOF
      az acr login -n ${var.helm_chart_acr_fqdn} -t -o tsv --query accessToken \
        | helm registry login ${var.helm_chart_acr_fqdn} \
          -u "00000000-0000-0000-0000-000000000000" \
          --password-stdin
    EOF
  }

The problem is that terraform reports that this value will be only known after appy and always wants to recreate the resource.

  # module.k8s.null_resource.helm_login must be replaced
-/+ resource "null_resource" "helm_login" {
      ~ id       = "4503742218368236410" -> (known after apply)
      ~ triggers = {
          - "hour" = "2021112010"
        } -> (known after apply) # forces replacement
    }

I have observed similar issues where values are fetched from data and passed to resources on creation, forcing me to not use those data values but hard code them.

1 Answers

As you just find out terraform evaluates the timestamp function at runtime,
that is why we see the: (known after apply) # forces replacement

But we can do something about that to meet your goal, we can pass the hour as a parameter:

variable "hour" {
  type = number
}

resource "null_resource" "test" {
  triggers = {
    hour = var.hour
  }
  provisioner "local-exec" {
    command = "echo 'test'"
  }
}

Then to call terraform we do:
hour=$(date +%G%m%d%H); sudo terraform apply -var="hour=$hour"


First run:

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # null_resource.test will be created
  + resource "null_resource" "test" {
      + id       = (known after apply)
      + triggers = {
          + "hour" = "2021112011"
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

null_resource.test: Creating...
null_resource.test: Provisioning with 'local-exec'...
null_resource.test (local-exec): Executing: ["/bin/sh" "-c" "echo 'test'"]
null_resource.test (local-exec): test
null_resource.test: Creation complete after 0s [id=6793564729560967989]

Second run:

null_resource.test: Refreshing state... [id=6793564729560967989]

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Related