I’m trying to understand why one of these solutions works and the other doesn’t. In counts like these:
count = var.x != null ? 1 : 0
# or
count = var.y != null && var.z != null ? 1 : 0
there often arises the age-old unknown at plan-time issue. To get around this, one can use for_each
and ensure the key is not a calculated value.
For example, in the former case:
for_each = { for i, v in [var.x] : i => v }
works nicely, and no longer complains. You just get key ["0"]
instead of [0]
.
But these don’t work for the second count.
for_each = { for i, v in [{
y = var.y
z = var.z
}] : i => v if alltrue([
v.y != null,
v.z != null
]) }
and:
for_each = { for i, v in [alltrue([
var.y != null,
var.z != null
])] : i => {
y = var.y
z = var.z
} if v }
They yield the error:
The "for_each" map includes keys derived from resource attributes that cannot be determined until apply, and so Terraform cannot determine the full set of
│ keys that will identify the instances of this resource.
But this works:
for_each = { for i, v in [alltrue([
var.y != null,
var.z != null
]) ? {
y = var.y
z = var.z
} : {}] : i => v }
But given that the keys are the same and the known information is the same, I cannot see why the first two raise the error but the third one doesn’t. Not pressing as all are ugly hacks and one is working, but I am confused by the error.