Skip to content

Instantly share code, notes, and snippets.

@nicerobot
Forked from karl-cardenas-coding/try.tf
Created May 29, 2020 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicerobot/12786d0ef5c856bd6feced6cf8c68fc1 to your computer and use it in GitHub Desktop.
Save nicerobot/12786d0ef5c856bd6feced6cf8c68fc1 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