bashadvanced
Terraform AWS EC2 Instance Setup
Terraform configuration to provision an EC2 instance with VPC, security group, and SSH key pair.
bashPress ⌘/Ctrl + Shift + C to copy
# 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.
bashadvanced
Terraform — AWS S3 + CloudFront Static Site
Provision an S3 static website with CloudFront CDN, SSL certificate, and origin access control.
Best for: Deploying static sites with global CDN distribution
#terraform#aws
typescriptintermediate
AWS SDK v3 — S3 Operations in TypeScript
Perform S3 operations with AWS SDK v3: upload, download, list, presigned URLs, and multipart upload.
Best for: Server-side file uploads to S3
#aws#s3
bashadvanced
Terraform Aws
DevOps practice: terraform-aws
Best for: infrastructure management
#devops#infrastructure
bashadvanced
Aws Cdk
DevOps practice: aws-cdk
Best for: infrastructure management
#devops#infrastructure