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.
Result:
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:
- outer_elb
- outer_elb[1]
by import 2 resources below in to the terraform code:
- front_access_sg
- front_access_vendor_sg
Importing resources:
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à "name": "front_b_sg"
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)
- Run
terraform import
command to import existing resources to the state file: - Import
front_a_sg
with 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
- Import
front_b_sg
with id:sg-0eeda2xxxx
:
/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 sg-0eeda2xxxx
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