Skip to content

Instantly share code, notes, and snippets.

@karl-cardenas-coding
Last active May 29, 2020 15:28
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save karl-cardenas-coding/1f67ad3c5ac46cce697081fa4a6a6b7b to your computer and use it in GitHub Desktop.
Example of using try in Terraform
# Try example
data "http" "primary-server" {
url = "https://ip-ranges.amazonaws.com/ip-ranges.json"
# Optional request headers
request_headers = {
Accept = "application/json"
}
}
locals {
# This returns the sync token from the endpoint, the return value is of the type string.
syncToken = try(jsondecode(data.http.primary-server.body).syncToken,
"NO TOKEN AVAILABLE"
)
# This variable holds the all the unique regions returned by the endpoint. The return value is of the type list OR a string error value.
regions = try(distinct([
for items in jsondecode(data.http.primary-server.body).prefixes:
items.region
]), "NO LIST PROVIDED IN LOCALS REGION VARIABLE")
# This variable holds the all the unique services returned by the endpoint. The return value is of the type list OR a string error value.
services = try(distinct([
for items in jsondecode(data.http.primary-server.body).prefixes:
items.service
]), "NO LIST PROVIDED IN LOCALS SERVICES VARIABLE")
# This variable holds the all the IPs addresses for the S3 service returned by the endpoint. The return value is of the type list OR a string error value.
s3_ips = try(distinct([
for items in jsondecode(data.http.primary-server.body).prefixes:
items.ip_prefix if items.service == "S3"
]), "NO LIST PROVIDED IN LOCALS SERVICES VARIABLE")
}
output "response-json-syncToken" {
value = local.syncToken
}
output "response-json-s3-ips" {
value = local.s3_ips
}
output "response-json-regions" {
value = local.regions
}
output "response-json-services" {
value = local.services
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment