Issue
I have the below in my .tf file
provider "aws" {
region = "${var.aws_region}"
}
resource "aws_ebs_volume" "agent-xvdf" {
count = "${var.ec2_count}"
availability_zone = "${var.availability_zone}"
kms_key_id = "xxxx"
encrypted = "true"
size = "${var.vol_size_details_xvdf}"
type = "${var.vol_type_details}"
tags {
Name = "d-drive"
Owner = "${var.ebs_vol_owner}"
Managed_By = "Terraform"
}
}
resource "aws_instance" "my-ec2" {
depends_on = ["aws_ebs_volume.agent-xvdf"]
lifecycle {
ignore_changes = ["tags"]
create_before_destroy = true
}
count = "${var.ec2_count}"
ami = "${data.aws_ami.ami_id.id}"
iam_instance_profile = "yyyy"
instance_type = "${var.instance_type_details}"
tags {
Owner = "${var.instance_owner}"
ServerRole = "${var.server_details} ${var.ec2_os_flavour}"
Creator = "${var.creator_initials}"
Created = "TF Creation Time = ${timestamp()}"
}
vpc_security_group_ids =
["${data.aws_security_group.vpc_security_group_details.id}"]
#This is a template provider which exposes chef-cookbook roles during
bootstrapping process to manage instances or to install software
#In the below code snippet we have used "teamcity.chef.json" file to
mention Chef cookbook recipes to httpd and TeamCity.
user_data = "${file("..\\common\\${var.env_subfolder}\\teamcity.agent.chef.${var.app_instance}.json")}"
availability_zone = "${var.availability_zone}"
subnet_id = "${data.aws_subnet.subnet_id_details.id}"
# This parameter automatically deletes root-volume attached to the instance
when the instance is terminated.
root_block_device {
delete_on_termination = "true"
volume_size = "${var.vol_size_details_sda1}"
volume_type = "${var.vol_type_details}"
}
}
# Below resource will attach/detach "agent-xvdf" volume from AWS Instance i.e. {aws_instance.my-ec2}
resource "aws_volume_attachment" "agent-xvdf" {
depends_on = ["aws_ebs_volume.agent-xvdf"]
count = "${var.ec2_count}"
device_name = "xvdf"
volume_id = "${element(aws_ebs_volume.agent-xvdf.*.id,
count.index)}"
instance_id = "${element(aws_instance.my-ec2.*.id, count.index)}"
force_detach = "true"
skip_destroy = "false"
}
With the present setup, terraform -pan, -apply, and -destroy works fine and creates and deletes 3 resources respectively.
However when i apply this plan via terraform, and then try to terminate the instance via AWS console the block EBS volume, i.e xvdf does not get deleted automatically.
How can we set this ebs volume to terminate on instance delete
?
Solution
You can use the ebs_block_device
block within the aws_instance
resource. This will by default delete the ebs volume when the instance is terminated.
https://www.terraform.io/docs/providers/aws/r/instance.html#block-devices
You have to use the above instead of the aws_volume_attachment
resource.
Answered By - manojlds Answer Checked By - Marie Seifert (WPSolving Admin)