Infrastructure at your Service

I came accross an issue by a customer using aws and terraform. He created a server with ebs volume attached to it but he deleted the volume by mistake.

He then recreated it manually without using the terraform to do it. Thus, the tfstate wasn’t up to date with the new volume and when executing the terraform plan it wanted to create a new volume withe the same name and everything.
So you’ll find the different steps in this blog to re-import the existing volume in the existing terraform tfstate.

We will use terraform in command line directly. I suppose that the path to your tfstate is well set in your .tf file, if you have it localy or in s3 doesn’t matter.

For this blog I’ll use the following resource declarations:
– EBS Volume Resource: aws_ebs_volume.inst-name-volume
– EBS Volume ID: vol-id_of_the_volume
– EBS Attachement Resource: aws_volume_attachment.inst-name-attachement
– Ec2 Instance ID: i-id_of_the_aws_instance

If you execute the plan you’ll find which resource it will try to create:

Command

terraform plan -out myplan

If the resource names are the same between the ones already in your tfstate and the ones you want to import, you’ll have to remove it from your tfstate as the import cannot update the current configuration.

Here the command to list all your declared resources:

Command

terraform state list

Here the command to remove the desired resources (ebs volume + attachement):

Command

terraform state rm aws_ebs_volume.inst-name-volume
terraform state rm aws_volume_attachment.inst-name-attachement

You can now import the existing ebs volume and attachement:

Command

terraform import aws_ebs_volume.inst-name-volume vol-id_of_the_volume
terraform import aws_volume_attachment.inst-name-attachement device_name:vol-id_of_the_volume:i-id_of_the_aws_instance
(e.g. terraform import aws_volume_attachment.inst-name-attachement /dev/xvdb:vol-028f89784ffff6294:i-0431fffffff1d2d3d)

The result of the commands should be successful, if so, you can list the declared resources:

Command

terraform state list

And if you execute the plan again, you should see no change, up to date:

Command

terraform plan -out myplan

Note that you can do it for an ec2 instance as well simply with:

Command

terraform import aws_instance.inst-name i-id_of_the_aws_instance

I hope it helped you, if you have any questions do not hesitate in the comments below.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Stephane Biehler
Stephane Biehler

Consultant