Ebs volume re-attach


I am not sure if this is possible, I have this scenario.

  1. The initial build will create ec2 and ebs volume.
  2. I would like to destroy ec2, without destroying ebs volume.
  3. I would like to rebuild ec2 and attach the ebs volume that was created in step 1.

Reading the documentation I could use skip_destroy but on the next apply it will try to create the same ebs again that is defined in step 1, which makes sense and the code to create ebs volume is in the project.

Is there a way to achieve this?



You can achieve this by using the aws_volume_attachment resource.

Essentially, create an aws_instance resource (with no volumes declared in this other than the root volume), and separately create your aws_ebs_volume resource.

Then, create an aws_volume_attachment resource which will attach the volume to the instance.

As the volume is declared independently of the instance, destroying the EC2 instance will not destroy your EBS volume - the volume will persist.

You can test this by deploying the above configuration, then re-running your terraform apply but using a different ami_id. Your output will show you that it destroys the “attachment” resource (which detaches the volume from the instance), then it will destroy the instance, then create the new instance, then create the new “attachment” resource (which attaches the existing volume to the new instance). The volume will persist unchanged.

Skeleton code is:

resource "aws_instance" "fileserver" {
  ami                     = var.ami_id
  root_block_device {
    volume_type           = "gp3"
    delete_on_termination = true

  depends_on = [

resource "aws_ebs_volume" "volume" {

resource "aws_volume_attachment" "volume" {
  instance_id = aws_instance.fileserver.id
  device_name = "xvdi"
  volume_id   = aws_ebs_volume.volume.id

I added the depends_on because you want terraform to make any changes to the volume before it makes changes to the instance, specifically if you’re using Windows OS - otherwise if you have a change to your volume, such as a size increase, terraform will make the change after the instance is launched and the new size sometimes won’t be recognised by the OS if EC2Launch v2 has already run.

Hope that helps.

thanks will give that a try.