Use multiple providers

Using multiple providers in Terraform involves specifying each required provider in your configuration file, each with its unique settings, allowing management of resources across different platforms or regions within the same configuration.

Working with multiple providers in a single Terraform configuration is straightforward. Each provider declaration is independent of others and enables Terraform to manage resources across diverse infrastructure platforms like AWS, Azure, Google Cloud, or even different regions of a single platform.

For instance, you might use the AWS provider to manage resources in the us-west-2 region and simultaneously want to deploy resources to the us-east-2 region, perhaps to have a multi-region deployment for high-availability. These providers coexist seamlessly within a single Terraform configuration, offering you the flexibility to manage complex, multi-platform infrastructure setups effectively.

This code snippet showcases the use of multiple AWS providers in a single Terraform configuration, each targeting a different AWS region. The first provider is an alias for the us-west-2 region, referred to as region-a, and the second provider is an alias for the us-east-2 region, referred to as region-b. These aliases allow specific resources to be associated with a particular provider configuration, facilitating the management of resources across different regions within the same configuration.

In this example, we’re deploying an EC2 instance of type t2.micro into each region, us-west-2 and us-east-2. The specific provider for each resource is referenced using the provider attribute.

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

provider "aws" {
  region = "us-east-2"
  alias  = "region-b"
}

resource "aws_instance" "ec2_region_a" {
  provider = aws.region-a
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

resource "aws_instance" "ec2_region_b" {
  provider = aws.region-b
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}
Last modified July 21, 2024: update (e2ae86c)