Lesson 3 of 3 Backends and State Locking

Configuring Remote Backends

Remote backends store state where the whole team can reach it. This lesson covers the backend block, partial configuration, migrating between backends and reading another configuration's outputs.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe a backend block and its restrictions.
  • Explain partial configuration and backend migration.
  • Describe how terraform_remote_state reads another configuration's outputs.

The backend block

A backend block inside the terraform block selects a backend type and its settings. The following example stores state in Amazon S3 with native locking.

terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "network/prod/terraform.tfstate"
    region       = "eu-west-1"
    encrypt      = true
    use_lockfile = true
  }
}

Built-in backend types include s3, azurerm, gcs, consul, pg, kubernetes, http, cos, oss, local and remote; each has its own arguments. A configuration can have only one backend, and HCP Terraform uses the separate cloud block instead of a backend block.

Backends are initialised before Terraform evaluates anything else, so backend arguments cannot use variables, locals or data sources. Credentials should not appear in the block; the S3 backend, for example, uses the same credential sources as the AWS CLI. For S3, enable bucket versioning so that earlier state versions can be recovered.

Spot the bug

A backend block that will not initialise

Exam skills 6.3.1

Find the lines that make this backend block fail or unsafe.

Log in to try this activity Interactive activities are free with an account.

Partial configuration

Because variables are not allowed, Terraform supports partial configuration: some or all arguments are left out of the block and supplied when initialising.

# backend.tf
terraform {
  backend "s3" {}
}

# prod.s3.tfbackend
bucket       = "acme-terraform-state"
key          = "network/prod/terraform.tfstate"
region       = "eu-west-1"
use_lockfile = true

# Initialise with the file, or with individual values
terraform init -backend-config=prod.s3.tfbackend
terraform init -backend-config="key=network/test/terraform.tfstate"

Partial configuration keeps environment-specific values and any sensitive settings out of the configuration and lets one configuration use different state locations per environment. Values not supplied by file or flag are requested interactively. Terraform stores the resulting settings in .terraform/terraform.tfstate, so later commands do not need the flags again.

The following diagram shows a backend block, per-environment files and the init command.

Choosing a backend key per environment with partial configuration. Backend blocks are evaluated before variables, so an interpolated key fails. The key moves into dev.s3.tfbackend and prod.s3.tfbackend files, and each pipeline runs init -reconfigure with its file, so state is never migrated between environments.
The bucket name is illustrative.

Migrating between backends

When the backend configuration changes, for example from local to S3, from one bucket to another, or from S3 to HCP Terraform, Terraform detects the change on the next terraform init. The options control what happens to existing state.

CommandEffect
terraform initDetects the change and asks whether to copy existing state to the new backend
terraform init -migrate-stateCopies existing state to the new backend, asking for confirmation
terraform init -reconfigureUses the new backend without migrating; existing state stays where it was

Removing the backend block and running init with -migrate-state moves state back to the local backend. After a successful migration to a remote backend, delete the local terraform.tfstate files so that no one uses them by mistake.

Match the pairs

Changing backends

Exam skills 6.3.2

Match each goal with the init command that achieves it.

Log in to try this activity Interactive activities are free with an account.

Reading outputs from remote state

The terraform_remote_state data source reads the root module outputs of another configuration's state, which lets separately managed configurations share values such as subnet IDs.

data "terraform_remote_state" "network" {
  backend = "s3"
  config = {
    bucket = "acme-terraform-state"
    key    = "network/prod/terraform.tfstate"
    region = "eu-west-1"
  }
}

resource "aws_instance" "app" {
  subnet_id = data.terraform_remote_state.network.outputs.private_subnet_ids[0]
  # ...
}

Only root outputs are exposed through .outputs, but the reader needs read access to the whole state file, which may contain secrets. HashiCorp therefore suggests publishing shared values through a dedicated store, such as AWS Systems Manager Parameter Store, or, in HCP Terraform, using the tfe_outputs data source, which grants access to outputs only.

True or false

terraform_remote_state

Exam skills 6.3.3

Check how terraform_remote_state shares values between configurations.

Log in to try this activity Interactive activities are free with an account.
Worked example

One configuration, many environments

A team wants the same network configuration to store dev and prod state in different S3 keys, and tries key = "network/${var.env}/terraform.tfstate". Init fails with an error that variables are not allowed.

The decisive rule is that backend blocks are evaluated before variables.

The team leaves key out of the block and creates dev.s3.tfbackend and prod.s3.tfbackend files. Each environment's pipeline runs terraform init -reconfigure -backend-config=prod.s3.tfbackend before planning. -reconfigure is used because the directory may have been initialised for another environment, and state must not be migrated between them.

Check yourself

How do you supply a backend bucket name that differs per environment?

Show answer

Use partial configuration: omit it from the backend block and pass it with terraform init -backend-config.

Exam Tips

Remember for the exam

  • backend blocks cannot use variables; use partial configuration with -backend-config.
  • One backend per configuration; HCP Terraform uses the cloud block.
  • init -migrate-state copies state; -reconfigure switches without copying.
  • terraform_remote_state reads root outputs but needs access to the full state.