Multiple Providers and Aliases
Use provider aliases to manage more than one region or account in a single configuration.
Syntax
provider "aws" {
alias = "west"
region = "us-west-2"
}Sometimes one configuration needs to reach two regions or two accounts. You do this with a second provider block and an alias.
Defining an alias
Give the extra provider an alias, then point a resource at it with the provider meta-argument, written as aws.alias_name.
Common use cases
- Replicating an S3 bucket into a second region for backups.
- Creating an ACM certificate in
us-east-1for CloudFront while everything else is elsewhere.
Example
provider "aws" {
region = "us-east-1"
}
provider "aws" {
alias = "west"
region = "us-west-2"
}
# This bucket is created in us-west-2
resource "aws_s3_bucket" "backup" {
provider = aws.west
bucket = "soundscode-backup-west"
}When to use it
- A team deploys an application's primary infrastructure in us-east-1 and a disaster-recovery replica in eu-west-1 using two aliased AWS provider blocks.
- A platform engineer uses aliased providers to manage resources in both a dev AWS account and a prod AWS account from a single Terraform configuration.
- A module accepts a provider configuration map so callers can pass in region-specific aliased providers without changing the module's internal code.
More examples
Two-region provider aliases
Declares two aliased AWS providers for different regions and assigns each bucket to the appropriate provider.
provider "aws" {
alias = "us_east"
region = "us-east-1"
}
provider "aws" {
alias = "eu_west"
region = "eu-west-1"
}
resource "aws_s3_bucket" "primary" {
provider = aws.us_east
bucket = "my-app-primary"
}
resource "aws_s3_bucket" "replica" {
provider = aws.eu_west
bucket = "my-app-replica"
}Cross-account provider alias
Uses two aliased providers that assume different IAM roles, enabling management of resources in separate AWS accounts.
provider "aws" {
alias = "prod"
region = "us-east-1"
assume_role {
role_arn = "arn:aws:iam::111111111111:role/TFProd"
}
}
provider "aws" {
alias = "dev"
region = "us-east-1"
assume_role {
role_arn = "arn:aws:iam::222222222222:role/TFDev"
}
}Passing alias into a module
Passes an aliased provider into a child module via the providers map, letting the module use the caller-supplied region.
provider "aws" {
alias = "replica_region"
region = "ap-southeast-1"
}
module "cdn" {
source = "./modules/cdn"
providers = {
aws.replica = aws.replica_region
}
}
Discussion