Getting Started with Terraform: Creating an EC2 Instance in AWS ☁️
Infrastructure as Code (IaC) has revolutionized the way we manage and provision cloud resources. Terraform, a popular IaC tool developed by HashiCorp, allows you to define and provision infrastructure using code. In this tutorial, we'll walk through the process of creating an Amazon Web Services (AWS) EC2 instance using Terraform.
Prerequisites
Before we begin, ensure you have the following:
AWS Account: You need an AWS account with administrative privileges.
Terraform: Install Terraform by following the instructions on the official website.
AWS CLI: Make sure you have the AWS Command Line Interface installed and configured with your AWS credentials.
The Need for Terraform and Infrastructure as Code (IaC)
Let's Understand IAC and Terraform like we are 9😊.
1. Automation:
Imagine building a sandcastle on the beach. Instead of using your hands, Terraform is like a magical tool that builds the sandcastle for you. It does the work faster and without mistakes.
Manual infrastructure provisioning is time-consuming and error-prone. IaC tools like Terraform enable automation, allowing you to define and deploy infrastructure resources using code. This reduces manual intervention and speeds up deployment processes.
2. Consistency:
When you build sandcastles, they should all look the same. Terraform ensures that when you create things in the cloud (like computer servers), they all look exactly how you want them to, no matter how many you build.
With IaC, you define your infrastructure using code, ensuring uniformity across environments. Whether it's development, staging, or production, the same code is used to create and manage resources, reducing configuration drift.
3. Making It Bigger or Smaller:
If you want to build a bigger sandcastle, you just tell Terraform to add more sand. If you want a smaller one, you tell it to take some sand away. Terraform makes it easy to change the size of your sandcastle.
As your application scales, you need to provision and manage more resources. IaC allows you to scale horizontally or vertically by updating your codebase, making it simple to adapt to changing demands.
4. Copy and Paste:
You can use the same instructions (the Terraform code) to build sandcastles at different beaches (cloud providers) without learning new ways to build each time. It's like using a copy-and-paste tool.
IaC enables you to recreate entire environments reliably. If disaster strikes or you need to replicate a specific environment for testing or development, you can do so with confidence that it matches the original configuration.
IaC abstracts the underlying cloud provider, making it possible to manage resources across multiple cloud providers or in hybrid cloud environments using the same codebase.
5. Saving Money:
Imagine you're using a toy that eats batteries. You can use Terraform to tell the toy to sleep when you're not playing with it. This way, you don't waste batteries, and you save money.
IaC helps you manage costs by allowing you to define and control the resources provisioned. You can easily automate the shutdown of non-production resources during off-hours or apply cost-effective instance types.
6. Fixing Things Quickly:
If your sandcastle gets destroyed, Terraform can rebuild it just as it was, super fast. It's like magic repair!
IaC allows you to easily configure redundancy and disaster recovery strategies. You can define failover mechanisms and recovery processes in your code.
7. Planning Ahead:
Before you build a sandcastle, you can make a plan on paper (Terraform plan). This helps you know what you're going to build and check for mistakes before you start.
🚀🚀 Well, enough of Theory, Let's dirty our hands by actually provisioning infrastructure on a cloud platform. For this, We are going to use AWS, As it is one of the most complex of all.
Creating a vpc and an ec2 instance using Terraform on AWS.
provider "aws" {
profile = "default"
region = "ap-south-1" // replace this with your desired region
}
// creating a vpc
resource "aws_vpc" "myvpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "Myvpc"
}
}
// creating a subnet in vpc
resource "aws_subnet" "some_public_subnet" {
vpc_id = aws_vpc.myvpc.id
cidr_block = "10.0.1.0/24"
availability_zone = "ap-south-1a"
tags = {
Name = "my-public-subnet"
}
}
// Attaching internet gatewway to vpc
resource "aws_internet_gateway" "my-igw" {
vpc_id = aws_vpc.myvpc.id
tags = {
Name = "my-igw"
}
}
//creating route table
resource "aws_route_table" "public_rt" {
vpc_id = aws_vpc.myvpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.my-igw.id
}
route {
ipv6_cidr_block = "::/0"
gateway_id = aws_internet_gateway.my-igw.id
}
tags = {
Name = "Public Route Table"
}
}
// making our subnet public by associating route table to subnet
resource "aws_route_table_association" "public_1_rt_a" {
subnet_id = aws_subnet.some_public_subnet.id
route_table_id = aws_route_table.public_rt.id
}
// creating security group of ec2
resource "aws_security_group" "web_sg" {
name = "HTTP and SSH"
vpc_id = aws_vpc.myvpc.id
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = -1
cidr_blocks = ["0.0.0.0/0"]
}
}
// key pay for ssh
resource "aws_key_pair" "my-key-pair" {
key_name = "deployer-key"
public_key = file("~/.ssh/id_rsa.pub")
}
// creating ec2 instance
resource "aws_instance" "web_instance" {
ami = "ami-06f621d90fa29f6d0" // you can get this from data sources or aws portal
instance_type = "t3.micro"
key_name = aws_key_pair.my-key-pair.key_name
subnet_id = aws_subnet.some_public_subnet.id
vpc_security_group_ids = [aws_security_group.web_sg.id]
associate_public_ip_address = true
tags = {
"Name" : "my-ec2-instance"
}
}
// displaying ec2 public ip after provisioning.
output "ip" {
value = aws_instance.web_instance.public_ip
}
Save this file as
main.tf
Open the terminal and typeterraform init
. This will install the required provider. In our case it's laws.You can view the blueprint of what Terraform is going to build by typing
terraform plan
in the terminal.If everything looks okay, then type
terraform apply
and you will be asked for confirmation, Just type yes and your desired infrastructure will be created on AWS.
That's it! You've successfully saved a Terraform configuration file and applied it to create or manage your infrastructure. Remember to use Terraform responsibly, especially when applying changes to production environments, and always review your configurations before applying them.