Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a tag to AWS EBS when creating through EC2 with Terraform?

I'm trying to create an EC2 instance for a TEST environment, which uses an AMI of PROD. Everything is creating correctly, but I can't add figure out how to add tags to the EBS volumes that are created along with it?

The tags work on the EC2 but don't get applied to the EBS or root volume. I tried adding a tag map on those as well but that was invalid. Any ideas?

provider "aws" {
  region = "us-east-1"
}

data "aws_ami" "existing_sft_ami" {
  most_recent = true

  filter {
    name   = "name"
    values = [var.prod_name]
  }
  owners = [
    var.aws_account_id]
}

data "aws_subnet" "subnet" {
  id = var.aws_subnet_id
}

resource "aws_instance" "sftp" {
  ami           = data.aws_ami.existing_sft_ami.id
  instance_type = "t2.micro"
  availability_zone = var.availability_zone
  subnet_id = data.aws_subnet.subnet.id
  key_name = var.ssh_key_name
  vpc_security_group_ids = [var.aws_security_group_id]
  root_block_device {
    delete_on_termination = true
  }
  ebs_block_device {
    device_name = "/dev/sdb"
    delete_on_termination = true
  }
  tags = {
    Name = var.name
    Owner = var.owner
    Created = formatdate("DD MMM YYYY hh:mm ZZZ", timestamp())
    Environment = "TEST"
  }
}
like image 305
John Avatar asked Jun 19 '20 12:06

John


People also ask

How do I add a tag in Terraform?

Tagging resources using Terraform is very simple – add a tags block to your resource with a tag name and value. The following example will create an S3 bucket with a Name tag of “My bucket” and an Environment tag of “Development”.

How do you add existing key pairs to EC2 instance Terraform?

If you want to attach a key to an EC2 instance while you create it using terraform, you need to first create a key on AWS console, download the . pem file and copy the Key pair name to the clip board. Terraform script requires the correct key name to associate it to the ec2 instance.


1 Answers

You need to use the additional volume_tags argument to tag the volumes. Also, to make your code a little more DRY, you can do this with a locals block.

locals {
    tags = {
        Name = var.name
        Owner = var.owner
        Created = formatdate("DD MMM YYYY hh:mm ZZZ", timestamp())
        Environment = var.environment
    }
}

resource "aws_instance" "sftp" {
  ami           = data.aws_ami.existing_sft_ami.id
  instance_type = "t2.micro"
  availability_zone = var.availability_zone
  subnet_id = data.aws_subnet.subnet.id
  key_name = var.ssh_key_name
  vpc_security_group_ids = [var.aws_security_group_id]
  root_block_device {
    delete_on_termination = true
  }
  ebs_block_device {
    device_name = "/dev/sdb"
    delete_on_termination = true
  }
  tags = local.tags
  volume_tags = local.tags
}

like image 92
Ben Whaley Avatar answered Oct 02 '22 06:10

Ben Whaley