Hey all,
I’ve successfully set up a VPS creation+provisioning system where I can provision 3 VPS servers in one location:
resource "linode_instance" "LIN-SERVER" {
count = 4
region = "us-west"
...
}
However I’m running into issues when creating multiple instances in multiple regions, since using count
and for_each
in the same resource is not allowed:
resource "linode_instance" "LIN-SERVER" {
# Deploy 4 VPS in each region
count = 4
for_each = toset([ "us-west", "us-central", "us-east" ])
region = each.key
...
}
These resources are pretty big (lots variables and provision scripts), so I don’t want to simply duplicate this .tf for every region. I’d like to re-use code and keep things minimal as much as I can so this infrastructure is easier to maintain.
Can anyone please offer some advice on how to create multiple servers in multiple regions?
Thanks,
Mitch
I have come up with a solution so far using flatten[]
, but it seems like there should be an easier way to do this.
In the locals block I combine two arrays together and then flatten them to produce a single array.
Then, following this StackOverflow answer I can format region_list
into region_list_formatted
, which allows the se_region value to be accessed more easily in the resource block.
locals {
region_list = flatten([
for r in toset([ "us-west", "us-central", "us-east" ]) : [
for i in toset([ 1, 2, 3, 4]) : {
se_region = r
unique_key = "${r}-${i}"
}
]
])
region_list_formatted = {
for each in local.region_list : each.unique_key => { se_region = each.se_region }
}
}
resource "linode_instance" "LIN-SESERVER" {
# Deploy 4 VPS in each region
for_each = local.region_list_formatted
region = each.value.se_region
Another neat way is to define a module within the repo that creates everything for a single region (as there are usually various resources rather than just one). Then when you call the module you can use for_each
to loop through the regions.
1 Like