'Terraform combine variables using locals
I want to combine 2 variables. I tried to use locales but I couldn't get the final result also even with flatten
Any other recommendation? I tried to use this structure since the vpc module receives that object with a list of subnets, the idea is that in networks we can add the name of the subnet in the list
variable "subnets" {
default = {
"subnet-01" = {
name = "subnet-01"
subnet_ip = "10.10.10.0/24"
subnet_region = "us-central1"
description = "This subnet has a description"
}
"subnet-02" = {
name = "subnet-02"
subnet_ip = "10.10.20.0/24"
subnet_region = "us-central1"
description = "This subnet has a description"
}
"subnet-03" = {
name = "subnet-03"
subnet_ip = "10.10.20.0/24"
subnet_region = "us-central1"
description = "This subnet has a description"
}
}
}
variable "networks" {
default = {
"test-network" = {
subnets = ["subnet-01", "subnet-02"]
auto_create_subnetworks = "false"
mtu = "0"
}
"test-network-2" = {
subnets = ["subnet-03"]
auto_create_net = false
auto_create_subnetworks = "false"
mtu = "0"
}
}
}
Is it possible to choose the following result?
networks = {
test-network = {
auto_create_subnetworks = false
mtu = 0
subnets = [
subnet-01 = {
name = "subnet-01"
subnet_ip = "10.10.10.0/24"
subnet_region = "us-central1"
description = "This subnet has a description"
}
subnet-02 = {
name = "subnet-02"
subnet_ip = "10.10.20.0/24"
subnet_region = "us-central1"
description = "This subnet has a description"
}
]
}
test-network-2 = {
auto_create_subnetworks = false
mtu = 0
subnets = [
subnet-03 = {
name = "subnet-03"
subnet_ip = "10.10.30.0/24"
subnet_region = "us-central1"
description = "This subnet has a description"
}
]
}
}
Solution 1:[1]
You can achieve that result having an embedded loop:
locals {
networks = {
for name, network in var.networks : name => {
"subnets" : [for subnet_name in network.subnets : var.subnets[subnet_name]],
"auto_create_subnetworks" : network.auto_create_subnetworks,
"mtu" : network.mtu
}
}
}
Also, please note, your subnet-02
has the name
of subnet-01
, which might not be what you would want.
Solution 2:[2]
I have the following code.
mymodule
variable "senses" {
type = string
}
locals {
sounds = {
"cat" = "meow"
"dog" = ["bark", "woof"]
}
}
output "noise" {
value = local[var.senses]["cat"]
}
call mymodule
module "mymodule" {
source = "../../../modules/mymodule"
senses = "sound"
}
returns error:
Error: Invalid reference
on ../../../modules/mymodule/outputs.tf line 62, in output "noise":
62: value = local[var.senses]["cat"]
The "local" object cannot be accessed directly. Instead, access one of its
attributes.
my code can't seem to handle
value = local[var.senses]["cat"]
Any suggestions on how i can get this to work?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | sebastian |