skip to Main Content

I have applied the code for tagging AWS ec2 instances in Terraform, when the code runs it only created singe TAG.
How can we add multiple TAGs e.g

  1. It add Auto creation DATE.
  2. It add Auto OS detection (like it is windows or linux)

Please see TAG detail in Screenshot

Gurus, your kind support will be highly appreciated.

I have added the following code for Tagging.

# Block for create EC2 Instance
resource "aws_instance" "ec2" {
  count                  = var.instance_count
  ami                    = "ami-005835d578c62050d"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [var.security_group_id]
  subnet_id              = var.subnet_id
  key_name               = var.key
  **tags = {
    Name = "${var.name}-${count.index + 1}"**
  }
}

2

Answers


  1. You can add other tags by simply adding to your Tags, For example:

      tags = {
        Name = "${var.name}-${count.index + 1}"
        CreationDate = timestamp()
        OS           = "Linux"
      }
    
    Login or Signup to reply.
  2. tags attribute accepts a map of strings and you can also use terraform functions like merge to merge default tags if available in your used case with custom resource-specific tags.

    # Block for create EC2 Instance
    resource "aws_instance" "ec2" {
      count                  = var.instance_count
      ami                    = "ami-005835d578c62050d"
      instance_type          = "t2.micro"
      vpc_security_group_ids = [var.security_group_id]
      subnet_id              = var.subnet_id
      key_name               = var.key
      tags = merge(var.default_ec2_tags,
        {
          Name = "${var.name}-${count.index + 1}"
        }
      )
    }
    
    variable "default_ec2_tags" {
      type = map(string)
      description = "(optional) default tags for ec2 instances"
      default = {
        managed_by = "terraform"
        environment = "dev"
      }
    }
    
    

    Something very specific to terraform-aws-provider and a very handy feature is default_tags which you can configure on the provider level and these tags will be applied to all resources managed by the provider.

    Click to view Tutorial from hashicorp on default-tags-in-the-terraform-aws-provider

    It’s not possible to get the OS type tag natively as mentioned by @Marcin already in the comments.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search