Migrating Existing Infrastructure to Terraform: A Success Story!

·

2 min read

Introduction

In today's fast-paced world of cloud computing, infrastructure automation is the name of the game. That's precisely why my team and I embarked on a journey to migrate our existing AWS infrastructure to Terraform.

The Journey Begins

Our AWS infrastructure was already humming along with EC2 instances running smoothly. The first step in our migration journey was to ensure that everything was up and running as expected.

Setting Up the Terraform Blueprint

We kicked things off by creating a main.tf file, where we specified our AWS provider and the desired region. This file served as the blueprint for our Terraform configuration.

provider "aws" { 
    region = "us-west-2" # Your desired region
}

import {
        id = "instanceid"

        to = aws_instance.example
}

Generating Configuration

Now utilize the terraform plan -generate-config-out=generated.tf command. This will generate a resource block in a separate file named generated.tf. It contains all the details of our AWS instance.

terraform plan -generate-config-out=generated.tf

Resource Copy-Paste

After obtaining the resource block, we bid farewell to the generated file and seamlessly integrated the resource block into our main.tf file. This was the point where we said goodbye to the import block as well.

Now if you run terraform plan, it will show to add 1 resources which is not right since we have that resource already running, terraform doesn't know the changes as it keep changes through its state files which is not present yet.

Unleashing the Magic of the State File

To fill that gap, we ran terraform import aws_instance.example (ec2id). This simple command not only created an import successfully but also generated the crucial state file. The state file is the heart and brain of Terraform—it ensures that your infrastructure aligns with your configuration.

terraform import aws_instance.example (ec2id)

Success Achieved

The culmination of our journey was a Terraform setup that seamlessly managed our existing infrastructure. Now if you run terraform plan again, it will beautifully display "No Changes," signifying the successful migration of our existing infrastructure to Terraform.

Key Takeaway

The key takeaway from our journey is the importance of the state file in Terraform. It's the guiding light that ensures your infrastructure mirrors your configuration.

Happy automating!