Decoding JSON string to terraform map

Ofer Velich picture Ofer Velich · Sep 22, 2017 · Viewed 13.5k times · Source

I'm using the HTTP data source to retrieve data from an internal service. The service returns JSON data.

I can't interpolate the returned JSON data and look up data in it.

For example:

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

The lookup function will fail to extract the key within the JSON data.

Is there any way to decode the JSON data into a terraform map ?

Answer

victor m picture victor m · Dec 13, 2017
data "external" "json" {
  program = ["echo", "${var.json}"]
}

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