As a follow-up to Terraform: null values and for_each, this time we are going to see which values are (not) allowed when dealing with for_each
, thus the following error:
│ Error: Invalid for_each argument
│ The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings,
| and you have provided a value of type tuple.
Prerequisites
- Terraform
Solution
At time of writing, and from my experience, for_each
only works with maps
, sets
, any list
, and bool
. So, the obvious solution would be to either to convert whatever you are working with, using TF functions, or just define them as such.
As for the solution it really depends on the case. However, here are some examples to give you some ideas to get you started at least.
example using vars with for_each defined as map
# module.tf
variable "subnets" {
description = "Map of subnets and CIDR IP ranges."
type = map(any)
default = {}
}
resource "google_compute_subnetwork" "this" {
for_each = var.subnets
name = each.key
ip_cidr_range = each.value
region = var.region
network = google_compute_network.this.id
project = var.project
stack_type = var.stack_type
}
# locals.tf
subnets = {
"subnet_1" = "10.1.0.0/24",
"subnet_2" = "10.2.0.0/24"
}
# main.tf
module "vpc" {
...
subnets = local.subnets
}
example using vars with for_each defined as list of objects
# module.tf
variable "database_flags" {
description = "List of database flag."
type = list(object({
name = string
value = number
}))
default = []
}
resource "google_sql_database_instance" "main" {
...
settings {
...
dynamic "database_flags" {
for_each = var.database_flags
content {
name = database_flags.value.name
value = database_flags.value.value
}
}
}
}
## locals.tf
database_flags = [
{
name = "max_connections"
value = 2048
},
{
name = "cron.log_run"
value = on
}
]
# main.tf
module "dbs" {
...
database_flags = local.database_flags
}
Regarding a bool
example, please check out the post linked at the start of this post.
Conclusion
When nothing works, feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.