DEV Community

sgrilux
sgrilux

Posted on • Originally published at blog.sgrilux.com on

Tagging with terraform

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 lets 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
}

Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

Thats it, easy peasy!

I hope you have enjoyed itsee you on the next post.

CIAO!

Here for more information about aws_ec2_tag

Top comments (0)