🧿Managing Infrastructure with Terraform: A Comprehensive Guide

🧿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 : )

Did you find this article valuable?

Support Pratik R. Mandge by becoming a sponsor. Any amount is appreciated!