Okay, here is a basic Terraform configuration to create an EC2 instance on AWS. This example includes:
- Provider Configuration: Sets up the AWS provider and specifies the region.
- Data Source: Fetches the ID of the default VPC in the specified region.
- Security Group: Creates a security group to control inbound/outbound traffic (allowing SSH and HTTP).
- EC2 Instance: Defines and creates the EC2 instance itself, associating it with the security group and specifying an AMI, instance type, and key pair.
- Variables: Uses variables for customization (region, AMI, instance type, key name).
- Outputs: Outputs the public IP address and instance ID after creation.
Project Structure:
It's good practice to separate configurations. Create these files in the same directory:
provider.tf (or main.tf)
variables.tf
outputs.tf
1. provider.tf (or main.tf)
# Configure the AWS Provider
provider "aws" {
region = var.aws_region
}
# Data source to get the default VPC ID
data "aws_vpc" "default" {
default = true
}
# Resource to create a Security Group
resource "aws_security_group" "web_server_sg" {
name = "web-server-sg"
description = "Allow SSH and HTTP inbound traffic"
vpc_id = data.aws_vpc.default.id # Uses the default VPC
# Allow SSH inbound traffic from your IP
ingress {
description = "SSH access from specific IP"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = [var.ssh_location] # Use variable for SSH source IP
# Example: cidr_blocks = ["YOUR_HOME_OR_OFFICE_IP/32"]
}
# Allow HTTP inbound traffic from anywhere
ingress {
description = "HTTP access from anywhere"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
# Allow HTTPS inbound traffic from anywhere (optional)
# ingress {
# description = "HTTPS access from anywhere"
# from_port = 443
# to_port = 443
# protocol = "tcp"
# cidr_blocks = ["0.0.0.0/0"]
# }
# Allow all outbound traffic
egress {
from_port = 0
to_port = 0
protocol = "-1" # -1 means all protocols
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "WebServerSG"
Environment = var.environment_tag
}
}
# Resource to create the EC2 Instance
resource "aws_instance" "web_server" {
ami = var.ami_id # AMI ID (e.g., Amazon Linux 2 or Ubuntu) - MUST be valid for your chosen region
instance_type = var.instance_type # Instance type (e.g., t2.micro, t3.small)
key_name = var.key_name # Name of your existing EC2 Key Pair in AWS
# Associate the security group created above
vpc_security_group_ids = [aws_security_group.web_server_sg.id]
# Optional: Add a public IP address (true by default for default VPC/subnets)
# associate_public_ip_address = true
# Optional: User data script to run on instance launch
user_data = <<-EOF
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello World from Terraform</h1>" > /var/www/html/index.html
EOF
tags = {
Name = var.instance_name_tag
Environment = var.environment_tag
ManagedBy = "Terraform"
}
# Ensure security group is created before instance is created
depends_on = [aws_security_group.web_server_sg]
}
2. variables.tf
variable "aws_region" {
description = "The AWS region to create resources in."
type = string
default = "us-east-1" # Choose your preferred region
}
variable "ami_id" {
description = "The AMI ID for the EC2 instance. Find AMIs in the AWS Console (e.g., search for 'Amazon Linux 2' or 'Ubuntu'). Note: AMI IDs are region-specific."
type = string
# Example AMI IDs (check for the latest/correct one for your region):
# Amazon Linux 2 (us-east-1): ami-0cff7528ff565fb58
# Ubuntu 22.04 LTS (us-east-1): ami-053b0d53c279acc90
# default = "ami-0cff7528ff565fb58" # Example: Amazon Linux 2 in us-east-1
}
variable "instance_type" {
description = "The EC2 instance type."
type = string
default = "t2.micro" # Free tier eligible type
}
variable "key_name" {
description = "The name of the EC2 Key Pair to use for SSH access. This key pair must already exist in your AWS account in the specified region."
type = string
# default = "my-aws-key" # Replace with your key pair name if desired, or set via TF_VAR_key_name or terraform.tfvars
}
variable "ssh_location" {
description = "The IP address range allowed to SSH into the instance (CIDR notation). Use '0.0.0.0/0' with caution, or specify your specific IP."
type = string
default = "0.0.0.0/0" # WARNING: Allows SSH from ANY IP address. Replace with your IP like "YOUR_IP/32" for better security.
}
variable "instance_name_tag" {
description = "Value for the Name tag on the EC2 instance."
type = string
default = "MyTerraformInstance"
}
variable "environment_tag" {
description = "Value for the Environment tag."
type = string
default = "development"
}
3. outputs.tf
output "instance_id" {
description = "The ID of the created EC2 instance."
value = aws_instance.web_server.id
}
output "instance_public_ip" {
description = "The public IP address of the created EC2 instance."
value = aws_instance.web_server.public_ip
}
output "instance_private_ip" {
description = "The private IP address of the created EC2 instance."
value = aws_instance.web_server.private_ip
}
output "security_group_id" {
description = "The ID of the created security group."
value = aws_security_group.web_server_sg.id
}
How to Use:
-
Prerequisites:
- Install Terraform: https://learn.hashicorp.com/tutorials/terraform/install-cli
- AWS Account & Configure Credentials: Ensure your AWS CLI is configured (
aws configure) or you have environment variables set (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION).
- Create an EC2 Key Pair: Go to the EC2 console in your chosen AWS region, navigate to "Key Pairs", and create one if you don't have one. Note its exact name.
-
Prepare:
- Save the code blocks above into the files (
provider.tf, variables.tf, outputs.tf) in a new directory.
- Crucially: Find a valid AMI ID for the
ami_id variable in your chosen region (e.g., us-east-1). You can find these in the EC2 launch wizard in the AWS console.
- Update the
key_name variable (or set the environment variable TF_VAR_key_name) to the name of the key pair you created.
- Update the
ssh_location variable to your specific IP address (e.g., "72.14.182.21/32") for better security, instead of the default 0.0.0.0/0. You can find your IP by searching "what is my IP" in Google.
-
Run Terraform:
- Open your terminal or command prompt.
- Navigate to the directory where you saved the files.
- Run
terraform init to initialize the Terraform workspace and download the AWS provider.
- Run
terraform fmt to format the code nicely.
- Run
terraform validate to check for syntax errors.
- Run
terraform plan to see what resources Terraform will create. Review the plan carefully.
- Run
terraform apply to create the EC2 instance. Type yes when prompted.
-
Connect: