How to Use Remote Backend with Terraform Cloud
To use a remote backend with Terraform Cloud, add a
backend "remote" block in your Terraform configuration specifying your Terraform Cloud organization and workspace. This setup stores your state remotely, enabling team collaboration and secure state management.Syntax
The backend "remote" block configures Terraform to store state files in Terraform Cloud. It requires specifying the organization and workspaces details.
organization: Your Terraform Cloud organization name.workspaces: Defines the workspace name or usesprefixfor dynamic naming.
terraform
terraform {
backend "remote" {
organization = "your-org-name"
workspaces {
name = "your-workspace-name"
}
}
}Example
This example shows how to configure Terraform to use Terraform Cloud as a remote backend. Replace your-org-name and your-workspace-name with your actual Terraform Cloud organization and workspace names.
terraform
terraform {
backend "remote" {
organization = "example-org"
workspaces {
name = "example-workspace"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "example" {
bucket = "example-terraform-remote-backend"
acl = "private"
}Output
Terraform will initialize and connect to Terraform Cloud workspace 'example-workspace' in organization 'example-org'. State will be stored remotely.
Common Pitfalls
Common mistakes when using Terraform Cloud remote backend include:
- Not running
terraform initafter adding the backend block, which is required to configure the backend. - Using incorrect organization or workspace names, causing authentication or connection errors.
- Not setting up Terraform Cloud API token in environment variables (
TF_TOKEN_app_terraform_io), leading to authorization failures. - Trying to use local state files alongside remote backend, which can cause conflicts.
terraform
terraform {
backend "remote" {
organization = "wrong-org"
workspaces {
name = "wrong-workspace"
}
}
}
# Correct usage:
terraform {
backend "remote" {
organization = "correct-org"
workspaces {
name = "correct-workspace"
}
}
}Quick Reference
Tips for using Terraform Cloud remote backend:
- Always run
terraform initafter backend changes. - Store your Terraform Cloud API token securely in environment variables.
- Use consistent workspace names to avoid state conflicts.
- Leverage Terraform Cloud features like state locking and versioning automatically.
Key Takeaways
Configure the remote backend block with your Terraform Cloud organization and workspace.
Run terraform init to initialize the remote backend connection.
Set your Terraform Cloud API token in environment variables for authentication.
Avoid mixing local and remote state files to prevent conflicts.
Terraform Cloud manages state locking and versioning automatically for you.