将JSON字符串解码为terraform map

时间:2017-09-22 18:50:39

标签: terraform

我正在使用HTTP data source从内部服务中检索数据。该服务返回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")}"
}

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}"
}

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

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

4 个答案:

答案 0 :(得分:12)

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

   output "map" {
      value = "${data.external.json.result}"
   }

答案 1 :(得分:5)

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

terraform version v0.10.6

答案 2 :(得分:1)

与地图转换没有直接关系,但是如果您在AWS SecretsManager中得到了多值秘密(= JSON),并且您想在另一个服务中使用与它分开的值,那么这里是jsondecode的另一个示例已经为此苦苦挣扎了。

获取秘密:

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
}

以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"]
    }
  }
}

答案 3 :(得分:0)

从0.12版本的Terraform开始,您可以使用jsondecode函数将json解码为Terraform映射。有关以下详细信息:https://www.terraform.io/docs/configuration/functions/jsondecode.html

上一页的示例:

> jsondecode("{\"hello\": \"world\"}")
{
  "hello" = "world"
}
> jsondecode("true")
true