馃敮Using Terraform for Managing Infrastructure.
鉁达笍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).
Happy Learning : )
Subscribe to my newsletter
Read articles from Sandeep Kale directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by