🧿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 : )
Subscribe to my newsletter
Read articles from Pratik R. Mandge directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Pratik R. Mandge
Pratik R. Mandge
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