8
votes

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?

1
How would that work if you'd defined two identical resources? - Oliver Charlesworth
How do you mean? Like if I had two different tf files that defined a resource of the same name? Sorry still wrapping my head around terraform so maybe I'm missing something here? - red888
Yeah, kind of. If you'd defined two EC2 instances (for example) with the exact same parameters, how would Terraform know which is which without storing the mapping to instance IDs? - Oliver Charlesworth
hmm well assuming I have just one tf file wouldn't each resource defined in that file need to have a unique name? So if those instances were themselves tagged with that mapping terraform could know which is which right? - red888
In theory, yes. But in general not all resources are "taggable". (Well, they might be in AWS, I don't know. But they're certainly not in general.) - Oliver Charlesworth

1 Answers

7
votes

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.