Import Existing Resources using Terraform
In this blog, I will walk you through the ways to import pre-existing cloud resources in terraform.
Why Import is required?
There will be a scenario, where you will have a stringent timeline to setup a cloud Infrastructure and it can lead to situations where infrastructure needs to be created manually due to time pressures, emergency releases or just the fact that the infrastructure exists, and terraform was never used in the first instance. In a worst case scenario, you can lose the terraform.tfstate file. Terraform import will be essential in most of all these scenarios.
Let's Import
With an understanding of why Import is required, let us begin by importing a simple AWS resource S3. Firstly, we need to setup the Terraform and AWS credentials locally, we will not go into the details of installing and setting AWS credentials in this blog but you can follow the official websites for Installing a Terraform and Setting the AWS credentials. To import the S3 resource into Terraform, follow the below step-by-step guide.
Step 1 – Create the S3 bucket Manually
Step 2 – Create main.tf and set Terraform Provider Configuration
// Provider configurationterraform {required_providers {aws = {source = "hashicorp/aws"version = "~> 3.0"}}}provider "aws" {region = "ap-south-1"}
Run terraform init to initialize the terraform modules. Below is the output for successful terraform initialization.
Step 3: Enter the config of the resource to import
We need to enter the configuration of S3. Basically, it will be hard to enter all the arguments of the resource but terraform import doesn't require all arguments to pass in the configuration instead only the required one. Append the below config in main.tf
resource "aws_s3_bucket" "myimportbucket" {}
Step 4: Import the Resource
We will import the S3 bucket which was configured manually to Infrastructure as a code and we can achieve this by running the import command as below
where <bucket_name> is name of the bucket which we are importing, in this case, bucket name is terraform-import-example-bucketterraform import aws_s3_bucket.myimportbucket <bucket_name>
Step 5: Validate the state file and plan
resource "aws_s3_bucket" "myimportbucket" {lifecycle {ignore_changes = [acl,force_destroy]}}
Let's run terraform plan again
We can observe, there is no difference in the configuration. If you want to modify any configuration later then you can easily change in the main file and you can maintain you infrastructure within the code.Conclusion:
In this blog post, I have shown you on how the terraform import can be used to import existing resources. We took S3 as an example of existing resource and later S3 resource configuration imported into the terraform. Hope this blog helped you in your similar use case.Thank you for reading!
Comments
Post a Comment