๐งฟManaging Infrastructure with Terraform: A Comprehensive Guide

๐ทTerraform Configuration File:
Create a Terraform configuration file to define a resource of AWS EC2 instance.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.42.0"
}
}
}
provider "aws" {
region = "us-east-2"
}
resource "aws_instance" "new-instance" {
ami = "ami-0b8b44ec9a8f90422"
instance_type = "t2.micro"
tags={
Name="new-instance"
}
}
๐ทCheck State Files:
Before running any commands, make sure to initialize Terraform:
terraform init
๐ทValidate the Configuration File:
Use the validate command to check for syntax errors:
terraform validate

๐ทAdd a Provisioner:
You can add a provisioner to your configuration file to configure the resource after it is created. For example, to run a shell script on the EC2 instance after creation, you can use the remote-exec provisioner:
resource "aws_instance" "new-instance" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
provisioner "remote-exec" {
command = "echo 'Instance created' > instance_status.txt"
}
๐ทApply Changes and Destroy Resources:
Apply the changes to create the EC2 instance and run the provisioner:
terraform apply

To destroy the resources:
terraform destroy
๐ทLifecycle Management Configurations:
You can add lifecycle management configurations to control the creation, modification, and deletion of resources. For example, to prevent accidental deletion:
resource "aws_instance" "new-instance" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
lifecycle {
create_before_destroy = true
prevent_destroy = true
}
}
This block ensures that Terraform creates a new resource before destroying the existing one (create_before_destroy) and allows the resource to be destroyed (prevent_destroy = false).
I'm confident that this blog will prove to be valuable, helping you discover new insights and learn something enriching .๐
๐Happy Learning : )
About the author
Hey there! ๐
I'm Pratik R. Mandge, a DevOps Engineer passionate about all things AWS DevOps Technology. Currently on a learning adventure, I'm here to share my journey and Blog's in the world of cloud and DevOps.
๐ ๏ธ My focus? Making sense of AWS services, improving CI/CD, and diving into infrastructure as code. Whether you're fellow interns or curious enthusiasts, let's grow together in the vibrant DevOps space.
๐ Connect with me for friendly chats, shared experiences, and learning moments. Here's to embracing the learning curve and thriving in the exciting world of AWS DevOps Technology!
Follow me on LinkedIn: https://www.linkedin.com/in/pratik-mandge363
Comments
Join the discussionNo comments yet. Be the first to comment.
Terraform - Infrastructure as a Code
In Terraform blog series, cover IaC basics, installation, config, workflow, modules, best practices, AWS/K8s integration, and practical examples. Aim to make readers proficient in Terraform.




