0
0
TerraformHow-ToBeginner · 3 min read

How to Use Multiple Providers in Terraform: Syntax and Example

To use multiple providers in Terraform, define each provider block with a unique alias using alias. Then, reference the specific provider in your resources using the provider argument with the alias name.
📐

Syntax

In Terraform, you declare multiple providers by giving each an alias. This lets you tell Terraform which provider to use for each resource.

  • provider block: Defines the provider and its settings.
  • alias: A unique name to distinguish this provider.
  • provider argument in resource: Specifies which provider alias to use.
terraform
provider "aws" {
  region = "us-east-1"
}

provider "aws" {
  alias  = "west"
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
  provider      = aws.west
}
💻

Example

This example shows how to create an AWS EC2 instance in two different regions by using two AWS providers with aliases.

terraform
provider "aws" {
  region = "us-east-1"
}

provider "aws" {
  alias  = "west"
  region = "us-west-2"
}

resource "aws_instance" "east_instance" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

resource "aws_instance" "west_instance" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  provider      = aws.west
}
Output
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
⚠️

Common Pitfalls

Common mistakes when using multiple providers include:

  • Not setting alias for additional providers, causing conflicts.
  • Forgetting to specify the provider argument in resources that should use the alternate provider.
  • Using the default provider unintentionally for all resources.

Always double-check provider aliases and resource references.

terraform
provider "aws" {
  region = "us-east-1"
}

provider "aws" {
  region = "us-west-2"  # Missing alias causes error
}

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
  provider      = aws.west  # This will fail because 'west' alias is missing
}

# Correct way:
provider "aws" {
  alias  = "west"
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
  provider      = aws.west
}
📊

Quick Reference

  • Use alias to name additional providers.
  • Reference providers in resources with provider = provider_name.alias.
  • The first provider block without alias is the default.
  • Multiple providers allow managing resources across regions or accounts.

Key Takeaways

Define multiple providers with unique aliases using the alias argument.
Specify the provider in each resource to control which provider it uses.
The default provider block has no alias and is used if no provider is specified.
Always check provider aliases to avoid configuration errors.
Multiple providers enable managing resources in different regions or accounts.