I am trying to deploy same instance across multiple regions using providers. The tree of the folder is:
.
|-- main.tf
`-- aws_instance
| `-- main.tf
`-- versions.tf
main.tf looks like:
module "aws_instances" {
source = "./aws_instance"
providers = {
aws.east1 = aws.east1
aws.east2 = aws.east2
}
}
aws_instance/main.tf looks like:
resource "aws_instance" "webserver" {
ami = "webserver-image"
instance_type = "t2.micro"
key_name = "EC2-keyPair-Name"
associate_public_ip_address = true
root_block_device {
volume_type = "gp2"
volume_size = "30"
delete_on_termination = false
}
versions.tf looks like:
terraform {
required_version = ">= 1.0.4"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 3.23.0"
configuration_aliases = [aws.east1, aws.east2]
}
}
}
provider "aws" {
region = "us-east-1"
alias = "east1"
}
provider "aws" {
region = "us-east-2"
alias = "east2"
}
With the current code, I am getting the instance deployed in just one region. Any hints of what can be wrong here?
Specifying
providers = {
aws.east1 = aws.east1
aws.east2 = aws.east2
}
does not create two instances. It just passes two aliases to your module. But module is still invoked only once. Since you can't loop over providers, you have to explicitly choose which provider to use for each instance. This means, duplication of code. So you either have to have two definitions of instances in the module:
aws_instance/main.tf
resource "aws_instance" "webserver1" {
ami = "webserver-image"
instance_type = "t2.micro"
key_name = "EC2-keyPair-Name"
associate_public_ip_address = true
root_block_device {
volume_type = "gp2"
volume_size = "30"
delete_on_termination = false
provider = aws.east1
}
resource "aws_instance" "webserver2" {
ami = "webserver-image"
instance_type = "t2.micro"
key_name = "EC2-keyPair-Name"
associate_public_ip_address = true
root_block_device {
volume_type = "gp2"
volume_size = "30"
delete_on_termination = false
provider = aws.east2
}
or alternatively, invoke module twice:
main.tf
module "aws_instance1" {
source = "./aws_instance"
providers = {
aws = aws.east1
}
}
module "aws_instance2" {
source = "./aws_instance"
providers = {
aws = aws.east2
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With