Terraform: LastUpdated Tag

less than 1 minute read

Description:

Quick post about how you can use the timestamp, timeadd, and formatdate functions in Terraform to set localized times for tagging your resources. More details from this post, example below.

To Resolve:

  1. The following locals block will build a string that will look like: 2022-10-15-09:10 AM PST for example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    locals {
       now     = timestamp()
       pst_tz  = timeadd(local.now, "-7h")
       time    = formatdate("YYYY-MM-DD-HH:mm AA", local.pst_tz)
       created = join(" ", [local.time, "PST"])
       tags = {
             Owner       = "Automation Admin"
             CostCenter  = "100"
             EntAppname  = "Automation Admin Terraform POC"
             Environment = "tst"
             Contact     = "gerry@automationadmin.com"
             Latest_RunBy  = "${var.requested_for} - ${var.requested_for_email}"
             LastUpdated     = local.created
       }
    }
    
  2. The main problem with this is everytime you run your pipeline it will update that tag. While it’s pretty obvious you want the LastUpdated tag to be the last time an object was touched, there may be better solutions out there like querying Microsoft Graph Explorer for last time a resource was updated. But maybe you can use these time functions for other things so will still keep this in mind.