Working on multi-region Terraform deployments on AWS

Adithya
2 min readNov 4, 2021

--

Terraform AWS provider works with only one region at a time. If we want to work on multiple regions, provider aliases need to be used. But using a variable value for this in a resource block or within a module is not possible.

Given a map of regions and VPC CIDRs, let’s try to create VPCs using modules. Note that we do not pass provider info here. It is passed when calling the module.

resource "aws_vpc" "vpc" {
count = length(var.cidr)
cidr_block = var.cidr[count.index]
tags = {
Name = "generated by terraform"
}
}

Root module files. Setup provider aliases for each region :

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.0"
}
}
}
provider "aws" {
alias = "aps1"
region = "ap-south-1"
}
provider "aws" {
alias = "use2"
region = "us-east-2"
}
provider "aws" {
alias = "use1"
region = "us-east-1"
}

Root module where we call the VPC module. We pass provider info into each module. As of writing this, providers block cannot be dynamically generated as well.

locals {
region_cidr_map = {
us-east-1 = ["10.0.0.0/16", "10.11.0.0/16"]
us-east-2 = ["10.0.0.0/16", "10.11.0.0/16"]
ap-south-1 = ["10.0.0.0/16", "10.11.0.0/16", "172.0.0.0/24"]
}
}
module "vpc_use1" {
source = "./modules/vpc"
providers = {
"aws" = "aws.use1"
}
cidr = lookup(local.region_cidr_map, "us-east-1")
}
module "vpc_use2" {
source = "./modules/vpc"
providers = {
"aws" = "aws.use2"
}
cidr = lookup(local.region_cidr_map, "us-east-2")
}
module "vpc_aps1" {
source = "./modules/vpc"
providers = {
"aws" = "aws.aps1"
}
cidr = lookup(local.region_cidr_map, "ap-south-1")
}

Applying above will create 7 VPCs:

$ terraform state list
module.vpc_aps1.aws_vpc.vpc[0]
module.vpc_aps1.aws_vpc.vpc[1]
module.vpc_aps1.aws_vpc.vpc[2]
module.vpc_use1.aws_vpc.vpc[0]
module.vpc_use1.aws_vpc.vpc[1]
module.vpc_use2.aws_vpc.vpc[0]
module.vpc_use2.aws_vpc.vpc[1]

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Adithya
Adithya

Written by Adithya

DevOps, IoT and amateur radio

No responses yet

Write a response