(01)Initialize and apply
Linux
1terraform init2terraform plan3terraform apply -auto-approve4terraform output instance_public_ip5ssh -i ~/.ssh/mykey.pem ubuntu@$(terraform output -raw instance_public_ip)main.tf
1terraform {2 required_providers {3 aws = {4 source = "hashicorp/aws"5 version = "~> 5.0"6 }7 }8}9 10provider "aws" {11 region = var.aws_region12}13 14resource "aws_security_group" "ubuntu_sg" {15 name = "ubuntu-sg"16 description = "Allow SSH and HTTP"17 18 ingress {19 from_port = 2220 to_port = 2221 protocol = "tcp"22 cidr_blocks = ["0.0.0.0/0"]23 }24 25 ingress {26 from_port = 8027 to_port = 8028 protocol = "tcp"29 cidr_blocks = ["0.0.0.0/0"]30 }31 32 egress {33 from_port = 034 to_port = 035 protocol = "-1"36 cidr_blocks = ["0.0.0.0/0"]37 }38}39 40resource "aws_instance" "ubuntu" {41 ami = var.ami42 instance_type = var.instance_type43 key_name = var.key_name44 vpc_security_group_ids = [aws_security_group.ubuntu_sg.id]45 46 tags = {47 Name = "Ubuntu-EC2"48 }49}variables.tf
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 region8}9 10variable "instance_type" {11 default = "t2.medium"12}13 14variable "key_name" {15 description = "Existing EC2 key pair name"16}outputs.tf
1output "instance_public_ip" {2 value = aws_instance.ubuntu.public_ip3}4 5output "instance_id" {6 value = aws_instance.ubuntu.id7}What to add before production merge
| Aspect | Minimal | Production |
|---|---|---|
| State backend | local state file | S3 + locking (DynamoDB or native lockfile) |
| Workspaces | default only | workspace per env (dev/staging/prod) |
| Locking | no lock | never force-unlock without confirming no running apply |
| Plan/apply | apply from laptop | CI plan on PR; apply from pipeline with approval |
| Secrets | vars in tfvars committed | TF_VAR_* from CI secrets; no secrets in git |
| Drift | ignored | scheduled plan + alert on drift |
Step 01
1terraform init2terraform plan3terraform apply -auto-approve4terraform output instance_public_ip5ssh -i ~/.ssh/mykey.pem ubuntu@$(terraform output -raw instance_public_ip)1terraform destroy -auto-approve