Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import all resources defined in tf file

Tags:

terraform

Lets say I've used terraform to build my infrastructure and my tfstate gets deleted for some reason. This means I already have my resources defined in tf files, I just need to re-import everything.

Does this have to be a manual process?

For example this is how I import an EC2 instance:

terraform import aws_instance.web i-123456

If I have to do that for every resource thats quite painful (might as well delete everything and start over).

If I already have my tf files is there a way to just import all the resources that have been defined in them? For example I needed the instance ID in order to import that instance. Can the terraform import command just read my tf file and find the resource mapped to "aws_instance.web"?

In order to do this terraform would need to have a mapping of that aws instance to the resource in the tf file- this is of course the purpose of the tfstate. BUT does terraform have a way of also tagging resources with their resource mappings? So I can do an import against a tf file and terraform just dynamically reads the tf file and finds the physical resources corresponding to the tf resources by unique tags?

like image 967
red888 Avatar asked Dec 03 '17 00:12

red888


1 Answers

No, there's no way to do this natively in Terraform; and even if you scripted a way together - I don't think it'd be very reliable and you wouldn't be able to trust that it selected the right resource (At least not easily).

Terraform says multiple times in the documentation that you need to protect your state file; this is why remote stores, such as S3 are encouraged for anything you care about; and also why this is a selling point of Terraform Enterprise.

like image 111
TJ Biddle Avatar answered Oct 06 '22 06:10

TJ Biddle