๐ง Introduction
Setting up cloud infrastructure can be overwhelming โ but with Terraform, it becomes clean, fast, and automated. In this guide, you'll learn how to set up an AWS EC2 server using Terraform right from your Mac, step by step.
Whether you're a developer, DevOps enthusiast, or beginner exploring infrastructure as code (IaC), this tutorial will help you get started confidently.
๐ What Youโll Learn
- Installing Terraform on Mac
- Creating an IAM user for Terraform access
- Writing your first Terraform configuration
- Launching an EC2 instance in AWS using Terraform
๐ Prerequisites
Before we begin, make sure you have:
- A Mac (running macOS)
- An AWS account
- Terminal access
- Basic command-line knowledge
๐ง Step 1: Install Terraform on Mac
Use Homebrew to install Terraform:
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
Verify installation:
terraform -v
๐ Step 2: Create an IAM User in AWS
- Go to the AWS IAM dashboard.
- Create a new user (e.g.,
terraform-admin
) with programmatic access. - Attach the AdministratorAccess policy.
- Save the Access Key ID and Secret Access Key.
๐ Step 3: Configure AWS CLI
In your terminal:
aws configure
Enter your keys, default region (like us-east-1
), and output format (json
).
๐งฑ Step 4: Set Up Your Terraform Project
Create a new folder and initialize the project:
mkdir terraform-ec2-setup && cd terraform-ec2-setup
touch main.tf variables.tf outputs.tf
โ๏ธ Step 5: Write Terraform Configuration
main.tf
provider "aws" {
region = var.aws_region
}
resource "aws_instance" "web_server" {
ami = var.ami_id
instance_type = var.instance_type
subnet_id = aws_subnet.main.id
vpc_security_group_ids = [aws_security_group.allow_ssh.id]
tags = {
Name = "TerraformEC2"
}
}
variables.tf
variable "aws_region" {
default = "us-east-1"
}
variable "ami_id" {
default = "ami-04505e74c0741db8d" # Amazon Linux 2
}
variable "instance_type" {
default = "t2.micro"
}
outputs.tf
output "instance_public_ip" {
value = aws_instance.web_server.public_ip
}
Also add VPC, Subnet, and Security Group setup (shared earlier).
โถ๏ธ Step 6: Deploy the Infrastructure
Initialize Terraform:
terraform init
Preview the changes:
terraform plan
Apply the configuration:
terraform apply
๐ก Step 7: Access Your Server
Terraform will output the EC2 serverโs public IP. If you added a key pair, connect using:
ssh -i your-key.pem ec2-user@<public-ip>
๐งน Step 8: Destroy the Infrastructure (Optional)
To clean everything up:
terraform destroy
๐ก Conclusion
You just launched your first AWS EC2 instance using Terraform on macOS โ all from scratch. This is a foundational step in mastering infrastructure as code and automating your cloud setups.