Terraform - AWS - How to prevent EBS volumes from being deleted?

Viewed 4363

I'm fairly new to Terraform so I'm hoping the issue is something I'm doing wrong.

I have some instances which need separate EBS volumes attached. These are defined as three separate Terraform resources:

aws_instance
aws_ebs_volume
aws_volume_attachment

When the instances boot, within AWS console the volumes say they have 'Delete on termination' protection, yet Terraform still destroys them:

aws ebs volume screenshot

If you use the 'block_device' mapping within the aws_instance resource definition you can prevent it from being terminated:

https://www.terraform.io/docs/providers/aws/r/instance.html#delete_on_termination-1

But this does option not appear in the ebs_volume resource:

https://www.terraform.io/docs/providers/aws/r/ebs_volume.html

How do I stop Terraform from deleting my EBS volumes?

I tried doing this, but it just stops the terraform destroy job from running:

  lifecycle = {
    prevent_destroy = true
  }

Thanks

3 Answers

It is doing exactly what the documentation says it will do, so Terraform will not allow a terraform destroy, if you need it to do this then I suggest moving these resources to their own terraform directory away from other resources.

prevent_destroy (bool) - This flag provides extra protection against the destruction of a given resource. When this is set to true, any plan that includes a destroy of this resource will return an error message.

In general, terraform destroy will destroy all resources. If you would rather destroy only specific resources, you can use for example: terraform destroy -target=aws_instance.some_name

For your EBS volume example, you would also have to destroy the aws_volume_attachment resource.

if you want to prevent your ec2 instance for accidental deletion, you can use the below command on your create ec2 instance resource section,

disable_api_termination= "true"

I have verified couple of time it's working fine.

Happy learning....!!

Related