Adding default tags to AWS resources with Terraform


If you’ve worked with the various cloud providers, you’ve probably realized the value that comes with tagging resources. For billing and searching, I like to create a default set of tags that are applied to every resource. These include the group that owns the resource, the application type, and one or more operational tags. To keep things DRY, I keep a tags.tf file with entries similar to the following:

variable "default_ec2_tags" {
  description = "Default set of tags to apply to EC2 instances"
  type        = map
  default = {
    Environment = "Production"
    SupportTeam = "PlatformEngineering"
    Contact     = "group@example.com"
  }
}

This file then becomes a one-stop-shop for defining tags that apply to everything in a project. When I create resources, I use merge to combine the defaults with resource specific tags:

resource "aws_instance" "nodes" {
  count                       = var.kafka_broker_count
  ami                         = var.kafka_ami_image
  instance_type               = var.kafka_instance_type
  vpc_security_group_ids      = [var.kafka_security_group_list]
  availability_zone           = element(var.availability_zones, count.index)
  associate_public_ip_address = var.associate_public_ip == true ? true : false
  subnet_id                   = element(aws_subnet.public-subnet.*.id, count.index)
  tags                        = { for k, v in merge({ "Name" = "Kafka-Broker-${format("%02d", count.index)}" },var.default_ec2_tags) : k => v }
}

This will produce a union of both, resulting in the following plan output:

$ terraform plan

+ tags                         = {
    + "Environment" = "Production"
    + "Name"        = "Kafka-Broker-01"
    + "SupportTeam" = "PlatformEngineering"
    + "Contact"     = "group@example.com"

This has proven to be super useful, though it took me some time to get the tags just right. When you are trying to track down a billing issue, or locate an application owner in a sea of resources, tags will quickly become your best friend.

This article was posted by on 2020-04-29 00:00:00 -0500 -0500