Create Terraform Scripts for an Existing Infrastructure
Introduction
This blog explains the solution approach and steps to create Terraform Scripts for an Existing Infrastructure. Here, AWS will be used for that infrastructure.
Solution Design
Implementation Steps
As a first step, need to identify the list of resources that already exists in the AWS infrastructure. These resources might have created manually To identify the already created (could be manually using console) resources in AWS, the below-listed approach will help.
Approach 1: Using AWS Console Tag Editor search, can identify the list resources created by resource type.
Approach 2: Using AWS CLI command (Example :
aws configservice list-discovered-resources --resource-type AWS::EC2::VPC
), can list down the resource list and its ids. Here, refer https://docs.aws.amazon.com/cli/latest/reference/configservice/list-discovered-resources.html#options
Create terraform script. Example:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 0.15.0"
}
}
}
provider "aws" {
profile = "default"
region = "us-west-2"
}
Run command
terraform init
to initialize the terraform and make sure the terraform connectivity with the infrastructure.Update terraform resource with resource name. Refer: Terraform documentation for the exact resource name and mandatory parameter configuration for import functionality.
resource "aws_vpc" "test_vpc" {
cidr_block = "10.0.0.0/16"
}
Here, cidr_block is mandatory. So added this parameter alone
Import the resource from existing infrastructure using the import command with the exact resource id noted in first step. Example
terraform import aws_vpc.test_vpc vpc-0841e2b7a945624b6
.Once imported, use the command
terraform show
to show the exact resource details to update back in terraform script.then, run
terraform validate
and cleanup all the error need to be fixed. Mostly the id attributes need to be removed which was copied from show command.Now, after all the errors fixed, can run command
terranform plan
which should resultNo changes. Infrastructure is up-to-date.
. This confirms terraform scripts and AWS infrastructure matches no need changes. Moving, forward can start making changes in terraform script and push it to AWS environment.