如何使用 terraform 从嵌套 API 请求数据

问题描述 投票:0回答:1

我使用带有 JSON 文件的 URL 来访问数据

每个对象的第一个元素是一个 URL,其中包含另一个包含更多数据的 JSON 文件

在第一个 URL 之后,还有第三个 JSON 文件,其中包含以下数据

从这三个 JSON 文件中,我想获取一些数据并将它们放在地图中,例如:

url = ****
apn = ****
operator = ****
iprange = ****
network = ****`

我尝试使用每个网络的所有数据创建一个地图,这样我就可以稍后过滤掉我需要的信息,但我不知道如何从嵌套的网址中获取数据。

json for-loop networking terraform
1个回答
0
投票

您可以使用几个提供程序来发出 http 请求:


这是使用

hashicorp/http
的示例:

data "http" "petstore_available" {
  url    = "https://petstore.swagger.io/v2/pet/findByStatus?status=available"
  method = "GET"

  request_headers = { Accept = "application/json" }
}

locals {
  response_body = jsondecode(data.http.petstore_available.response_body)
  ids           = sort([for x in local.response_body : x.id if x.id < 9000])
}

data "http" "petstore_pets" {
  for_each = toset(local.ids)
  url      = "https://petstore.swagger.io/v2/pet/${each.value}"
  method   = "GET"

  request_headers = { Accept = "application/json" }
}

locals {
  pet_names = distinct(flatten([
    for x in data.http.petstore_pets : [
      try(jsondecode(x.response_body).name, "")
    ]
  ]))
}

output "pet_names" {
  value = local.pet_names
}
  • data "http" "petstore_available"
    我们得到了所有可用的宠物
  • 我们用循环提取宠物 ID 列表:
    for x in local.response_body : x.id if x.id < 9000
  • 然后在
    data "http" "petstore_pets"
    中,我们循环这些 id 以获取更多信息
  • 最后在
    pet_names
    中我们提取那些有名字的宠物的名字

如果我们对此运行 TF 计划,我们会得到:

Changes to Outputs:
  + pet_names = [
      + "doggie",
      + "xyz",
      + "Chance",
      + "A2",
      + "Sam",
      + "pelhamdog",
      + "PasBre",
      + "",
      + "Fluffy",
      + "Deshawn",
      + "Sammy",
    ]
© www.soinside.com 2019 - 2024. All rights reserved.