`terraform console` can't be scripted as outputing some messages on stdout
Terraform Version
Terraform v1.9.7
on linux_amd64
+ provider registry.terraform.io/hashicorp/aws v5.67.0
+ provider registry.terraform.io/hashicorp/external v2.3.4
+ provider registry.terraform.io/hashicorp/null v3.2.3
Terraform Configuration Files
N/A
Debug Output
N/A
Expected Behavior
Only output console result on stdout in order to be able to parse output.
Actual Behavior
When warning (or may be other cases) are emitted, they are also printed on stdout:
Command:
terraform console <<<'jsonencode(local.test)'
Stdout:
╷
│ Warning: Backend configuration ignored
│
│ on .terraform/modules/diff_secret/module/default_backend.tf line 3, in terraform:
│ 3: backend "s3" {
│
│ Any selected backend applies to the entire configuration, so Terraform
│ expects provider configurations only in the root module.
│
│ This is a warning rather than an error because it's sometimes convenient to
│ temporarily call a root module as a child module for testing purposes, but
│ this backend configuration block will have no effect.
╵
"foobar"
Also tried with TF_IN_AUTOMATION=true TF_LOG=off same result.
Steps to Reproduce
terraform initterraform console <<<'jsonencode(local.test)'
Additional Context
N/A
References
N/A
Thanks for this report!
Will be a suitable solution to output warnings to the stderr or just add --disable-warnings option? For me, the 2nd way is better. Thinking to get it to work
I'm also looking for a way to get around this. To give my use case, I've been using things like
FOO=$(terraform console <<< var.foo)
to grab the value of foo as terraform would use as input (maybe coming from a tfvar file, or maybe a default, etc). But this completely breaks if there is any kind of warning. I was extremely surprised to find out that the warnings are printed to stdout. I don't think there's any other way to ask this kind of query in general.
So I think a potential workaround is by always using jsonencode (to force the output to be exactly one line) and piping through tail -n 1. The warnings seem to always be printed before the actual output. So in bash,
# returns something appropriate for passing to jq
function tf_query_json () {
terraform console <<< "jsonencode($1)" | tail -n 1 | jq -r .
}
# returns "raw" output (no quotes or escaping)
function tf_query_raw () {
tf_query_json "$1" | jq -r .
}
Because terraform is double escaping string output, the extra jq -r . is needed. In the end, I think these two functions work well for what one might want to do, e.g.,
tf_query_raw '"hello world"'
tf_query_raw '0.5'
tf_query_raw '1'
tf_query_raw '["a", "b", "c", "d"]'
tf_query_json '["a", "b", "c", "d"]' | jq -r '.[2]'
tf_query_json '{foo="bar"}'
hello world
0.5
1
[
"a",
"b",
"c",
"d"
]
c
{"foo":"bar"}
I wish this is how terraform console itself worked, as this workaround feels kind of sketchy, but at least there's a workaround :)