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

Image of Bright Data

High-Quality Data for AI – Access diverse datasets ready for your ML models.

Browse our extensive library of pre-collected datasets tailored for various AI and ML projects.

Explore Datasets

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay