Created
May 13, 2021 16:55
-
-
Save jamesarosen/6a51164c7f9d8c86fb5dc56c7b4e445e to your computer and use it in GitHub Desktop.
I'm trying to fetch and parse some JSON in Terraform using jq and I just can't figure it out.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Braintree publish a list of their CIDR blocks and IP addresses at | |
# https://assets.braintreegateway.com/json/ips.json | |
# The body looks like | |
# { | |
# "production": { | |
# "cidrs": [ | |
# "1.2.3.4/5" | |
# ] | |
# "ips": [ | |
# "6.7.8.9" | |
# ] | |
# } | |
# "sandbox": { | |
# "cidrs": [ | |
# "11.12.13.14/15" | |
# ] | |
# "ips": [ | |
# "16.17.18.19" | |
# ] | |
# } | |
# } | |
# | |
# Using Terraform, I want to | |
# 1. retrieve that document | |
# 2. extract the `.production.cidrs` and `.production.ips` arrays, then join them | |
# 3. use the resulting array in another Terraform object | |
# 1. Fetch the document. This works fine. | |
data "http" "braintree_ips" { | |
url = "https://assets.braintreegateway.com/json/ips.json" | |
request_headers = { | |
Accept = "application/json" | |
} | |
} | |
# 2. Process the JSON I'm totally stuck here. | |
# Normally, `jq` reads from stdin, but Terraform's `external` resource can only pass a JSON | |
# document that's of the form `{ string: string }` as stdin. So the best I can do is pass | |
# the JSON document as an escaped string within another JSON document: | |
# `{"json": "{\"production\":{…}}"}` | |
# I don't know how to parse the inner document with jq. | |
# | |
# It also can't use the Unix pipe operator, so I can't just echo the JSON. | |
# | |
# I _think_ I want the `--argjson` option, but I can't figure it out. | |
data "external" "braintree_ips" { | |
program = ["jq", "--argjson", "root", replace(data.http.braintree_ips.body, "\n", ""), "."] | |
} | |
# 3. Use the resulting array. For now, I just have an `output` because it makes it easy to debug. | |
output "braintree_ips" { | |
value = data.external.braintree_ips.result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment