Importing Existing Resources into Terraform - Day 8
Managing infrastructure using Terraform provides numerous benefits, including automation, version control, and reproducibility. However, many organizations already have existing resources deployed manually or through other means before adopting Terraform. In such scenarios, the process of importing existing resources into Terraform becomes vital.
In Terraform 1.5 and later, importing of existing resource is made easy. import
block is used to import existing infrastructure resources into Terraform, bringing them under Terraform's management. The import
block expects two arguments, id of existing resource and a resource block name for the resource.
Once imported, Terraform tracks the resource in your state file. You can then manage the imported resource like any other, updating its attributes and destroying it as part of a standard resource lifecycle.
Let's import the following manually created EC2 instance in the AWS console into Terraform.
Step 1: Create provider.tf and imports.tf files with the configurations below, and execute terraform init
to download the necessary provider plugin.
Step 2: To prompt Terraform to generate configuration for the import block you've specified, execute terraform plan
with the -generate-config-out=
flag followed by a new file path. Terraform displays its plan for importing your resource and the file where Terraform generated configuration based on this plan.
Step 3: Examine the recently created .tf file and relocate the resource block to a distinct configuration file. Execute the command terraform import aws_instance.example <instance_id>
. This action will import the desired configuration from the newly generated .tf file.
The desired resource has now been successfully imported into Terraform. You can confirm this by executing the command terraform plan
. As indicated in the snapshot below, the command should yield no changes.