Terraform Labs · Lab 1 of 9
Your First Terraform Project: Plan, Apply, Destroy
Build a small Terraform project on your own computer, with no cloud account: pin providers, declare variables, create resources, read outputs, change an input and watch Terraform replace a resource, then destroy everything.
- Environment
- Local
- Level
- Beginner
- Time
- About 30 min
- Cost
- Free
You will build
A four-file Terraform project that generates a config file with a random server name, and the habit of reading every plan before you apply it.
Before you start
Terraform 1.6 or newer (
terraform version)A terminal and a text editor
This lab uses two providers that need no cloud account: random (generates values) and local (writes files).
Everything you learn here — init, plan, apply, state, outputs, destroy — works exactly the same with AWS,
Azure or Google Cloud later.
How Terraform works
You describe the result you want in .tf files. init downloads the providers (plugins that talk to an
API — here random and local; later aws, google, azurerm). plan compares your files with the
state (Terraform's record of what it created) and the real world, and lists the differences. apply makes
those changes through the providers and updates the state.
What you will build
Two inputs feed two resources. local_file.config uses random_pet.server.id, so Terraform creates the name
first; you never write the order yourself.
Your random server name will differ from the one shown below; everything else should match.
Project structure
hello-terraform/ ├── .gitignore ├── versions.tf # Terraform and provider versions ├── variables.tf # inputs: project, environment ├── main.tf # resources: random_pet, local_file ├── outputs.tf # values printed after apply └── out/ # created by Terraform (git-ignored)
Steps
-
1Create the project folder
Make an empty folder and create the files below in it (or download the starter files above). Splitting a configuration by purpose is a convention, not a rule: Terraform reads every
.tffile in the folder together.Run mkdir hello-terraform && cd hello-terraformCheck:lsshowsversions.tf,variables.tf,main.tf,outputs.tfand.gitignore. -
2Pin Terraform and the providers
versions.tfsays which Terraform version the project needs and which providers to download.~> 2.5means "2.5 or newer, but below 3.0", so you get fixes without surprise major upgrades.versions.tf terraform { required_version = ">= 1.6" required_providers { local = { source = "hashicorp/local" version = "~> 2.5" } random = { source = "hashicorp/random" version = "~> 3.6" } } }Hint
Without
required_providers, Terraform guesses the provider source. Always pin it. -
3Declare inputs with validation
variables.tfdeclares two inputs with types, defaults and descriptions. Thevalidationblock rejects bad values before anything is created.variables.tf variable "project" { description = "Project name, used in file names" type = string default = "shop" } variable "environment" { description = "dev, staging or prod" type = string default = "dev" validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "environment must be dev, staging or prod." } } -
4Describe the resources
main.tfcreates a random two-word name and a config file that uses it. Because the file's content refers torandom_pet.server.id, Terraform knows to create the name first — you never write the order.main.tf resource "random_pet" "server" { length = 2 } resource "local_file" "config" { filename = "${path.module}/out/${var.project}-${var.environment}.conf" content = <<-EOT project=${var.project} environment=${var.environment} server_name=${random_pet.server.id} EOT } -
5Add outputs
Outputs print useful values after
applyand let scripts and other configurations read them.outputs.tf output "server_name" { description = "Generated server name" value = random_pet.server.id } output "config_file" { description = "Path of the generated config file" value = local_file.config.filename } -
6Keep generated files out of Git
Provider downloads, state (which can hold secrets) and generated files never belong in Git.
.gitignore .terraform/ *.tfstate *.tfstate.* out/ -
7Initialise the project
initdownloads the providers into.terraform/and writes.terraform.lock.hclwith the exact versions.Run terraform initExpected output
Initializing the backend... Initializing provider plugins... - Finding hashicorp/local versions matching "~> 2.5"... - Finding hashicorp/random versions matching "~> 3.6"... - Installing hashicorp/local v2.9.1... - Installed hashicorp/local v2.9.1 (signed by HashiCorp) - Installing hashicorp/random v3.9.1... - Installed hashicorp/random v3.9.1 (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!
Check:A
.terraform.lock.hclfile exists. Commit it; never commit.terraform/.Hint
Newer provider versions may be installed for you; that's fine as long as they match the constraints.
-
8Format and validate
Run these before every commit.
fmt -checkprints nothing and exits 0 when the files are already formatted.Run terraform fmt -check terraform validateExpected output
Success! The configuration is valid.
Check:No file names printed by
fmt -check, and the validate success message. -
9Read the plan
planis a dry run.+means create. Values Terraform can't know yet, such as the random name, show as(known after apply).Run terraform planExpected output
Terraform will perform the following actions: # local_file.config will be created + resource "local_file" "config" { + content = (known after apply) ... + filename = "./out/shop-dev.conf" + id = (known after apply) } # random_pet.server will be created + resource "random_pet" "server" { + id = (known after apply) + length = 2 + separator = "-" } Plan: 2 to add, 0 to change, 0 to destroy. Changes to Outputs: + config_file = "./out/shop-dev.conf" + server_name = (known after apply)Check:Plan: 2 to add, 0 to change, 0 to destroy. -
10Apply
applyshows the plan again and asks foryes. (-auto-approveskips the question; use it only in labs and in CI after a reviewed plan.)Run terraform applyExpected output
random_pet.server: Creating... random_pet.server: Creation complete after 0s [id=exciting-chipmunk] local_file.config: Creating... local_file.config: Creation complete after 0s [id=e5aba4e6c7fe075f7cd6264a29445a90532ce88b] Apply complete! Resources: 2 added, 0 changed, 0 destroyed. Outputs: config_file = "./out/shop-dev.conf" server_name = "exciting-chipmunk"
Check:cat out/shop-dev.confprints three lines ending with your server name. -
11Inspect outputs and state
Terraform recorded what it created in
terraform.tfstate. Read it with commands, never by editing the file.-rawprints a single value without quotes, ready for scripts.Run terraform output terraform output -raw server_name terraform state listExpected output
config_file = "./out/shop-dev.conf" server_name = "exciting-chipmunk" exciting-chipmunk local_file.config random_pet.server
-
12Plan again: no changes
Nothing changed in the code or the real files, so Terraform has nothing to do. This is idempotency.
Run terraform planExpected output
No changes. Your infrastructure matches the configuration.
-
13Change an input and read the replacement
Changing the file name can't be done in place, so the plan shows
-/+(destroy, then create) and marks the argument with# forces replacement. The random name is unchanged: only resources whose inputs changed are touched.Run terraform plan -var environment=prodExpected output
# local_file.config must be replaced -/+ resource "local_file" "config" { ~ content = <<-EOT # forces replacement project=shop - environment=dev + environment=prod server_name=exciting-chipmunk EOT ... ~ filename = "./out/shop-dev.conf" -> "./out/shop-prod.conf" # forces replacement } Plan: 1 to add, 0 to change, 1 to destroy.Check:Plan: 1 to add, 0 to change, 1 to destroy.— therandom_petis not in the plan. -
14See validation reject a bad value
Run terraform plan -var environment=qaExpected output
Error: Invalid value for variable on variables.tf line 7: 7: variable "environment" { ├──────────────── │ var.environment is "qa" environment must be dev, staging or prod.Check:The plan stops with the error message you wrote; nothing is changed.
-
15Destroy everything
destroyremoves every resource in the state, in reverse dependency order.Run terraform destroyExpected output
Plan: 0 to add, 0 to change, 2 to destroy. ... local_file.config: Destroying... [id=e5aba4e6c7fe075f7cd6264a29445a90532ce88b] local_file.config: Destruction complete after 0s random_pet.server: Destroying... [id=exciting-chipmunk] random_pet.server: Destruction complete after 0s Destroy complete! Resources: 2 destroyed.
Check:terraform state listprints nothing andout/shop-dev.confis gone.
In production
This lab used local state, your own laptop and -auto-approve. A team running real infrastructure changes
each of those. The same four files stay; what surrounds them grows.
What changes
| In this lab | In production |
|---|---|
terraform.tfstate on your laptop |
Remote state (S3, GCS or Azure Blob) with locking and versioning, one state per environment |
You run plan and apply by hand |
CI runs fmt -check, validate and plan on every pull request; apply runs the reviewed, saved plan after merge |
-var environment=prod on the command line |
One folder (or one .tfvars file) per environment, so prod can't be applied by mistake |
| Defaults for every input | Required inputs with validation, so a missing value fails before anything changes |
| Your own credentials | Short-lived credentials for CI (OIDC to an IAM role or service account), no stored keys |
random_pet names |
A naming convention and tags (Project, Environment, Owner, ManagedBy = "terraform") on every resource |
Why the layout holds up
versions.tf, variables.tf, main.tf and outputs.tf is the layout most teams and public modules use, so
anyone can find their way around. Larger projects add providers.tf, locals.tf and data.tf, and move
reusable parts into modules/.
Production checklist
required_versionand providerversionconstraints set;.terraform.lock.hclcommitted- State stored remotely with locking; state bucket versioned and access-restricted
- Every input has a
typeand adescription; risky inputs havevalidation - No secrets in
.tfor.tfvarsfiles in Git terraform fmt -checkandterraform validaterun in CI- Plans are reviewed before apply; production applies need an approval
.gitignorecovers.terraform/, state files and generated output
Learn the concepts
- Terraform Get Started · Terraform Tutorial
- Terraform Variables · Terraform Tutorial
- Terraform Outputs · Terraform Tutorial
- Terraform State · Terraform Tutorial
- Terraform in Production · Course
Preparing for the Terraform Associate exam? Practice tests and mock exams →