How to import existing infrastructure to terraform
Terraform import is a command that allows you to take existing resources within your infrastructure and create Terraform configuration files for them.
This allows you
to manage those resources using Terraform, rather than having to manually make
changes to them.
The syntax for the import command is as follows: terraform import <resource type> <resource name> <resource ID>
For example,
If you have an
existing S3 bucket that you want to manage using Terraform, you would use the
following command: terraform import
aws_s3_bucket.example my-example-bucket
The first
argument, aws_s3_bucket.example, is the resource type and name that you
want to create in your Terraform configuration. The second argument, my-example-bucket, is the name of the existing S3 bucket that you want to import.
Once you run the
import command, Terraform will create a new file in your configuration
directory called terraform.tfstate which will contain the state of the
imported resource. This file is used to track the current state of your infrastructure
and is used to compare it with the desired state defined in your Terraform
configuration files.
Please note that
Terraform import is only able to import
resources that already exist within your infrastructure, it can't create new
resources. Additionally, the imported resources must match the resource types
and properties defined in your Terraform configuration files, otherwise, the
import may fail.
For example,
If
you're importing a virtual machine, you'll also need to import the virtual
network, storage account, and other resources that the virtual machine depends
on. Failure to do so could result in errors when running Terraform commands.
Terraform script that imports an existing S3 bucket:
CODE BELOW :
# Import the S3 bucket
resource "aws_s3_bucket" "example" {
# The name of
the S3 bucket that you want to import
bucket =
"my-example-bucket"
}
# Import the existing S3 bucket
terraform import aws_s3_bucket.example my-example-bucket
For more Terraform Use cases and scripts Read below :
- Terraform & AWS Landing Zone Accelerator for Multi Cloud Hybrid Datacenters
- Terraform script for creating an SQS FIFO queue, including the use of variables and remote state -AWS
- Terraform script that creates an S3 bucket, a VPC with two subnets (one public and one private), and a CloudFront distribution to access the S3 bucket