How to import existing resource using terraform import comand?
To import an existing infrastructure resource into Terraform, you can use the terraform import
command. This command allows you to take an existing resource that was created outside of Terraform and bring it under Terraform management.
In this blog, we will take two examples -
Also, we are going to take a look on the -
- In which situation you should use terraform import?
- Drawbacks of Terraform import?
- Always use terraform output during the terraform import
But before that here's the basic syntax for the terraform import command:
1# terraform import command to import resource
2
3terraform import <RESOURCE_TYPE>.<RESOURCE_NAME> <RESOURCE_ID>
For example, if you want to import an existing Amazon S3 bucket into Terraform, you could use a command like this:
1terraform import aws_s3_bucket.my_bucket my-bucket-name
This would import the S3 bucket with the name my-bucket-name
into Terraform and create a resource block for it in your Terraform configuration.
Keep in mind that you will need to have a resource block in your Terraform configuration for the resource type you are importing. The resource block should include all of the required arguments for the resource type, as well as any optional arguments that you want to set.
Once you have imported the resource, you can use the standard Terraform workflow to make changes to the resource and apply those changes.
How to import EC2 Instance using Terraform import?
To import an Amazon EC2 instance into Terraform using the terraform import
command, you will need to have a resource block in your Terraform configuration for the aws_instance resource type. The resource block should include all of the required arguments for the aws_instance resource, as well as any optional arguments that you want to set.
Here are the steps which you need to follow for import:
- Identify the EC2 Instance- But first let's check the EC2 Instance which is already provisioned on AWS. Here is the screenshot of my EC2 Instance running on AWS-
-
Write Empty aws_instance resource block- Write an empty terraform resource block for EC2 Instance:
1 #main.tf 2 3 provider "aws" { 4 region = "eu-central-1" 5 shared_credentials_files = ["/Users/rahulwagh/.aws/credentials"] 6 } 7 8 resource "aws_instance" "ec2_example" { 9 }
-
Run terraform import- Now the
terraform import
command using the correct resource name .e.g.aws_instance.ec2_example
1 terraform import aws_instance.ec2_example i-097f1ec37854d01c2
-
Fill in the resource block- After the successful import add the EC2 resource information into the empty block of
aws_instance
:1 resource "aws_instance" "ec2_example" { 2 ami = "ami-06ce824c157700cd2" 3 instance_type = "t2.micro" 4 tags = { 5 "Name" = "my-test-ec2" 6 } 7 }
-
Verify the import- Now you can verify the
terraform import
by running the commandterraform plan
and it should not create any more resources -
The above steps will import the EC2 instance with the ID i-097f1ec37854d01c2 into Terraform and create a resource block for it in your configuration. You can then use the standard Terraform workflow to make changes to the EC2 instance and apply those changes.
How to import S3 Bucket using Terraform import?
Here are the steps which you need to follow for importing pre-existing S3 bucket using terraform import
command -
-
Find the name of the bucket- The first step would be to find the name of the bucket which you want to import back using
terraform import
. Here is the bucket which I have created manually from the AWS GUI console -S3 bucket which I have created manually from AWS console -
Create empty aws_s3_bucket resource in main.tf- Create an empty
aws_s3_bucket
resource inside the terraform file(main.tf
). Here is the code for emptyaws_s3_bucket
-1resource "aws_s3_bucket" "my_test_bucket" { 2 bucket = "test-bucket-1-for-import" 3 tags = { 4 "name" = "test-bucket" 5 } 6 }
Also, you need to create an empty resource for
aws_s3_bucket_acl
-1resource "aws_s3_bucket_acl" "example" { 2 bucket = aws_s3_bucket.my_test_bucket.id 3}
-
Run terraform import- Now run the
terraform import
command for both the resources --
aws_s3_bucket
-
aws_s3_bucket_acl
1terraform import aws_s3_bucket.my_test_bucket test-bucket-1-for-import
-
Let's import the aws_s3_bucket_acl
also using the following command -
1 terraform import aws_s3_bucket_acl.example test-bucket-1-for-import
-
Fill in the resource block- Now you can write the remaining terraform code inside your terraform file(
main.tf
) and execute the terraform plan command to verify that you have successfully imported all the resources.1 # main.tf 2 3 resource "aws_s3_bucket" "my_test_bucket" { 4 bucket = "test-bucket-1-for-import" 5 tags = { 6 "name" = "test-bucket" 7 } 8 } 9 10 resource "aws_s3_bucket_acl" "example" { 11 bucket = aws_s3_bucket.my_test_bucket.id 12 }
-
Verify the import- Run the
terraform plan
command to verify the import and if you have successfully imported the resources then it should show the following message on your terminal "No changes. Your infrastructure matches the configuration." -Terraform import aws_s3_bucket_acl for S3 bucket -
Great you have successfully imported the S3 bucket.
How to import the module?
Importing a module can be a little challenging and it depends a lot on how big and complex the module is. But there are steps which I would recommend you follow -
-
Define the source of local module - You need to define a module block and specify the source of the module, like this:
1 module "example" { 2 source = "./module-directory" 3 }
- The above code will import to the local directory
module-directory
.
-
Define the source of the remote module - specify a remote source for the module, such as a Git repository or a Terraform registry. You can use the registry name and the module name in the source field, like this:
1 module "example" { 2 source = "registry.terraform.io/module/name" 3 }
You can even define the version of the module also if in case you want to import any specific module version -
1 module "example" {
2 source = "registry.terraform.io/module/name/version"
3 }
-
Reference the resources with the module- After defining the module in your configuration, you can use the resources and outputs defined in the module by referencing them using the module name and resource/output name, like this:
1 resource "aws_instance" "example" { 2 ami = module.example.ami_id 3 instance_type = "t2.micro" 4 }
Here is the output resource block -
1output "example_output" {
2 value = module.example.output_value
3}
- Example command for module import- Here is an example command for importing the module but you need to modify the code based on the name of your module
1terraform import module.example.aws_s3_bucket.example BUCKET-NAME
In which situation you should use terraform import?
There are a few situations where you might want to use the terraform import
command:
-
When you want to bring existing infrastructure under Terraform management: If you have infrastructure that was created outside of Terraform, you can use
terraform import
to bring it under Terraform management. This allows you to use the standard Terraform workflow to make changes to the infrastructure and track those changes over time. -
When you want to move infrastructure between environments: If you have the infrastructure in one environment (e.g. a staging environment) and you want to move it to another environment (e.g. production), you can use
terraform import
to bring the infrastructure into Terraform in the target environment, and then use the standard Terraform workflow to apply the changes. -
When you want to switch from manual management to Terraform management: If you have been manually managing infrastructure and you want to switch to using Terraform, you can use terraform import to bring the existing infrastructure under Terraform management. This allows you to start using the standard Terraform workflow to manage the infrastructure going forward.
Keep in mind that terraform import
is a one-time operation, and it should not be used as a replacement for the standard Terraform workflow. After you have imported a resource, you should continue to use the standard Terraform workflow to make changes to the resource.
Drawbacks of terraform import?
-
It is a one-time operation:
terraform import
is a one-time operation, and it should not be used as a replacement for the standard Terraform workflow. After you have imported a resource, you should continue to use the standard Terraform workflow to make changes to it. -
It can be difficult to use with complex infrastructure:
terraform import
can be difficult to use with infrastructure that has many dependencies or is otherwise complex. It may be easier to recreate the infrastructure from scratch using the standard Terraform workflow. -
It does not import the resource's history:
terraform import
does not import the history of the resource, so you will not be able to see the changes that were made to the resource before it was brought under Terraform management.
Always use terraform output during the terraform import
The output block in a Terraform configuration is used to define values that you want to be available after running Terraform. These outputs can be used to display important information about your infrastructure, or to pass values to other resources or modules.
A well-formatted terraform output
block will help you to re-construct the resource block after you have successfully imported the terraform state
using the terraform import
command.
References - Stackoverflow - Terraform import existing resources
Posts in this Series
- Securing Sensitive Data in Terraform
- Boost Your AWS Security with Terraform : A Step-by-Step Guide
- How to Load Input Data from a File in Terraform?
- Can Terraform be used to provision on-premises infrastructure?
- Fixing the Terraform Error creating IAM Role. MalformedPolicyDocument Has prohibited field Resource
- In terraform how to handle null value with default value?
- Terraform use module output variables as inputs for another module?
- How to Reference a Resource Created by a Terraform Module?
- Understanding Terraform Escape Sequences
- How to fix private-dns-enabled cannot be set because there is already a conflicting DNS domain?
- Use Terraform to manage AWS IAM Policies, Roles and Users
- How to split Your Terraform main.tf File into Multiple Files
- How to use Terraform variable within variable
- Mastering the Terraform Lookup Function for Dynamic Keys
- Copy files to EC2 and S3 bucket using Terraform
- Troubleshooting Error creating EC2 Subnet InvalidSubnet Range The CIDR is Invalid
- Troubleshooting InvalidParameter Security group and subnet belong to different networks
- Managing strings in Terraform: A comprehensive guide
- How to use terraform depends_on meta argument?
- What is user_data in Terraform?
- Why you should not store terraform state file(.tfstate) inside Git Repository?
- How to import existing resource using terraform import comand?
- Terraform - A detailed guide on setting up ALB(Application Load Balancer) and SSL?
- Testing Infrastructure as Code with Terraform?
- How to remove a resource from Terraform state?
- What is Terraform null Resource?
- In terraform how to skip creation of resource if the resource already exist?
- How to setup Virtual machine on Google Cloud Platform
- How to use Terraform locals?
- Terraform Guide - Docker Containers & AWS ECR(elastic container registry)?
- How to generate SSH key in Terraform using tls_private_key?
- How to fix-Terraform Error acquiring the state lock ConditionalCheckFiledException?
- Terraform Template - A complete guide?
- How to use Terragrunt?
- Terraform and AWS Multi account Setup?
- Terraform and AWS credentials handling?
- How to fix-error configuring S3 Backend no valid credential sources for S3 Backend found?
- Terraform state locking using DynamoDB (aws_dynamodb_table)?
- Managing Terraform states?
- Securing AWS secrets using HashiCorp Vault with Terraform?
- How to use Workspaces in Terraform?
- How to run specific terraform resource, module, target?
- How Terraform modules works?
- Secure AWS EC2s & GCP VMs with Terraform SSH Keys!
- What is terraform provisioner?
- Is terraform destroy needed before terraform apply?
- How to fix terraform error Your query returned no results. Please change your search criteria and try again?
- How to use Terraform Data sources?
- How to use Terraform resource meta arguments?
- How to use Terraform Dynamic blocks?
- Terraform - How to nuke AWS resources and save additional AWS infrastructure cost?
- Understanding terraform count, for_each and for loop?
- How to use Terraform output values?
- How to fix error configuring Terraform AWS Provider error validating provider credentials error calling sts GetCallerIdentity SignatureDoesNotMatch?
- How to fix Invalid function argument on line in provider credentials file google Invalid value for path parameter no file exists
- How to fix error value for undeclared variable a variable named was assigned on the command line?
- What is variable.tf and terraform.tfvars?
- How to use Terraform Variables - Locals,Input,Output
- Terraform create EC2 Instance on AWS
- How to fix Error creating service account googleapi Error 403 Identity and Access Management (IAM) API has not been used in project before or it is disabled
- Install terraform on Ubuntu 20.04, CentOS 8, MacOS, Windows 10, Fedora 33, Red hat 8 and Solaris 11