I have posted this question on SO - https://stackoverflow.com/questions/61218173/why-terraform-is-unable-to-compute-a-local-variable-correctly-in-the-following-t
Here it is:
Given is the following configuration (main.tf):
locals {
locations = toset(["a", "b"])
}
resource "local_file" "instance" {
for_each = local.locations
content = each.value
filename = "${path.module}/${each.value}.txt"
}
output "primary_filename" {
value = local_file.instance["a"].filename
}
And it seems to work fine:
C:\work\test> dir
Directory: C:\work\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 4/15/2020 11:47 PM 280 main.tf
C:\work\test> terraform init
Initializing the backend...
Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "local" (hashicorp/local) 1.4.0...
...
C:\work\test> terraform apply -auto-approve
local_file.instance["b"]: Creating...
local_file.instance["a"]: Creating...
local_file.instance["a"]: Creation complete after 0s [id=86f7e437faa5a7fce15d1ddcb9eaeaea377667b8]
local_file.instance["b"]: Creation complete after 0s [id=e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98]
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Outputs:
primary_filename = ./a.txt
C:\work\test>
Now I delete the file a.txt
and rerun:
C:\work\test> del .\a.txt
C:\work\test> terraform apply -auto-approve
local_file.instance["a"]: Refreshing state... [id=86f7e437faa5a7fce15d1ddcb9eaeaea377667b8]
local_file.instance["b"]: Refreshing state... [id=e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98]
Error: Invalid index
on main.tf line 13, in output "primary_filename":
13: value = local_file.instance["a"].filename
|----------------
| local_file.instance is object with 1 attribute "b"
The given key does not identify an element in this collection value.
It can be fixed by using the try
function:
value = try(local_file.instance["a"].filename, "")
Which does make it work:
C:\work\test> terraform apply -auto-approve
local_file.instance["b"]: Refreshing state... [id=e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98]
local_file.instance["a"]: Refreshing state... [id=86f7e437faa5a7fce15d1ddcb9eaeaea377667b8]
local_file.instance["a"]: Creating...
local_file.instance["a"]: Creation complete after 0s [id=86f7e437faa5a7fce15d1ddcb9eaeaea377667b8]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
primary_filename = ./a.txt
C:\work\test>
Now I know we are not supposed to delete resources outside of terraform, but things happen and my expectation is that terraform handles it gracefully. And it does, except for this local variable behavior.
I do not like using the try
function, because it would hide a real problem. Ideally, it should behave like try
during the plan phase and without try
during the apply phase.
Anyway, I have a feeling I am missing something important here, like I am not using the local variables correctly or something else. So, what am I missing?