Terraform AWS EC2 Instance Setup
Terraform configuration to provision an EC2 instance with VPC, security group, and SSH key pair.
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.region
}
variable "region" {
default = "us-east-1"
}
variable "instance_type" {
default = "t3.micro"
}
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
}
resource "aws_security_group" "web" {
name_prefix = "web-sg-"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
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"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
vpc_security_group_ids = [aws_security_group.web.id]
user_data = <<-EOF
#!/bin/bash
apt update && apt install -y nginx
systemctl enable nginx
EOF
tags = {
Name = "web-server"
}
}
output "public_ip" {
value = aws_instance.web.public_ip
}Sponsored
AWS Free Tier — Start building on AWS for free
Use Cases
- Provisioning cloud infrastructure with code
- Reproducible server setups across environments
- Automated cloud resource management
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
S3 Presigned URL Generator
Generate secure presigned URLs for S3 upload and download operations with expiry and content type.
Docker Compose Multi-Service Setup
Docker Compose configuration for a Node.js app with PostgreSQL, Redis, and Nginx reverse proxy.
Kubernetes Deployment Configuration
Production-ready Kubernetes deployment with replicas, resource limits, health checks, and rolling updates.
Nginx Reverse Proxy Configuration
Nginx config to reverse-proxy requests to a backend with WebSocket support and security headers.