将JSON字符串解码为terraform map

Ofe*_*ich 10 terraform

我正在使用HTTP数据源从内部服务检索数据.该服务返回JSON数据.

我无法插入返回的JSON数据并在其中查找数据.

例如:

模块A.

data "http" "json_data" {
    url = "http://myservice/jsondata"

    # Optional request headers
    request_headers {
       "Accept" = "application/json"
    }
}

output "json_data_key" {
    value = "${lookup(data.http.json_data.body, "mykey")}"
}
Run Code Online (Sandbox Code Playgroud)

main.tf

provider "aws" {
   region = "${var.region}"
   version = "~> 0.1"
}

module "moduleA" {
   source = "../../../terraform-modules/moduleA"
}

resource "aws_instance" "example" {
    ami = "ami-2757f631"
    instance_type = "${module.moduleA.json_data_key}"
}
Run Code Online (Sandbox Code Playgroud)

查找功能将无法在JSON数据中提取密钥.

有没有办法将JSON数据解码为terraform地图?

vic*_*r m 15

   data "external" "json" {
      program = ["echo", "${var.json}"]
   }

   output "map" {
      value = "${data.external.json.result}"
   }
Run Code Online (Sandbox Code Playgroud)


tps*_*idt 7

与地图转换没有直接关系,但这里有一个额外的示例,jsondecode如果您在 AWS SecretsManager 中有一个多值密钥 (=JSON),并且您想在另一个服务中使用它的单独值,因为我一直在努力解决这个问题。

找回秘密:

data "aws_secretsmanager_secret" "oauth_client" {
  name = "oauth-client"
}

data "aws_secretsmanager_secret_version" "oauth_client" {
  secret_id = data.aws_secretsmanager_secret.oauth_client.id
}
Run Code Online (Sandbox Code Playgroud)

以在 Lambda 中使用它为例:

resource "aws_lambda_function" "lambda" {
  [...]
  environment {
    variables = {
      OAUTH_CLIENT_ID     = jsondecode(data.aws_secretsmanager_secret_version.oauth_client.secret_string)["client_id"]
      OAUTH_CLIENT_SECRET = jsondecode(data.aws_secretsmanager_secret_version.oauth_client.secret_string)["client_secret"]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Ofe*_*ich 5

好吧,所以似乎是这样做的方法是使用外部数据,因为它从json响应返回一个映射. https://www.terraform.io/docs/providers/external/data_source.html

terraform版本v0.10.6


小智 5

从 0.12 版本的 Terraform 开始,您可以使用jsondecode函数将 json 解码为 Terraform 地图。更多详情:https : //www.terraform.io/docs/configuration/functions/jsondecode.html

上面页面中的示例:

> jsondecode("{\"hello\": \"world\"}")
{
  "hello" = "world"
}
> jsondecode("true")
true
Run Code Online (Sandbox Code Playgroud)