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

Members can save this page, take notes and track progress. See membership · Sign in

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.

Write .tf filesmain.tf, variables.tf…terraform initproviders, lock fileterraform planwhat would changeterraform applymake the changes.terraform/downloaded providersterraform.tfstatewhat Terraform managesReal infrastructurefiles, VMs, networks…writesreadsAPI callsrecords resultsplan also checks the real world (refresh)Edit → plan → review → apply, then repeat. terraform destroy removes everything in the state.
The Terraform workflow: init, plan and apply, and where state fits

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.

Inputs (variables.tf)var.project"shop"var.environment"dev" ✓ validatedResources (main.tf)random_pet.serverrandom providerlocal_file.configlocal provideridOutputs (outputs.tf)server_nameconfig_fileReferences create the order: random_pet first, then local_file, then outputs
Lab 1 dependency graph: inputs feed resources, references decide the order, outputs read the results

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)

Download starter filesDownload finished project

Steps

  1. 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 .tf file in the folder together.

    Run
    mkdir hello-terraform && cd hello-terraform
    
    Check:

    ls shows versions.tf, variables.tf, main.tf, outputs.tf and .gitignore.

  2. 2Pin Terraform and the providers

    versions.tf says which Terraform version the project needs and which providers to download. ~> 2.5 means "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.

  3. 3Declare inputs with validation

    variables.tf declares two inputs with types, defaults and descriptions. The validation block 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."
      }
    }
    
  4. 4Describe the resources

    main.tf creates a random two-word name and a config file that uses it. Because the file's content refers to random_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
    }
    
  5. 5Add outputs

    Outputs print useful values after apply and 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
    }
    
  6. 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/
    
  7. 7Initialise the project

    init downloads the providers into .terraform/ and writes .terraform.lock.hcl with the exact versions.

    Run
    terraform init
    

    Expected 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.hcl file 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.

  8. 8Format and validate

    Run these before every commit. fmt -check prints nothing and exits 0 when the files are already formatted.

    Run
    terraform fmt -check
    terraform validate
    

    Expected output

    Success! The configuration is valid.
    Check:

    No file names printed by fmt -check, and the validate success message.

  9. 9Read the plan

    plan is a dry run. + means create. Values Terraform can't know yet, such as the random name, show as (known after apply).

    Run
    terraform plan
    

    Expected 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.

  10. 10Apply

    apply shows the plan again and asks for yes. (-auto-approve skips the question; use it only in labs and in CI after a reviewed plan.)

    Run
    terraform apply
    

    Expected 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.conf prints three lines ending with your server name.

  11. 11Inspect outputs and state

    Terraform recorded what it created in terraform.tfstate. Read it with commands, never by editing the file. -raw prints a single value without quotes, ready for scripts.

    Run
    terraform output
    terraform output -raw server_name
    terraform state list
    

    Expected output

    config_file = "./out/shop-dev.conf"
    server_name = "exciting-chipmunk"
    exciting-chipmunk
    local_file.config
    random_pet.server
  12. 12Plan again: no changes

    Nothing changed in the code or the real files, so Terraform has nothing to do. This is idempotency.

    Run
    terraform plan
    

    Expected output

    No changes. Your infrastructure matches the configuration.
  13. 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=prod
    

    Expected 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. — the random_pet is not in the plan.

  14. 14See validation reject a bad value

    Run
    terraform plan -var environment=qa
    

    Expected 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.

  15. 15Destroy everything

    destroy removes every resource in the state, in reverse dependency order.

    Run
    terraform destroy
    

    Expected 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 list prints nothing and out/shop-dev.conf is 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_version and provider version constraints set; .terraform.lock.hcl committed
  • State stored remotely with locking; state bucket versioned and access-restricted
  • Every input has a type and a description; risky inputs have validation
  • No secrets in .tf or .tfvars files in Git
  • terraform fmt -check and terraform validate run in CI
  • Plans are reviewed before apply; production applies need an approval
  • .gitignore covers .terraform/, state files and generated output

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake