Constructing a json string from a list of objects

I’m working on a new module to call an ansible playbook. The playbook takes a rather complex payload of various user inputs of nested lists, optional parameters, etc. The idea is that the payload is constructed by the module so we can take advantage of the built-in validation.

I have this somewhat working with the following…

variable "instances" {
  type = list(object({
    name = string,
    data_center = string,
    enable_ssl = optional(bool, false),
    server_groups = optional(list(object({
      number_of_instances  = number,
      function   = string

And then in the module’s, I am passing the instances var to jsonencode.

locals {
  extravars = jsonencode(var.instances)

No problems there. That works great and formats out the json string.

Now I need to take that subset of the extravars strings and combine it with the rest of the values we need to pass…

Here’s a subset of what I’m getting now, which makes sense given the fact that the variable is set to a list of objects:


How would I go about creating the extravars string to map the list to “instances” (like the following)?
\"instances\": [{\"server_groups\":[{\"number_of_instances\":2

I was thinking I could have a parent map set as a local var and add the instances list to that map, but I’m having trouble thinking through how this would be done or if this would even be the best approach.

I attempted to add the list to a map and obviously that doesn’t work since you can’t have different types in a map.

Really at a loss here on how to do this.

I am finding your question a bit hard to understand, but are you just trying to write

locals {
  extravars = jsonencode({ instances = var.instances })


Yeah… sorry about that. This is all a bit new and I’m finding it rather difficult to put down in words what I’m trying to do.

Despite that, it seems you managed to figure it out for me. I did not realize that you can pass an expression into jsonencode.