Backends¶
A backend determines:
- Where Terraform stores state snapshots
- How Terraform performs operations (local or remote)
Standard Backends¶
Standard backends only store state. Terraform operations run locally via the CLI.
Examples:
- AWS S3 (with DynamoDB locking)
- AzureRM (with locking)
- Google Cloud Storage (with locking)
- HashiCorp Consul (with locking)
- etcd (no locking)
- etcdv3 (with locking)
- JFrog Artifactory (no locking)
- PostgreSQL (with locking)
- Kubernetes Secret backend (with locking)
- HTTP backend (optional locking)
Example backend configuration using S3:
backend "s3" {
bucket = "tfstate-bucket" # bucket id
key = "file.tfstate" # name of the state file
region = "us-east-1" # region of the bucket
}
Note: Standard backends do not require Terraform Cloud.
Enhanced Backends¶
Enhanced backends can:
- Store state
- Execute Terraform operations
Two types:
I. Local Backend
- Default backend if none is specified
- Stores state locally
- Terraform operations are performed locally
- Uses system-level file locking
- Can explicitly configure a path:
backend "local" {
path = "relative/path/to/statefile.tfstate"
}
II. Remote Backend
Uses Terraform Cloud or Terraform Enterprise. State and (optionally) execution are offloaded to the remote platform.
This allows centralized execution and avoids storing credentials locally. Provider credentials (ex: AWS keys) must be configured in Terraform Cloud, not locally.
Remote Backend with a Single Workspace Example:
terraform {
backend "remote" {
hostname = "app.terraform.io"
organization = "company"
workspaces {
name = "my-app-prod"
}
}
}
Remote Backend with Multiple Workspaces (Prefix):
terraform {
backend "remote" {
hostname = "app.terraform.io"
organization = "company"
workspaces {
prefix = "my-app-"
}
}
}
You would then run commands in order to choose which workspace is supposed to be targeted:
terraform workspace select dev(if you have a my-app-dev workspace)terraform workspace select prod(if you have a my-app-prod workspace)
Note: You cannot use both name and prefix.
Cloud Backend¶
Terraform Cloud now uses the cloud block instead of the older remote backend block.
Example:
terraform {
cloud {
hostname = "app.terraform.io"
organization = "company"
workspaces {
tags = ["app"]
}
}
}
The previous method is still supported but deprecated for new setups.
Backend Initialization¶
Use -backend-config during initialization for dynamic or sensitive backend settings.
You can create a backend.hcl file:
workspaces { name = "workspace" }
hostname = "app.terraform.io"
organization = "company"
Then, you can run:
terraform init -backend-config=backend.hcl