Search code examples
jsonterraformvmware

Terraform jsonencode type conversion failing to convert values to array


I'm trying to deploy a VM using the vmware/vra provider and get this error when trying to define the inputs:

│ Error: cannot convert input 'disks' value '{"label":"/appmnt","mountpoint":"/app","size":"20"}' into type 'array'. &json.UnmarshalTypeError{Value:"object", Type:(*reflect.rtype)(0x103c715e0), Offset:1, Struct:"", Field:""}

inputs = {
  image  = "Ubuntu"
  folderPath = "folder/Path"
  folderName = "terraform"
  name = "terraDeploy"
  disks = jsonencode({ "mountpoint": "/app", "label": "/appmnt", "size": "20" })
}

My 'terraform apply' output for disks looks like this:

         + "disks"      = jsonencode(
                {
                  + label      = "/appmnt"
                  + mountpoint = "/app"
                  + size       = "20"
                }
            )

This is the method that works requesting with Postman/curl:

        "cpuCount": "4",
        "disks": [
            {
                "size": 20,
                "mountpoint": "/app",
                "label": "appmnt"
            }
        ],


Solution

  • In the example you showed that worked, you've passed a JSON array containing a JSON object, but in your Terraform configuration you've passed only a single JSON object.

    You can pass a JSON array by passing a list or tuple value to jsonencode. For example:

      disks = jsonencode([
        { "mountpoint": "/app", "label": "/appmnt", "size": "20" },
      ])
    

    Terraform will encode this as a JSON array containing a JSON object, which should therefore match your working request:

    [{"mountpoint":"/app","label":"/appmnt","size":"20"}]
    

    Note that this error message seems to be from the vmware/vra provider rather than from Terraform itself, and so this is a question about the disks argument rather than a question about jsonencode. It doesn't really matter, but I wanted to note it in case you have further questions so that you can mention the provider as part of the question title.