This article will talk about The easiest way to define AWS Tag in your Terraform code. Tags are the most valuable and straightforward feature of the AWS Cloud. It allows us to label our resources, giving them any Key and Value for them, and we can attach tags to almost any resource within the Cloud.
Recently, I created a Terraform Module that helps my team create and assign Tag for any resources we want to add. But unfortunately, that module got complex over time to support several scenarios.
However, I suddenly found a new solution that makes our life easier.
The easiest way to define AWS Tag in your Terraform Code.
There is a feature with Terraform with AWS Provider (v3.38.0 or later) and Terraform 0.12 or later that allows us to declare default tags. So, for example, using the provider block, we can define the tags that will add to any resource that Terraform will create for this code. So, we don’t need to manually specify each Tag for each resource within your code and module.
Let’s see one example of how to define default tags on Terraform for AWS provider:
provider "aws" {
default_tags {
tags = {
Environment = "Prod"
Owner = "Bits Lovers"
Goal = "Biggest Blog about DevOps"
}
}
}
resource "aws_s3_bucket" "my-bucket" {
bucket = "my-for-tags-example"
acl = "private"
versioning {
enabled = true
}
}
resource "aws_ecs_cluster" "bits-cluster" {
name = "Bits-Lovers"
setting {
name = "containerInsights"
value = "enabled"
}
}
So, all resources. The Terraform will create the S3 Bucket and EKS Cluster and assign the tags: Environment, Owner, and Goal automatically, and you don’t need to specify them manually.
Define Default Tags for Auto Scaling Group
According to Hashicorp and AWS, the only resource that cannot use the default tag approach is the Auto Scaling Group. But you can do it using another method, described below:
Create a Terraform variable with the default tag and then merge that into the Auto Scaling group.
variable "my_tags" {
default = {
Environment = "Prod"
Owner = "Bits Lovers"
Goal = "Biggest Blog about DevOps"
}
description = "Tags for Auto Scaling Group"
type = map(string)
}
resource "aws_autoscaling_group" "bits-asg" {
availability_zones = ["us-east-1a"]
desired_capacity = 1
max_size = 1
min_size = 1
launch_template {
id = aws_launch_template.foobar.id
version = "$Latest"
}
tags = merge(
var.default_tags,
{
Name = "Bits ASG"
},
)
}
Conclusion
This article’s tiny, but the idea is to help you save time and still reach a best practice, defining the tags to your resources.