0
votes

Prior to terraform import, I have defined:

# instance.tf

resource "aws_instance" "appserver" {

}

Then I ran: terraform import aws_instance.appserver <instance-id> and went smoothly, which I can see the imported ec2 resource by using terraform show. However, the mystery to me is to "transfer" this existing terraform state into the terraform config (instance.tf above) so that I can manage it as an Infrastructure as a Code (or at least that how I understood it). I added the ami and instance_type keys and their corresponding values but every time I issue terraform plan, terraform seems to want to "replace" my existing instance.

1) Why is terraform want to replace that instance?

2) How can I "transfer" the instance's terraform state into the config? (is this possible?)

3) For you guys seasoned veterans, how were you guys able to manage an existing aws infrastructure in terraform?

1

1 Answers

1
votes

First of all, terraform wants to replace your instance because terraform didn't do the 'link' you expected between the resource configuration and the current existing instance.

Terraform official documentation: (https://www.terraform.io/docs/import/index.html)

The current implementation of Terraform import can only import resources into the state. It does not generate configuration. A future version of Terraform will also generate configuration.

Because of this, prior to running terraform import it is necessary to write manually a resource configuration block for the resource, to which the imported object will be mapped.

While this may seem tedious, it still gives Terraform users an avenue for importing existing resources. A future version of Terraform will fully generate configuration, significantly simplifying this process.

After understanding the written above, I would use the following steps:

  1. First, write your terraform resource configuration. Should look like this:

    resource "aws_instance" "example" {
         # ...instance configuration...
    }
    
  2. terraform import aws_instance.example i-abcd1234 in order to import existing infrastructure to your state and attach it to the resource configuration you've created above.

Detailed source for more: https://www.terraform.io/docs/import/usage.html