Andrew Mercer
on this page
Page Covers
This page Concepts, workflow, first configuration
CLI reference Every command you'll use, grouped by task

What Terraform is

Terraform is a declarative infrastructure-as-code tool. You describe the infrastructure you want in HCL files; Terraform compares that with what exists, proposes a plan to close the gap, and executes it through providers that call cloud and platform APIs.

     .tf files                state                       real world
  (desired state)      (last known mapping)              (cloud APIs)
         │                     │                              │
         └──────────┬──────────┘                              │
                    ▼                                         │
             terraform plan  ◄────── refresh (read) ──────────┤
                    │                                         │
          diff: create / update / replace / destroy           │
                    ▼                                         │
             terraform apply ─────── provider CRUD calls ─────┘
                    │
                    ▼
               new state

Three ideas carry most of the weight:

  1. Declarative. You say what, not how. No "if it doesn't exist, create it". Terraform works out the steps.
  2. State. Terraform remembers which real objects it manages and their last-known attributes (state management).
  3. The graph. References between objects determine order and parallelism (dependencies).

Terraform vs configuration management: Terraform provisions (creates the VM, network, database). Ansible, cloud-init and friends configure what runs inside. Terraform vs Kubernetes controllers: Terraform runs when you run it; controllers reconcile continuously. These tools complement each other.

Building blocks

Providers

Plugins that know one API. Declared in required_providers, configured with provider blocks (providers).

Resources

Objects Terraform manages through their whole lifecycle:

resource "azurerm_resource_group" "app" {
  name     = "rg-app-dev-cc"
  location = "canadacentral"
}

azurerm_resource_group is the type (the prefix names the provider), app is the local name (label). Together they form the address azurerm_resource_group.app. Arguments you set are inputs; attributes the provider returns (like id) are available after creation.

Data sources

Read-only lookups of things that already exist, managed elsewhere or by nobody:

data "azurerm_client_config" "current" {}

data "azurerm_virtual_network" "hub" {
  name                = "vnet-hub-cc"
  resource_group_name = "rg-connectivity"
}

Refer to them as data.azurerm_virtual_network.hub.id.

Variables, outputs, locals, modules

Inputs, return values, named expressions and reusable packages. See variables, outputs and locals and modules.

A first configuration

# versions.tf
terraform {
  required_version = "~> 1.16"
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 4.40"
    }
  }
}

# providers.tf
provider "azurerm" {
  features {}
  subscription_id     = var.subscription_id
  storage_use_azuread = true   # needed because the storage account below disables shared keys
}

# variables.tf
variable "subscription_id" {
  type        = string
  description = "Target subscription."
}

variable "env" {
  type    = string
  default = "dev"
}

# main.tf
locals {
  tags = { environment = var.env, managed_by = "terraform" }
}

resource "azurerm_resource_group" "app" {
  name     = "rg-demo-${var.env}-cc"
  location = "canadacentral"
  tags     = local.tags
}

resource "azurerm_storage_account" "logs" {
  name                            = "stdemo${var.env}logs001"
  resource_group_name             = azurerm_resource_group.app.name
  location                        = azurerm_resource_group.app.location
  account_tier                    = "Standard"
  account_replication_type        = "LRS"
  min_tls_version                 = "TLS1_2"
  allow_nested_items_to_be_public = false
  shared_access_key_enabled       = false
  tags                            = local.tags
}

# outputs.tf
output "storage_account_id" {
  value = azurerm_storage_account.logs.id
}
az login
export TF_VAR_subscription_id=$(az account show --query id -o tsv)

terraform init            # download providers, set up backend
terraform fmt             # format
terraform validate        # check syntax and types
terraform plan -out=tfplan
terraform apply tfplan    # apply exactly what you reviewed
terraform output
terraform destroy         # clean up

The core workflow

terraform init

Prepares the working directory: downloads providers (respecting .terraform.lock.hcl), downloads modules, configures the backend. Run it after cloning, and after changing providers, modules or backend config. Safe to re-run.

terraform plan

  1. Refresh: read each managed object from the API to detect drift.
  2. Diff: compare configuration against refreshed state.
  3. Propose actions.

Save the plan (-out=tfplan) whenever you'll apply it, so apply does exactly what you reviewed.

terraform apply

Executes the plan. With a saved plan file, no prompt and no re-plan. Without one, it plans again and asks for confirmation. State is written as each resource completes, so an interrupted apply leaves an accurate partial state.

terraform destroy

Plans and executes deletion of everything in state (equivalent to terraform apply -destroy). In shared environments it should essentially never be run by hand.

Reading plan output

Symbol Meaning
+ Create
- Destroy
~ Update in place
-/+ Destroy, then create (replacement)
+/- Create, then destroy (replacement with create_before_destroy)
<= Read (data source deferred to apply)
# forces replacement This attribute change can't be done in place
(known after apply) Value unknown until the API returns it
(sensitive value) Redacted
has moved to A moved block renamed the address
will be imported An import block adopts an existing object

More on reviewing plans in practices.

The resource lifecycle

     (not in state)
          │ + create
          ▼
       managed ──── ~ update in place ────┐
          │  ▲                            │
          │  └────────────────────────────┘
          │ -/+ replace (immutable attribute changed, -replace, replace_triggered_by)
          │ - destroy (block removed, or terraform destroy)
          ▼
     (not in state)

What happens on change depends on the provider's schema: some attributes update in place, others force replacement. A storage account's account_replication_type from LRS to GRS updates in place; changing its name forces replacement. The plan always tells you which.

Control the lifecycle with the lifecycle block: create_before_destroy, prevent_destroy, ignore_changes, replace_triggered_by.

Where to go next

  1. HCL language: types, expressions, loops, conditionals, functions
  2. Modules: packaging and reuse
  3. State: backends, locking, refactoring
  4. Multi-environment configuration
  5. Development practices and hygiene
in this section
* cli reference