If you don't want to preserve the root volume when an instance terminates,set to terminate the ebs volume also. To delete an Amazon Elastic Block Store (EBS) volume when terminating an EC2 instance using Terraform, you can utilize the "delete_on_termination" attribute of the root_block_device resource. Here's an example of how you can achieve this:
root_block_device { delete_on_termination = true }
resource "aws_instance" "ec2_instance" {
ami = data.aws_ami.base_ami.id
count = var.apps_instance_count
subnet_id = var.apps_subnet_id
instance_type = var.apps_instance_type
key_name = var.apps_key_name
security_groups = ["sg-xxxxxxxxxxxx","sg-xxxxxxxxxx"]
user_data_replace_on_change = true
user_data = "${file(var.apps_script_file)}"
dynamic "root_block_device" {
for_each = var.root_block_override ? [1] : []
content {
delete_on_termination = var.root_block_delete_on_termination
volume_type = var.root_block_volume_type == "gp3" ? null : var.root_block_iops
volume_size = var.root_block_volume_size
throughput = var.root_block_throughput
}
}
}
In the above example, we create an EC2 instance and attach an EBS volume to it. The delete_on_termination attribute is set to true, which ensures that the volume will be deleted automatically when the EC2 instance is terminated.
By specifying delete_on_termination = true and creating the attachment, Terraform will handle the deletion of the EBS volume when the EC2 instance is terminated.
Comments (0)