Search code examples
jsonterraformterraform-template-file

How to convert string to number in terraform template file


I have a terraform template file source.tpl - it's a json and it has to be JSON, because it's produced by python json library. This file has the following entry

[
    {
        "data": {
            "address": "${NETWORK}",
            "netmask": "${NETMASK}",
        }
    }
]

In my tf module, I render this template:

data "template_file" "source" {
  template = "${file("${path.module}/source.tpl")}"
  vars = {
    NETWORK = element(split("/", "${var.cidr}"),0)
    NETMASK = tonumber(element(split("/", "${var.cidr}"),1))
  }
}

where cidr is a string - something like 10.1.1.0/24

In the rendered output I need NETMASK to be a number and NETWORK to be a string. I.e. it has to be something like:

                    data        = {
                        address   = "10.1.1.0"
                        netmask   = 24
                    }

But I'm getting:

                    data        = {
                        address   = "10.1.1.0"
                        netmask   = "24"
                    }

I.e. netmask is a string. How can I get rid of those quotes in terraform? Initial source.tpl should still have those quotes, because if I remove them - it becomes invalid JSON.


Solution

  • I understand the problem here, you're generating the template using a JSON library that cannot produce something like the following since it's invalid JSON, though this is what you want for the template to be

    [
        {
            "data": {
                "address": "${NETWORK}",
                "netmask": ${NETMASK}
            }
        }
    ]
    

    Might I recommend a little bit of preprocessing? For example

      template = "${replace(file("${path.module}/source.tpl"), "\"$${NETMASK}\"", "$${NETMASK}")}"