TL;DR
A step-by-step guide to getting started with Infrastructure as Code using Terraform to manage AWS resources.
How to Write Your First Terraform Script for AWS Infrastructure
Executive Summary
Your first Terraform configuration teaches you the whole model in miniature: declare resources in a file, preview the changes with plan, create them with apply, and let Terraform track everything in state. This guide walks through a complete first script for AWS — a VPC and a public subnet — explaining each concept as it appears: providers, resources, variables, outputs, and state. After reading it, you should be able to write, run, modify, and destroy a small AWS configuration with confidence, using the safety habits worth adopting while the stakes are low.
Why This Matters
The first configuration is where habits form, and habits formed on a tutorial have a way of surviving into production. A first script that hard-codes credentials teaches a pattern that later leaks. A first script run against local state teaches a workflow that breaks the day a colleague needs to collaborate. Conversely, a first script that pins the provider, takes inputs as variables, exposes results as outputs, and runs plan before apply scales directly into real work — the files get bigger, but the shape stays the same. Treat this exercise as building the template your future projects start from, not as a disposable demo.
Core Concepts
The Moving Parts
Five concepts cover everything in a first script:
aws_vpc or aws_subnet, declared with a type and a name.The workflow tying them together is always the same loop: terraform init prepares the working directory, terraform plan previews changes, terraform apply makes them, and terraform destroy removes everything when you are done.
Prerequisites
You need three things before starting:
aws configure, environment variables, or an SSO login. Terraform's AWS provider finds them through the standard credential chain; you never paste keys into a .tf file.The First Configuration
Create a directory and a main.tf containing a provider and two resources — a VPC, and a subnet inside it that references the VPC's ID:
# Configure AWS Provider
provider "aws" {
region = "us-west-2"
}
# Create VPC
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "main"
Environment = "production"
}
}
# Create Subnet
resource "aws_subnet" "public" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
tags = {
Name = "public"
}
}The reference aws_vpc.main.id is the important idea. Terraform sees that the subnet depends on a value only the VPC can provide, so it creates the VPC first and the subnet second — and destroys them in reverse order. You never write sequencing code; the dependency graph falls out of the references.
In practice you would also pin the provider version in a terraform block, so the configuration behaves identically on every machine:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}Running It
terraform init # download the provider, set up the working directory terraform plan # show what will be created, change nothing terraform apply # create the resources after you confirm the plan
Read the plan output before confirming. It lists every resource to be added, changed, or destroyed, and the attribute values Terraform already knows. After apply, Terraform writes terraform.tfstate in the directory — that file is the record linking aws_vpc.main to a real VPC ID, and it is why a second terraform plan correctly reports no changes. Change the subnet's CIDR in the file, plan again, and you will see Terraform propose replacing the subnet, because a subnet's CIDR block cannot be modified in place. That destroy-and-recreate behaviour, visible in the plan before anything happens, is the core safety property of the tool.
Variables and Outputs
Hard-coded values are fine for a first run and wrong for a second environment. Promote them to variables:
variable "region" {
description = "AWS region to deploy into"
type = string
default = "us-west-2"
}
variable "vpc_cidr" {
description = "CIDR block for the VPC"
type = string
default = "10.0.0.0/16"
}
provider "aws" {
region = var.region
}Outputs surface the values other people — or other configurations — will need:
output "vpc_id" {
description = "ID of the created VPC"
value = aws_vpc.main.id
}
output "public_subnet_id" {
description = "ID of the public subnet"
value = aws_subnet.public.id
}Run terraform output any time to read them back from state. A third mechanism, locals, names a computed expression once — a standard tag set, for example — and reuses it across resources.
State: Handle With Care From Day One
State commands you will meet early: terraform state list shows everything Terraform manages, terraform state show aws_vpc.main shows one resource's recorded attributes, and terraform state mv renames a resource in state when you refactor its label. Two rules matter more than any command. First, never edit the state file by hand. Second, the moment anyone else needs to run this configuration, move state out of the directory into a remote backend (for AWS, an S3 bucket with locking) — a state file on one laptop is a single point of failure and a collaboration blocker. State also contains resource attributes in plain text, so treat the file as sensitive even in a learning project.
Common First-Script Problems
aws sts get-caller-identity, and check that the credentials you configured are the ones in the shell running Terraform.terraform force-unlock; on a solo learning project with local state this is rare, but the habit of checking first is the point.terraform validate and by plan itself. Run terraform fmt to normalise formatting; most editors also flag HCL errors as you type.Security Basics Worth Starting With
Three practices cost nothing at this scale and everything if retrofitted later. Keep credentials out of code — use the credential chain described above. Encrypt state once it moves to a remote backend, and restrict who can read it. And apply least privilege to the credentials Terraform runs with: a learning project needs VPC permissions, not administrator access to the whole account.
Decision Framework
| Situation | Recommendation |
|---|---|
| Just learning, solo, disposable account | Local state, one file, hard-coded region is acceptable — destroy everything afterwards |
| Configuration will be reused or shared | Variables for inputs, outputs for IDs, provider pinned, state moved to a remote backend |
| Need compute or storage next | Add aws_instance or aws_s3_bucket resources the same way; look up AMIs with a data source instead of hard-coding an ID |
| Same layout needed in several environments | Keep one configuration, vary it with variable files per environment |
| Script is growing past a few hundred lines | Split into main.tf, variables.tf, outputs.tf, then extract repeated patterns into modules |
| Unsure whether a change is safe | Run plan and read the replacement lines; never apply a plan you have not read |
Implementation Checklist
terraform version runs.tf fileterraform blockterraform init, plan, and apply complete; a second plan reports no changesterraform fmt and terraform validate passterraform destroy has been run at least once, so cleanup is a known quantity, not a fearTrade-offs
A first script hides the costs that arrive with scale. Local state is effortless now and a liability later; the migration to a remote backend is easy but must actually happen. Terraform also only manages what it creates — it will not adopt the resources already in your account until you import them, and it cannot see changes made in the console except by refreshing state at plan time, which is why console edits and Terraform fight each other. Finally, the apply model is all-or-nothing per run: a failure halfway leaves some resources created and recorded in state, which is recoverable but surprises beginners who expected a transaction.
When Not to Use
Conclusion
A VPC, a subnet, and the init-plan-apply loop contain the entire Terraform model: declarative resources, a dependency graph built from references, and state recording the result. Learn it with the safety habits already in place — pinned providers, variables and outputs, no credentials in code, plans always read — and the step from this script to production configurations is one of size, not of kind.
References
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.