is it possible to use !terraform.state with a yq e...
# atmos
c
is it possible to use !terraform.state with a yq expression to pass in a list of values to terraform that expects a list?
eg:
Copy code
vars:
  subnet_ids: !terraform.state vpc ".subnets[] | select(.group == ""someservice"") | .id"

OR

vars:
  subnet_ids: !terraform.state vpc "[.subnets[] | select(.group == ""someservice"") | .id]"
I get the 3 values concatenated into a string separated by space, which is not terrible but I'm wondering if there is a nicer way
testing the expression with jq, I have to wrap the whole expression in [] to make the output a list
but if I do that I get "null null null" in terraform
a
Copy code
subnet_ids: !terraform.state vpc "[.subnets[] | select(.group == ""someservice"") | .id] | tojson"
try that ^
c
"db_subnets": "null\nnull\nnull"
a
do you have any results from the query before putting them into a list?
there could be two diff issues:
• No results from the query satisfying the filters • The YQ expression is not 100% correct
for the second one, try
Copy code
subnet_ids: !terraform.state vpc "([.subnets[]? | select(.group == ""someservice"") | .id] | map(select(. != null))) | tojson"
for the above to work, the
vpc
output should have the following:
•
.subnets
•
.group
• each subnet should have
.id
c
the output is:
Copy code
subnets:
  "service-0": {
    "id": id,
    "cidr_block": "1.2.3.0/24",
    "group": "service"
   }
 }
etc.
a
so the structure is different,
subnets
is a list of maps?
c
nope, it's a nested map
a
Copy code
subnet_ids: !terraform.state vpc "([.subnets? // {} | .[] | select(.group == ""service"") | .id] | map(select(. != null)) | tojson)"
Copy code
Why this works:

.subnets? // {} handles missing subnets.

.[] iterates the map's values.

select(.group == "service") filters.

| .id extracts IDs.

[...] collects into one array.

map(select(. != null)) drops any nulls.

tojson returns a proper JSON list (["subnet-aaa","subnet-bbb"]) Terraform reads as list(string).
c
no dice. I'm not doing the filtering out null values as I know the values are there, if I capture them in terraform as a string, without wrapping the yq in [], I see the subnet ids separated by a space. using the expression
"[.subnets[] | select(.group == ""someservice"") | .id] | tojson"
gives me following values in the generated terraform.tfvars.json:
Copy code
service:
  db_subnets: |-
    null
    null
    null
the values get passed as a multi-line string
no idea why they are null though
I can verify the expression running yq manually
Copy code
cat subnets.json| yq '[.subnets[] | select(.group == "admin") | .id] | tojson'
[
  "subnet-...",
  "subnet-...",
  "subnet-..."
]