The file name is myfile.txt
and the content is:
# a comment line
aaa.bbb.cc 423
ddd.ee.fff 452
...
tons.like.them 111
The data query should look like:
data "external" "myfile" {
program = [
"bash",
"${path.module}/template/parser.sh",
"${path.module}/template/myfile.txt",
"ddd.ee.fff"
]
}
And the template/parser.sh
contains:
#!/usr/bin/env bash
set -eo pipefail
CONFIG=$(cat $1|grep -v '#' | sed 's/ /=/g' | jq -R -n -c '.data = ([inputs|split("=")|{(.[0]):.[1]}] |add)')
OUTPUT=$(echo $CONFIG | jq -r '.data["'$2'"]')
jq -n --arg output "$OUTPUT" '{"output":$output}'
This tricky script will return:
{"output": 452}
And the interpolation can be used to get the resulting value:
${data.external.myfile.result.output}
Unfortunately I didn't find how to load the full list of rows into Terraform and access them using "variable of variable" or lookup(). If the bash scripts return the result of the first jq
call, Terraform throws the exception:
command "bash" produced invalid JSON: json: cannot unmarshal object into Go value of type string
Update2: To access the resulting values, you need to use an additional key ".result" before the actual ".output" key from the script.