Import Existing Resources Into Terraform code
Step by step guide to import resources into Terraform code:
Confirm the state before import:
The first thing that you have to do is uing
terraform plan command to confirm the current state.
To make our system’s state be stable, we have to keep the change to the state as small as possible. As you can see in the above image, there are 3 resources to add and 2 resources that have to be change.
Our task now is to make changes to the state in tfstate file of 2 following resources:
by import 2 resources below in to the terraform code:
Step 1/ Remove 2 objects in tfstate file:
You can search for the location of the two in terraform.tfstate.prd file by keywords:
"name": "front_a_sg" và
Step 2/ Import the resources:
- Log in to the console and find the resources wanting to import.
- Copy the ids of the resources that you want to import. (in this case, the id of front_a_sg is sg-036ec74316xxxxx and that of front_b_sg is sg-0eeda2xxxx)
terraform importcommand to import existing resources to the state file:
front_a_sgwith id sg-036ec74316xxxx:
/usr/local/src/terraform/terraform_0.12 import -var-file=./tfvars/prd.tfvars -state=./tfstate/terraform.tfstate.prd --state-out=./tfstate/terraform.tfstate.prd.new aws_security_group.front_a_sg sg-036ec74316xxxx
/usr/local/src/terraform/terraform_0.12 import -var-file=./tfvars/prd.tfvars -state=./tfstate/terraform.tfstate.prd.new --state-out=./tfstate/terraform.tfstate.prd.new aws_security_group.front_b_sg
Step 3/ Confirm the result by running
terraform plan command again.
You should notice that the state change of system now is equal to 0.
Memo: Nếu có index:
/usr/local/src/terraform/terraform_0.14 import -var-file=./tfvars/stg.tfvars -state=./tfstate/terraform.tfstate.stg --state-out=./tfstate/terraform.tfstate.stg aws_db_parameter_group.rds_parameter_group[\"rds_instance_001\"] web-rds-pg
⇒ escaping the double quotes fixes that.
Syntax to use:
terraform import aws_iam_user.api_users[\\"foo\\"] foo