Terraform basics: providers, resources, plan/apply
Provision a VPC and EC2 instance from code.
By Invicly Tech, , in Full DevOps with Python. About 12 minutes to read.
In short
Terraform describes infrastructure in HCL files and makes the real cloud match them. You always preview changes with plan before apply changes anything.
Explained simply
Terraform lets you describe servers, networks and databases in text files instead of clicking in a web console. You write what you want, for example one network and one server, and Terraform works out the API calls needed to make the cloud look like that.
The files use a language called HCL (HashiCorp Configuration Language). It is made of blocks: a provider block says which cloud to talk to, resource blocks describe things to create, and output blocks print useful values such as an IP address.
The daily work is three commands. terraform init downloads the plugins. terraform plan shows a preview: what will be created, changed or deleted. terraform apply does it. Because the files live in Git, every change to your infrastructure can be reviewed like code.
Terraform remembers what it created in a state file. Next time, it compares your code, the state and the real cloud, and changes only the differences. When you are done, terraform destroy removes everything it made, so a test environment costs nothing overnight.
Press Play on a diagram to walk through it one step at a time.
- 1Write HCL
Provider, resources, variables and outputs.
- 2terraform init
Downloads providers and sets up the backend.
- 3terraform plan
Shows what will be created, changed or destroyed.
- 4terraform apply
Makes the changes and updates state.
- 5Change the code
Edit config and plan again.
- Back to step 1
- 1Your HCL code
resource aws_instance web
- 2Terraform core
Builds the graph, plans, keeps state
- 3AWS provider plugin
Turns resources into API calls
- 4AWS APIs
EC2 RunInstances, CreateVpc and more
- 5Real infrastructure
The VPC and instance in your account
In depth
Installing Terraform and configuring the AWS provider
Install Terraform from HashiCorp's package repository (apt, dnf or brew via the hashicorp/tap) and check it with terraform version. Since version 1.6, Terraform uses the Business Source License; OpenTofu is a community fork with the same commands under the name tofu.
In a terraform block, declare required_providers with a source (hashicorp/aws) and a version constraint such as ~> 6.0, which allows 6.x updates but not 7.0. terraform init downloads the provider and writes .terraform.lock.hcl with the exact version and checksums. Commit that lock file so everyone and CI use the same provider build; do not commit the .terraform folder.
The AWS provider finds credentials the same way the AWS CLI does: environment variables, a profile in ~/.aws (including SSO logins), or an IAM role on the machine running Terraform. Never write access keys into .tf files. Set the region in the provider block and add default_tags so every resource gets owner and project tags automatically.
- Commit .terraform.lock.hcl; ignore .terraform/ and *.tfstate
- ~> 6.0 means at least 6.0 and below 7.0
- Credentials come from env vars, profiles or roles, never .tf files
How Terraform decides what to do
Terraform reads all .tf files in the folder as one configuration; file names only help humans. When one resource refers to another, like vpc_id = aws_vpc.main.id, Terraform records a dependency. From all these references it builds a graph and creates resources in the right order, running independent ones in parallel (10 at a time by default).
During plan, Terraform refreshes: it asks AWS for the current settings of every resource in state. It then compares three things: your code (desired), the state (what it created before) and reality (what AWS reports). Any difference becomes a planned action.
The plan uses symbols. A plus sign means create, a minus sign means destroy, a tilde means update in place, and -/+ means the resource must be replaced: destroyed and created again. Replacement happens when you change an attribute that AWS cannot modify on a live resource, such as a subnet's CIDR block. That is the line to look for before you type yes.
- 1Parse .tf files
All files in the folder form one config
- 2Build the graph
References decide the order
- 3Refresh
Read real settings from AWS
- 4Diff
Code vs state vs reality
- 5Show actions
+ create, ~ update, -/+ replace, - destroy
Building a VPC that actually routes traffic
An aws_vpc alone is an empty private network. To make a public subnet that can reach the internet you need four more pieces. An aws_subnet with a CIDR inside the VPC range and an availability zone. An aws_internet_gateway attached to the VPC. An aws_route_table with a route for 0.0.0.0/0 pointing to that gateway. And an aws_route_table_association that links the subnet to the route table. A subnet is called public only because its route table sends traffic to an internet gateway.
Set map_public_ip_on_launch = true on the public subnet so instances there get a public IP. Private subnets use a separate route table with no internet gateway route; if they need outbound access, they route to a NAT gateway, which costs money per hour.
Use the aws_availability_zones data source instead of typing zone names, so the code works in any region.
- aws_subnet.public
- 10.0.1.0/24 in one AZ
- map_public_ip_on_launch = true
- aws_internet_gateway.gw
- Attached to the VPC
- aws_route_table.public
- 0.0.0.0/0 to the gateway
- aws_route_table_association
- Links subnet to route table
- aws_security_group.web
- Allow 22 from your IP, 80 from anywhere
Outputs, data sources and launching EC2
A data source reads something that already exists without managing it. The classic example is finding the latest Ubuntu image: data "aws_ami" with most_recent = true, owners set to Canonical's account 099720109477, and a name filter. You then use data.aws_ami.ubuntu.id as the instance's ami. Because the lookup runs on each plan, a new Ubuntu release can trigger an instance replacement, so production teams often pin the AMI ID.
An aws_instance needs at least an ami and an instance_type, such as t3.micro. Place it with subnet_id, protect it with vpc_security_group_ids, and set key_name to an existing EC2 key pair for SSH. user_data runs a script on first boot.
Outputs print values after apply, for example the public IP, and terraform output -raw public_ip gives just the value for scripts. Outputs marked sensitive = true are hidden in the console but still stored in state as plain text.
- data sources read; resources create and manage
- terraform output -raw name prints one value for scripts
- sensitive hides output on screen, not in state
Destroying cleanly and avoiding drift
terraform destroy builds the dependency graph in reverse and deletes everything in state: instances before subnets, subnets before the VPC. Run terraform plan -destroy first to see the list. If something fails, often because a resource created outside Terraform (like a hand-made security group) still uses the VPC, delete that blocker and run destroy again.
For important resources, add lifecycle { prevent_destroy = true }; Terraform will then refuse any plan that deletes it. create_before_destroy makes Terraform build the replacement before removing the old one, which avoids downtime for some resources.
Drift is when reality no longer matches the code, usually because someone changed a setting in the console. Plan will show it as a change back to the code. terraform plan -refresh-only shows drift without proposing fixes. The rule that prevents drift is simple: once a resource is managed by Terraform, change it only through Terraform.
- terraform plan -destroy previews a destroy
- lifecycle { prevent_destroy = true } guards key resources
- terraform state list shows everything Terraform manages
Learn it in 6 short steps
About 1h each. Track them with a timer in your plan.
- 1Install Terraform and configure the AWS provider~1h
- 2Write resources for a VPC~1h
- 3Run init, plan and apply~1h
- 4Use outputs and data sources~1h
- 5Launch an EC2 instance from code~1h
- 6Destroy everything cleanly~1h
Key points
- A provider plugin talks to an API; resources are the things it creates.
- Read every plan, especially lines marked destroy or must be replaced.
- Data sources look up existing things, like the latest Ubuntu AMI.
- terraform destroy removes everything the configuration created.
Key terms
Tap a card to flip it. 0/5 known
Examples
provider "aws" { region = "us-east-1" }
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
tags = { Name = "demo" }
}
resource "aws_subnet" "public" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
}
output "vpc_id" { value = aws_vpc.main.id }A VPC and subnet; run init, plan and apply.
Launch an Ubuntu EC2 instance in your public subnet
This continues the explainer's VPC. Step 1: a data source finds the newest Ubuntu 24.04 image from Canonical. Step 2: the instance uses it and sits in the public subnet (add key_name with an existing key pair if you want SSH). Step 3: user_data installs nginx on first boot. Step 4: an output prints the public IP. Run terraform plan, check it says 1 to add, then apply and open the IP in a browser (the security group must allow port 80).
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-*"]
}
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
subnet_id = aws_subnet.public.id
vpc_security_group_ids = [aws_security_group.web.id]
user_data = "#!/bin/bash\napt-get update && apt-get install -y nginx"
}Read a plan that wants to replace something
You changed the subnet CIDR from 10.0.1.0/24 to 10.0.2.0/24 and ran plan. Step 1: look at the summary line: 1 to add, 0 to change, 1 to destroy. Step 2: find the resource marked -/+ and the attribute with the comment forces replacement. Step 3: notice the instance in that subnet is also replaced, because its subnet_id will change. Step 4: decide: if this is not what you want, revert the code. Saving the plan with -out and applying that file guarantees apply does exactly what you reviewed.
terraform fmt && terraform validate
terraform plan -out=tfplan
# -/+ resource "aws_subnet" "public" {
# ~ cidr_block = "10.0.1.0/24" -> "10.0.2.0/24" # forces replacement
# Plan: 2 to add, 0 to change, 2 to destroy.
terraform show tfplan # review the saved plan again
terraform apply tfplan # applies exactly this plan, no new promptQuick reference
- terraform init downloads providers; rerun after adding a provider or module
- terraform fmt formats files; terraform validate checks syntax and references
- terraform plan -out=tfplan then terraform apply tfplan applies exactly what you reviewed
- Plan symbols: + create, ~ update in place, -/+ replace, - destroy
- Commit .terraform.lock.hcl; never commit .terraform/ or terraform.tfstate
- Canonical's AWS account ID for official Ubuntu AMIs is 099720109477
- terraform state list shows managed resources; terraform output -raw x prints one value
- terraform plan -destroy previews what terraform destroy would delete
Common mistakes
- Changing resources by hand in the console, causing drift from the code.
- Running apply without reading the plan and replacing a database by accident.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Add a terraform block that pins the AWS provider to version 6.x and requires Terraform 1.10 or newer, then initialise and confirm the versions.
- Exercise 2medium
Make the public subnet actually reach the internet: add an internet gateway, a route table with a default route and the association.
- Exercise 3hard
Create one public subnet per availability zone (first two zones in the region) using a data source and count, with CIDRs 10.0.0.0/24 and 10.0.1.0/24 computed, and output all subnet IDs.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between Terraform and Ansible?
- Terraform creates and deletes infrastructure such as networks, servers and databases, and tracks them in state. Ansible configures what runs inside servers, such as packages and config files. Many teams use Terraform to build the server and Ansible to set it up.
- Is Terraform still free to use?
- Yes for normal use: the Business Source License lets you use Terraform to manage your own infrastructure. It restricts building competing commercial products. OpenTofu is an open-source fork if your company needs that.
- What happens if I delete the state file?
- Terraform forgets the resources but they keep running in AWS. A new apply would try to create duplicates, so you would have to import them back. This is why state belongs in a versioned remote backend.
- Can Terraform manage resources I created by hand?
- Yes. Add an import block (or run terraform import) with the resource address and its real ID, write matching configuration, and run plan until it shows no changes.