Working on multi-region Terraform deployments on AWS

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]

--

--

--

I work with cloud, containers, linux

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

There Is Only One Web Project

BETTERMENT DIGITAL TOKEN INFORMATION

Pub-Sub in Azure

https://azure.microsoft.com/en-us/global-infrastructure/services/?products=web-pubsub

Why We Broke Our Philosophical Vows to Bring You CircleCI 2.0

Java Servlets and JSP

Why do software projects fail?

KYVE: Testnet and Ambassador program

Here is what I feel after 3 months of

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adithya

Adithya

I work with cloud, containers, linux

More from Medium

How to Deploy Amazon WorkSpaces in AWS using Terraform

I had always this thought what if I can automate the infrastructure?

Terraform

Localstack as an AWS sandbox