Hi All,
Here is my use case -
folder structure
- providers.tf
- root.tf
- variables.tf
- modules
- create_security_group
- aws_security_group.tf
- create_security_group
I am trying to create security group for a set of vpcs, these vpcs are present in different aws regions.
Note : The actual use case involves creation of lots of resources in loop, giving a short example here.
providers.tf
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 4.11.0"
configuration_aliases = [ aws.us-east-1, aws.us-east-2 ]
}
}
provider "aws" {
//aws creds
region = "us-east-1"
alias = "us-east-1"
}
provider "aws" {
//aws creds
region = "us-east-2"
alias = "us-east-2"
}
}
variables.tf
variable security_groups {
type = list(object({
name = string,
vpc = string
region = string
}))
default = [
{
"name": "security_group1",
"vpc": "vpc1",
"region": "us-east-1"
},
{
"name": "security_group2",
"vpc": "vpc2",
"region": "us-east-2"
}
]
}
root.tf
module "create_security_group" {
source = "./modules/create_security_group"
for_each = { for sg in var.security_groups : sg.name => sg }
vpc_id = lookup(each.value, "vpc")
name = each.key
providers = {
aws = aws.us-east-1
}
}
aws_security_group.tf
//create security group
resource "aws_security_group" "security_group" {
vpc_id = var.vpc_id
name = var.name
}
As terraform is not allowing creation of providers dynamically. I am planning to create providers.tf using some script.
In root.tf , I am passing providers to create_security_group
module in order to create some resources in a particular aws region.
I would like to know if there is any way in which, I could send the configuration alias dynamically based on region.
providers = {
aws = aws.us-east-1 // wanted to do aws.lookup(each.value, "region") or anything else to
// pass configuration alias dynamically
}
Your help is highly appreciated.