Welcome to Day 3 of my Terraform learning journey! Today,I will walk through deploying your first server on AWS using Terraform. This guide is designed for beginners, so don’t worry if you’re new to infrastructure as code I've got you covered.
Why Terraform?
Terraform simplifies infrastructure management by using code to provision and manage resources. Instead of manually creating servers in the AWS console, Terraform automates this process, ensuring consistency and repeatability.
What We’ll Achieve
By the end of this guide, you’ll have:
- Deployed an AWS EC2 instance running a simple web server.
- Configured the instance with an HTTP server (Apache) using a startup script.
- Accessed your web server via a public IP.
Step-by-Step Deployment
1. Prerequisites
Ensure you have the following set up:
- Terraform Installed: Download Terraform.
- AWS CLI Installed: Install AWS CLI.
-
AWS Access Configured: Run
aws configure
and input your credentials. - A Text Editor: Visual Studio Code or your preferred editor.
2. Write the Terraform Code
Create a new file named main.tf
and add the following code:
provider "aws" {
region = "us-east-1" # Specify your AWS region
}
resource "aws_instance" "simple_web_server" {
ami = "ami-0453ec754f44f9a4a" # Amazon Linux 2
instance_type = "t2.micro" # Free-tier eligible
vpc_security_group_ids = [aws_security_group.simple_web_server.id]
user_data = <<-EOF
#!/bin/bash
sudo yum update -y
sudo yum install -y httpd
sudo systemctl start httpd
sudo systemctl enable httpd
echo "Hello, World" > /var/www/html/index.html
EOF
tags = {
Name = "simple_web_server"
}
}
resource "aws_security_group" "simple_web_server" {
name = "simple_web_server"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # Allow traffic from all IPs
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"] # Allow all outbound traffic
}
}
3. Deploy the Server
- Initialize Terraform: Open your terminal, navigate to the project directory, and run:
terraform init
- Plan the Infrastructure: Review the resources Terraform will create:
terraform plan
- Apply the Configuration: Deploy the resources:
terraform apply
Type yes
when prompted.
- Get the Public IP: After deployment, find the public IP of your instance in the AWS console or output it in Terraform:
output "instance_public_ip" {
value = aws_instance.simple_web_server.public_ip
}
4. Test the Deployment
- Copy the public IP of your EC2 instance.
- Open a browser and visit:
http://<Public_IP>:80
- You should see "Hello, World" displayed on the page.
Key Learnings
- Terraform Basics: You’ve learned how to define resources like EC2 instances and security groups.
-
Automating Server Setup: Using
user_data
, you automated server initialization and web server setup. - Infrastructure as Code: You’ve experienced how Terraform can quickly provision and manage cloud resources.
Let me know how your deployment goes or if you have questions!
Top comments (0)