Problem
When using the timestamp() function directly within a resource's tags argument, it can overwrite other tags, such as default tags applied by a provider or module. This happens because assigning a new map to tags replaces the existing map entirely rather than merging with it.
Solution
To dynamically add a timestamp to tags without overwriting existing tags, you can define the timestamp and other dynamic values in a locals block and then use the merge() function to combine them with other tag variables.
This approach ensures that all sets of tags are correctly combined into a single map.
Procedure
This example demonstrates how to use locals with the timestamp() and merge() functions to combine a base set of tags with dynamically generated tags.
-
Define Local Values: In a
localsblock, create a map for your dynamic tags. This example includesLastModifiedTimeusingtimestamp()andLastModifiedByusing a data source. -
Merge Tags: Use the
merge()function to combine the dynamic tags fromlocal.computed_tagswith your base tags fromvar.extra_tags. -
Apply Merged Tags: You can then assign
local.merged_tagsto thetagsargument of any resource.
This is the complete example configuration.
provider "aws" {
region = "us-west-2"
}
variable "extra_tags" {
type = map(any)
default = {
Enviroment = "tags-test-env"
}
}
data "aws_caller_identity" "current" {}
locals {
computed_tags = {
LastModifiedTime = timestamp()
LastModifiedBy = data.aws_caller_identity.current.arn
}
merged_tags = merge(local.computed_tags, var.extra_tags)
}
output "merged_tags_output" {
value = local.merged_tags
}Example Output
After applying this configuration, the output shows that the tags have been successfully merged.
Changes to Outputs:
+ merged_tags_output = {
+ "Enviroment" = "tags-test-env"
+ "LastModifiedBy" = "arn:aws:sts::ACCOUNT_ID:assumed-role/ROLE_NAME/USERNAME"
+ "LastModifiedTime" = "2023-10-27T10:00:00Z"
}Additional Information
For more details on the functions and concepts used in this guide, refer to the official Terraform documentation.