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"
}
}
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”.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With