Tagging with terraform

Tagging with terraform

·

1 min read

We all know that when we share a resource in AWS with a different account, tags are not shared alongside the resource. Tags are account based so you need to assign tags to the other account as well.

Terraform comes to help with aws_ec2_tag which allows us to tag indivvidual resources that are created outside Terraform.

So let’s jump directly to an example.

You have a networking account with a VPC that you are sharing with your production account. You want to Name your VPC with the same name that has been given in the networking account.

first you need to collect VPC data (using a provider that connects to the networking account)

data "aws_vpc" "selected" {
  filter {
    name   = "tag:Environment"
    values = ["production"]
  }

  provider = aws.central-networking
}

then, with a production provider, you can tag your VPC

resource "aws_ec2_tag" "my_prod_vpc" {
  resource_id = data.aws_vpc.selected.id
  key         = "Name"
  value       = data.aws_vpc.selected.tags.Name

  provider = aws.production
}

You can also use for_each to assign multiple tags to the same resource:

resource "aws_ec2_tag" "my_prod_vpc" {
  for_each = local.tags

  resource_id = data.aws_vpc.selected.id
  key         = each.key
  value       = each.value
}

That’s it, easy peasy!

I hope you have enjoyed it…see you on the next post.

CIAO!

Here for more information about aws_ec2_tag