Is there a way to import JSON with interpolation taking place?

I’m using Auth0 to configure my ECS tasks in AWS.

I have files containing things like:

 container_definitions = <<DEFINITION
    "name": "${var.workspace}-${var.taskName}",
    "command": [

I’d love to extract my JSON into an actual .json file so that I can benefit from validation and formatting in my IDE, but if I do that, I lose the ability to inject values through variable interpolation.

Is there a way to achieve the former without losing the latter?

Hi @dancrumb,

As long as you are only using ${ ... } sequences inside quoted strings as you showed in your example, a template like that factored out into a separate file should still be valid JSON that your editor could understand.

Given that, you could replace your container_definitions expression with a call to the templatefile function:

  container_definitions = templatefile("${path.module}/container_definitions.json", {
    workspace = var.workspace
    taskName  = var.taskName
    command   = var.command

Inside the container_definitions.json file you’d refer to these arguments using e.g. ${ workspace } instead of ${ var.workspace } because an external template is evaluated in a different scope built from that second argument to templatefile.

Another option would be to write the container definitions directly in the Terraform language syntax and have Terraform convert the result to JSON using jsonencode. This would then let you use the Terraform language validation and highlighting in your editor, as opposed to the JSON highlighting:

  container_definitions = jsonencode([
      "name": "${var.workspace}-${var.taskName}",
      "command": [

A key advantage of this approach is that you can freely use values of any type inside the literal object, without worrying about separately encoding/escaping each value. The var.command reference in the above doesn’t need to be interpolated into a string because jsonencode can already see that it’s a string, so it’ll automatically produce a valid JSON quoted string containing whatever is in var.command, handling automatically any necessary escaping of quotes and backslashes.

1 Like