So You’re Terraforming Your First EC2 + S3 Bucket? Cool, Let’s Go

You’ve got AWS credentials exported in your shell (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, maybe AWS_SESSION_TOKEN if you’re on temp creds). Terraform will just pick those up automatically — no need to hardcode anything. Good, let’s not do that ever.

1. Make a folder, make a file

mkdir my-first-tf && cd my-first-tf
touch main.tf

2. Tell Terraform which cloud and region

provider "aws" {
region = "us-west-2"
}

That’s it. No access keys in the file — it reads them from your environment.

3. Spin up an EC2 instance

resource "aws_instance" "my_first_ec2" {
ami = "ami-0c101f26f147fa7fd" # Amazon Linux 2023, us-west-2
instance_type = "t2.micro"
tags = {
Name = "my-first-terraform-box"
}
}

AMI IDs are region-specific. If you’re not in us-east-1, grab the right one from the AWS console (EC2 → Launch Instance → copy the AMI ID before hitting launch).

4. Create an S3 bucket

resource "aws_s3_bucket" "my_first_bucket" {
bucket = "my-first-tf-bucket-change-this-name-12345"
}

Bucket names are globally unique across all of AWS, so my-bucket is taken. Add your name, a random number, whatever — just make it unique.

5. The magic three commands

terraform init # downloads the AWS provider plugin
terraform plan # shows you what it's ABOUT to do (read this!)
terraform apply # actually does it (type "yes" when prompted)

init only needs to run once per project (or when you add new providers). plan and apply are your daily drivers.

6. Check your work

terraform show

Or just go look in the AWS console — your instance and bucket should be sitting there.

7. Clean up (seriously, do this)

terraform destroy

EC2 instances and S3 buckets cost money if left running. Don’t be the person who leaves a t2.micro running for six months and gets a surprise bill.

Quick tips before you go

  • Never commit .tfstate files to git — they can contain sensitive data.
  • Add a .gitignore with .terraform/, *.tfstate, *.tfstate.backup.
  • Run terraform fmt to auto-format your files so they don’t look like a mess.
  • If plan shows something you didn’t expect, stop and read it again before apply. Terraform does exactly what you tell it to, including deleting things.

That’s the whole loop: initplanapplydestroy. Everything else is just more resources.

Leave a comment

Blog at WordPress.com.

Up ↑