Declarative

You describe the result; Terraform works out the steps

resource "aws_instance" "web" { count = 3 ami = "ami-0abc1234" instance_type = "t3.micro"}a resource: its type, and your name for ithow manywhich machine imagewhich sizeafter apply: 3 serversYou describe the result. Terraform works out the steps.This is declarative: the file says what should exist, not how to create it. Apply it to an emptyaccount and three servers appear. Apply it again and nothing happens, because the result is alreadythere. The files live in Git, so infrastructure gets branches, review and history like any code.

The file states what should exist, not how to build it.

Declarative · Going deeper · 1 of 2

Providers: one tool, many platforms

Terraformreads .tf files, plansProviders: pluginsThe platformsawsthe AWS APIazurermthe Azure APIgooglethe Google Cloud APIkubernetesthe Kubernetes APIgithubthe GitHub APIA provider is a plugin that turns resources into API calls for one platform.Terraform itself knows no cloud. terraform init downloads the providers a configuration asks for, atthe versions pinned in its lock file. The language and the workflow are the same everywhere; theresource types are not: an aws_instance is not an azurerm_linux_virtual_machine.

A provider translates resources into one platform's API calls.

count and for_each · Going deeper · 2 of 2

count numbers the copies; for_each names them

count: copies are numberedresource "aws_instance" "s" { count = length(var.names) tags = { Name = var.names[count.index] }}for_each: copies are namedresource "aws_instance" "s" { for_each = toset(var.names) tags = { Name = each.key }}names is ["web", "api", "db"]. Now remove "web" from the list and run plan:~ s[0] Name: "web" -> "api"~ s[1] Name: "api" -> "db"- s[2] the server that was dbPlan: 0 to add, 2 to change, 1 to destroy.- s["web"] s["api"] no change s["db"] no changePlan: 0 to add, 0 to change, 1 to destroy.Plan lines are shortened to show the effect.count identifies copies by position, so removing one shifts the rest. for_each identifies them by key.With count, Terraform sees s[0] and s[1] change their names and s[2] vanish: the machine that was db is destroyed and twoothers are relabelled. Use count for identical copies or an on-off switch (count = var.enabled ? 1 : 0), and for_each,over a map or a set of strings, when each copy has its own identity.

Use for_each when copies have identities: count shifts every index after a removal.

Plan and apply

plan compares what you want with what exists

Configurationthe .tf files: what you wantStatethe record of what Terraform builtReal infrastructurewhat exists in the cloudterraform plancompares the three, and prints Plan: 1 to add, 0 to change, 0 to destroy.terraform applycalls the API to create the missing server, and records it in the state.plan compares what you want with what exists. apply closes the gap.The state file maps every resource in the configuration to a real object and its id. Plan firstrefreshes that record from the real infrastructure, then lists the differences. Nothing changesuntil you have read the plan and approved the apply.

Configuration, state and reality: plan compares, apply closes the gap.

Plan and apply · Going deeper

The workflow, command by command

initdownloads providersand modulesfmttidies the layoutof the filesvalidatechecks syntaxand referencesplanshows whatwould changeapplymakes thechangesdestroyremoves all thatit managesSix commands cover the daily workflow.Run init once in each working directory, and again when providers, modules or the backend change.fmt and validate are cheap checks for a pipeline. In a team, plan runs on the pull request, so thatreviewers see its effect, and apply runs after the merge.

init, plan, apply. And fmt and validate before them.

Reading a plan

Read the plan: -/+ means destroy, then create again

# aws_instance.web[2] will be created + resource "aws_instance" "web" { ... } # aws_security_group.web will be updated in-place ~ ingress { from_port = 80 -> 443 } # aws_db_instance.main must be replaced-/+ resource "aws_db_instance" "main" { ... }Plan: 2 to add, 1 to change, 1 to destroy.+ create: something new~ change in place: the resource survives-/+ replace: destroy it, then create it againa replacement counts as one add and one destroyRead the plan before you apply. The symbol -/+ means destroy, then create again.Some settings cannot be changed on a live resource, so Terraform replaces the resource. For astateless server that is harmless. For a database it means the data is gone, unless there is abackup or a prevent_destroy rule. Check the summary line: is it what you meant to do?

