🖥️
Dockerfile

Terraform AWS EC2 (Ubuntu)

Provision a Ubuntu EC2 instance with security group — Simple-Project pattern

📋Configuration Files

main.tf

yaml
1terraform {
2 required_providers {
3 aws = {
4 source = "hashicorp/aws"
5 version = "~> 5.0"
6 }
7 }
8}
9
10provider "aws" {
11 region = var.aws_region
12}
13
14resource "aws_security_group" "ubuntu_sg" {
15 name = "ubuntu-sg"
16 description = "Allow SSH and HTTP"
17
18 ingress {
19 from_port = 22
20 to_port = 22
21 protocol = "tcp"
22 cidr_blocks = ["0.0.0.0/0"]
23 }
24
25 ingress {
26 from_port = 80
27 to_port = 80
28 protocol = "tcp"
29 cidr_blocks = ["0.0.0.0/0"]
30 }
31
32 egress {
33 from_port = 0
34 to_port = 0
35 protocol = "-1"
36 cidr_blocks = ["0.0.0.0/0"]
37 }
38}
39
40resource "aws_instance" "ubuntu" {
41 ami = var.ami
42 instance_type = var.instance_type
43 key_name = var.key_name
44 vpc_security_group_ids = [aws_security_group.ubuntu_sg.id]
45
46 tags = {
47 Name = "Ubuntu-EC2"
48 }
49}

variables.tf

yaml
1variable "aws_region" {
2 default = "us-east-1"
3}
4
5variable "ami" {
6 description = "Ubuntu AMI ID for your region"
7 default = "ami-0c7217cdde317cfec" # Ubuntu 22.04 us-east-1 — update for your region
8}
9
10variable "instance_type" {
11 default = "t2.medium"
12}
13
14variable "key_name" {
15 description = "Existing EC2 key pair name"
16}

outputs.tf

yaml
1output "instance_public_ip" {
2 value = aws_instance.ubuntu.public_ip
3}
4
5output "instance_id" {
6 value = aws_instance.ubuntu.id
7}

Terraform: minimal vs production

What to add before production merge

AspectMinimalProduction
State backendlocal state fileS3 + locking (DynamoDB or native lockfile)
Workspacesdefault onlyworkspace per env (dev/staging/prod)
Lockingno locknever force-unlock without confirming no running apply
Plan/applyapply from laptopCI plan on PR; apply from pipeline with approval
Secretsvars in tfvars committedTF_VAR_* from CI secrets; no secrets in git
Driftignoredscheduled plan + alert on drift
📄

Step 01

Provision EC2

(01)Initialize and apply

Linux
1terraform init
2terraform plan
3terraform apply -auto-approve
4terraform output instance_public_ip
5ssh -i ~/.ssh/mykey.pem ubuntu@$(terraform output -raw instance_public_ip)

(02)Destroy when done

Linux
1terraform destroy -auto-approve