Terraform hands-on: your first EC2 instance with plan and apply
A beginner's walk through a first Terraform project on AWS: a provider, a data source for the Ubuntu AMI, a security group and one EC2 instance, then init, plan, apply and destroy, how to read the plan and what the state file is.
A while back I wrote a post on what Terraform is and why you'd version your infrastructure. It had no code in it. This is the follow-up I should have written then: one small project, start to finish, on a real AWS account.
In this blog we will create one EC2 instance running nginx, read the plan before anything happens, apply it, look at the state file and then destroy it all. Level: beginner. You need an AWS account, credentials for the AWS CLI on your machine and Terraform installed. I used Terraform 1.17.1 and the AWS provider 6.73.0 on a Mac.
Why I bother with this at all
My own blog runs on one EC2 instance in ap-south-1, and every piece of it (the instance, the Elastic IP, the backup bucket, SES) is in Terraform. Most of it got there by importing hand-built resources, because for years I had clicked everything together in the console. The day I wanted a second server, I had no idea how the first one was set up. That's the whole sales pitch, honestly. The code is the notes.
The project
Make an empty folder and put three files in it. First versions.tf, which pins Terraform and the provider.
terraform {
required_version = ">= 1.11"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
~> 6.0 means any 6.x version, never 7. Major versions of the AWS provider do break things, so I always pin the major.
Then main.tf. This is the whole thing.
provider "aws" {
region = "ap-south-1"
default_tags {
tags = {
Project = "tf-hands-on"
}
}
}
# Latest Ubuntu 24.04 image published by Canonical.
data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] # Canonical
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
}
resource "aws_security_group" "web" {
name = "tf-hands-on-web"
description = "HTTP in, everything out"
}
resource "aws_vpc_security_group_ingress_rule" "http" {
security_group_id = aws_security_group.web.id
cidr_ipv4 = "0.0.0.0/0"
from_port = 80
to_port = 80
ip_protocol = "tcp"
}
resource "aws_vpc_security_group_egress_rule" "all" {
security_group_id = aws_security_group.web.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "-1"
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
vpc_security_group_ids = [aws_security_group.web.id]
user_data = <<-EOT
#!/bin/bash
apt-get update -y
apt-get install -y nginx
echo "hello from terraform" > /var/www/html/index.html
EOT
metadata_options {
http_tokens = "required"
}
root_block_device {
volume_size = 8
volume_type = "gp3"
encrypted = true
}
tags = {
Name = "tf-hands-on"
}
}
And outputs.tf, so Terraform prints the useful bits at the end.
output "instance_id" {
value = aws_instance.web.id
}
output "ami_id" {
value = data.aws_ami.ubuntu.id
}
output "url" {
value = "http://${aws_instance.web.public_dns}"
}
Let us look at what's in there, because these few words are most of Terraform.
A provider is the plugin that talks to an API, here AWS in Mumbai. default_tags puts the Project tag on everything it creates, which makes it easy to find the stuff later in the console or in the bill.
A data source (data "aws_ami") only reads. It asks AWS for the newest Ubuntu 24.04 image owned by Canonical's account. I use this exact block for my blog server. Hardcoding an AMI ID works for a week and then you're running an old image, and AMI IDs are different in every region anyway.
A resource is something Terraform creates and owns. The names after the type (web, http, all) are only for Terraform, they never reach AWS. When one resource uses another's attribute, like aws_security_group.web.id, Terraform works out the order by itself. The group gets created first, then the rules and the instance.
A few choices I made on purpose. The instance doesn't have a key pair and port 22 is closed. I don't SSH into my servers anymore, I use SSM instead of SSH, and for a throwaway nginx box you don't need a shell at all. http_tokens = "required" turns on IMDSv2 only. The root disk is encrypted. None of this costs anything extra, so I just put it in from day one.
There's no VPC or subnet in the code. Without one, AWS puts the instance in your default VPC, which has public subnets. If you deleted your default VPC at some point, this will fail and you'll need a subnet_id.
terraform init
terraform init
This downloads the provider and writes a .terraform.lock.hcl file.
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 6.0"...
- Installing hashicorp/aws v6.73.0...
- Installed hashicorp/aws v6.73.0 (signed by HashiCorp)
Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.
Terraform has been successfully initialized!
Commit the lock file. My blog repo's lock file still says 6.72.0, this new folder got 6.73.0, and that is exactly the point of it: the version only moves when I run terraform init -upgrade. Don't commit .terraform/ though. The AWS provider binary on my Mac was 729 MB. I checked twice.
Two more commands before plan, both cheap.
terraform fmt
terraform validate
fmt fixes the indentation and lines up the = signs. validate catches typos and wrong argument names without calling AWS.
Reading the plan
terraform plan -out=web.tfplan
A small confession about the output below. I didn't want to start a real instance only to copy some text for a blog post, so I ran this plan against moto, a local AWS mock, with fake credentials. It's real Terraform output, but the AMI ID is a fake one from the mock. On your account you'll see a real Canonical image ID. I also cut the long instance block down.
data.aws_ami.ubuntu: Reading...
data.aws_ami.ubuntu: Read complete after 0s [id=ami-0123456789abcdef0]
Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_instance.web will be created
+ resource "aws_instance" "web" {
+ ami = "ami-0123456789abcdef0"
+ arn = (known after apply)
+ id = (known after apply)
+ instance_type = "t3.micro"
+ public_dns = (known after apply)
+ tags = {
+ "Name" = "tf-hands-on"
}
+ tags_all = {
+ "Name" = "tf-hands-on"
+ "Project" = "tf-hands-on"
}
...
}
# aws_security_group.web will be created
+ resource "aws_security_group" "web" {
+ description = "HTTP in, everything out"
+ id = (known after apply)
+ name = "tf-hands-on-web"
+ vpc_id = (known after apply)
...
}
...
Plan: 4 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ ami_id = "ami-0123456789abcdef0"
+ instance_id = (known after apply)
+ url = (known after apply)
How I read a plan. The data source line comes first, it ran already, so the AMI is a real value even in the plan. Then one block per resource with a symbol in front: + create, ~ update in place, - destroy, and -/+ destroy and create again (a replace). (known after apply) means AWS decides that value, like the instance ID.
Then I go straight to the last line, Plan: 4 to add, 0 to change, 0 to destroy. On a first run it's all adds, boring. On later runs this line is the one to read slowly. A -/+ on an instance means a new instance, new disk, new IP, and whatever was on the old disk is gone. I've had a plan want to replace a key pair on my live server once, it's in the import post, and I only caught it because I read the plan.
You can look at a saved plan again any time, it's just a file.
terraform show web.tfplan
Apply
terraform apply web.tfplan
When you apply a saved plan file, Terraform doesn't ask "yes" again, because you already reviewed it. If you run plain terraform apply instead, it makes a new plan, prints it and waits for you to type yes. I use the saved file for anything I care about. It means what gets applied is exactly what I read.
Instance takes a minute or two to boot and install nginx. Then the outputs show the URL.
terraform output url
curl "$(terraform output -raw url)"
You should get hello from terraform back. If curl hangs, give cloud-init another minute, apt was probably still running.
The state file
After apply there's a new file in the folder, terraform.tfstate. It's JSON, and it's how Terraform remembers that aws_instance.web in your code is that particular instance ID in AWS. On the next plan it reads the state, asks AWS for the current values and compares both to your code.
terraform state list
terraform state show aws_instance.web
Treat it as a secret. It holds every attribute of every resource, and some resources keep passwords and keys in there. This is why I keep IAM access keys out of Terraform completely, as I wrote in the SES SMTP post. Put the state files in .gitignore before your first commit.
.terraform/
*.tfstate
*.tfstate.*
*.tfplan
A local state file is fine while it's only you on one laptop. My blog infra still works that way. Once two people (or a laptop and a CI job) run Terraform, it needs to live somewhere shared with a lock, and that's the next post in this series.
Change something
Try one change to see an update. Add a tag to the instance, Owner = "me", and plan again. You'll get a ~ and 1 to change, and the instance stays where it is. Now change instance_type to t3.small and plan. Still in place, but AWS stops and starts the instance to do it. Some attributes force a replace instead, the plan marks those with # forces replacement. It's worth looking for that comment every single time.
Destroy
terraform destroy
It prints a plan full of - and asks for yes. Type it, wait a minute, and the instance, the rules and the security group are gone. Check the EC2 console after, a forgotten t3.micro is a small bill but it's still a bill.
There we have it. Next time you click something together in the console, try writing it as a resource first.