Search code examples
amazon-web-servicesamazon-amiterraform

How to remove an AWS Instance volume using Terraform


I deploy a CentOS 7 using an AMI that automatically creates a volume on AWS, so when I remove the platform using the next Terraform commands:

terraform plan -destroy -var-file terraform.tfvars -out terraform.tfplan
terraform apply terraform.tfplan 

The volume doesn't remove because it was created automatically with the AMI and terraform doesn't create it. Is it possible to remove with terraform?

My AWS instance is created with the next terraform code:

resource "aws_instance" "DCOS-master1" {
    ami = "${var.aws_centos_ami}"
    availability_zone = "eu-west-1b"
    instance_type = "t2.medium"
    key_name = "${var.aws_key_name}"
    security_groups = ["${aws_security_group.bastion.id}"]
    associate_public_ip_address = true
    private_ip = "10.0.0.11"
    source_dest_check = false
    subnet_id = "${aws_subnet.eu-west-1b-public.id}"

    tags {
            Name = "master1"
        }
}

Solution

  • I add the next code to get information about the EBS volume and to take its ID:

    data "aws_ebs_volume" "ebs_volume" {
      most_recent = true
    
      filter {
        name   = "attachment.instance-id"
        values = ["${aws_instance.DCOS-master1.id}"]
      }
    }
    
    output "ebs_volume_id" {
      value = "${data.aws_ebs_volume.ebs_volume.id}"
    }
    

    Then having the EBS volume ID I import to the terraform plan using:

    terraform import aws_ebs_volume.data volume-ID
    

    Finally when I run terraform destroy all the instances and volumes are destroyed.