Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform initial state file creation

Is there a way to create the terraform state file, from the existing infrastructure. For example, an AWS account comes with a some services already in place ( for ex: default VPC).

But terraform, seems to know only the resources, it creates. So,

  1. What is the best way to migrate an existing AWS Infrastructure to Terraform code
  2. Is it possible to add a resource manually and modify the state file manually (bad effects ?)

Update

Terraform 0.7.0 supports importing single resource.

like image 572
Shan Avatar asked Jan 22 '16 17:01

Shan


People also ask

How Terraform state file is created?

Terraform is a coding tool aligned with this practice which allows us to define cloud and local resources in formatted configuration files that we can reuse and share. When we build infrastructure in Terraform configuration, a state file gets created in the local workspace directory named terraform. tfstate .

Does Terraform plan create a state file?

This state is stored by default in a local file named "terraform. tfstate", but it can also be stored remotely, which works better in a team environment. Terraform uses this local state to create plans and make changes to your infrastructure.

How does Terraform state file work?

Terraform stores information about your infrastructure in a state file. This state file keeps track of resources created by your configuration and maps them to real-world resources.


2 Answers

For relatively small things I've had some success in manually mangling a state file to add stubbed resources that I then proceeded to Terraform over the top (particularly with pre-existing VPCs and subnets and then using Terraform to apply security groups etc).

For anything more complicated there is an unofficial tool called terraforming which I've heard is pretty good at generating Terraform state files but also merging with pre-existing state files. I've not given it a go but it might be worth looking into.

Update

Since Terraform 0.7, Terraform now has first class support for importing pre-existing resources using the import command line tool.

As of 0.7.4 this will import the pre-existing resource into the state file but not generate any configuration for the resource. Of course if then attempt a plan (or an apply) Terraform will show that it wants to destroy this orphaned resource. Before running the apply you would then need to create the configuration to match the resource and then any future plans (and applys) should show no changes to the resource and happily keep the imported resource.

like image 70
ydaetskcoR Avatar answered Oct 12 '22 04:10

ydaetskcoR


Use Terraforming https://github.com/dtan4/terraforming , To date it can generate most of the *.tfstate and *.tf file except for vpc peering.

like image 31
padmakarojha Avatar answered Oct 12 '22 03:10

padmakarojha