In the previous blog, I discussed the Terraform commands. You can check it here: Terraform Commands.
Terraform is a powerful Infrastructure as Code (IaC) tool that allows engineers to manage cloud infrastructure through configuration files. In this blog, we’ll learn how to create, modify, and delete AWS EC2 Instances using Terraform.
Creation Of AWS EC2 Instance:
Step 1: Make sure you have an account with the AWS. if you don’t have an account Please check my blog: AWS-Basics.
If you have a root user account on AWS, Please create an IAM user for yourself. You can check this blog: AWS-IAM-USER
Step 2: Install the terraform on the Linux server :
Terraform Installation on Linux Server
Step 3: Create a file provider.tf to define the provider AWS.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0" # This will use the latest version of the 5.x series
}
}
}
provider "aws" {
region = "us-east-1"
access_key = "AKIAXYKJUXNDKEMLO2FA"
secret_key = "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"
}
Step 4: Create an instance.tf file to define the ec2 instance information
resource "aws_instance" "web" {
ami = "ami-06b21ccaeff8cd686"
instance_type = "t2.micro"
tags = {
Name = "first-aws-instance"
}
}
Step 5: Initialize Terraform Project.
Before applying the configuration run the “terraform init”
command to initialize the terraform project.
terraform init
Step 6: Plan the configuration.
Run terraform plan
to see what changes Terraform will make.
terraform plan
Note: You can see the output as per the plan 1 resource add, 0 change and 0 destroy.
Step 7: Apply the configuration.
Now apply the configuration using terraform apply
the command.
terraform apply
Step 8: Verify EC2 Instance is created or not.
Note: Please make sure you are checking in the same region as given in the instance.tf file.
Modify the Resources :
Let’s take an example You need to change the ami-id for the instance which you previously deployed that’s the wrong ami-id.
Step 1: Change ami-id on instance.tf file.
resource "aws_instance" "web" {
ami = "ami-0583d8c7a9c35822c"
instance_type = "t2.micro"
tags = {
Name = "first-aws-instance"
}
}
Step 2: Initialize the project using the terraform init
command.
terraform init
Step 3: Plan the changes using terraform plan
command.
terraform plan
Note: In the above image terraform plan output showing the image is replaced.
Note: Now the plan is to add 1 resource and delete 1 resource.
Step 4: Apply the changes using the terraform apply
command.
Step 5: Verify on AWS Console, EC2-Instace ami-id is changed or not.
Delete the Resource :
By a single command, you can delete all the resources that are created by Terraform.
terraform destroy
Verify over the AWS Console:
You can see EC2 Instance is in a Terminated state.
Thank you for giving your precious time to read this blog/article and if any suggestions or improvements are required on my blogs feel free to connect on LinkedIn Unnati Gupta. Happy Learning 💥🙌**!!**