+ creates, ~ changes in place, -/+ replaces.

lifecycle · Going deeper

lifecycle changes how Terraform replaces, protects or ignores a resource

Inside lifecycle { }EffectUse it forcreate_before_destroy = truebuild the replacement first, then destroy the old oneanything serving traffic; plan shows +/-prevent_destroy = truea plan that would destroy the resource fails insteaddatabases, buckets that hold dataignore_changes = [tags]differences in the listed attributes are left alonevalues another system managesreplace_triggered_by = [x]replace this resource whenever x changesservers built from a config or imageAs writtenresource "aws_db_instance" "main" { # ... lifecycle { prevent_destroy = true }}A plan that would destroy it (typical output)Error: Instance cannot be destroyedResource aws_db_instance.main haslifecycle.prevent_destroy set, but the plan calls forthis resource to be destroyed.lifecycle does not change what a resource is. It changes how Terraform replaces, protects or ignores it.prevent_destroy guards against a careless change, not a deliberate one: delete the whole resource block and the guardgoes with it. create_before_destroy needs names that can exist twice for a moment: use name_prefix where it is offered.

prevent_destroy makes a destructive plan fail. create_before_destroy avoids a gap.

Drift

A change made by hand is drift; apply will undo it

Configurationwhat you wantinstance_type"t3.micro"Statewhat Terraform builtinstance_type"t3.micro"Real infrastructurewhat exists nowinstance_type"t3.large"changed by hand in the consoleterraform plan~ instance_type = "t3.large" -> "t3.micro" Plan: 0 to add, 1 to change, 0 to destroy.Either apply, and the hand-made change is undone. Or edit the configuration to "t3.large", and the plan is empty.A change made by hand is drift, and the next apply will undo it.Terraform trusts the configuration, and treats any difference in the real infrastructure assomething to correct. So once a resource is managed by Terraform, change it only through Terraform.Fix by hand in an emergency if you must, and bring the code into line the same day.

Reality that differs from the configuration is treated as a mistake to correct.

Drift · Going deeper

Where the state lives

Engineer Aterraform applyEngineer Bterraform applyRemote statea storage bucket,or HCP Terraformholds the lockwaits: the state is locked✓shared: one record for everyone✓locked: one apply at a time✗never in Git: it can hold secretsThe state belongs in a shared, locked place, and never in Git.On one laptop the state is a local file, terraform.tfstate. A team stores it in a remote backend, sothat everyone plans against the same record and two applies cannot run at once. State can containpasswords in plain text: restrict access to it, encrypt it, and never edit it by hand.

Remote, locked, and never in Git.

Modules

A module is a blueprint; variables make each use differ

module "shop"a network, a load balancerand a number of serversof one sizedevservers = 1size = "small"dev: 1 small serverprodservers = 3size = "large"prod: 3 large serversA module is a blueprint. Variables make each use of it different.Input variables are a module's parameters, and outputs are what it hands back, such as the addressof the load balancer. Dev and prod are then built from the same code and differ in a few values,which is what makes a test in dev mean something. Pin the version of any module you did not write.

One module, many environments, each with its own variables.

Variable precedence · Going deeper

Six places can set a variable, and the last one loaded wins

variable "size" { type = string default = "small" validation { condition = contains(["small", "large"], var.size) error_message = "size must be small or large." }}Loaded in this order. A later one overrides an earlier one.1default in the variable block2TF_VAR_size (environment variable)3terraform.tfvars4terraform.tfvars.json5*.auto.tfvars (in alphabetical order)6-var and -var-file (in the order given)TF_VAR_size=small terraform apply -var="size=large"gives size = "large": the command line is loaded lastA variable can be set in six places. Terraform loads them in a fixed order, and the last value loaded wins.With no value anywhere and no default, Terraform asks at the prompt, or fails when run with -input=false, as pipelines do.validation rejects a bad value at plan time, before anything is built. sensitive = true hides a value in plan output,but it is still written to the state in plain text. Keep one .tfvars file per environment: -var-file=prod.tfvars.

The command line beats .tfvars files, which beat TF_VAR_ environment variables.

Lesson complete

You finished “Infrastructure as code”

Nicely done.

Open in a new tab