terraformterragrunt

Terraform: Create tfvars from local values


I have a data structure like the following:

locals {
  replication_tasks = {
    track_to_s3_live = {
      replication_task_id       = "track-to-s3"
      migration_type            = "full-load-and-cdc"
      replication_task_settings = file("files/s3_tracking_cdc_settings.json")
      table_mappings            = file("files/s3_tracking_table_mappings.json")
      source_endpoint_key       = "source"
      target_endpoint_key       = "s3_tracking"
    }
  }
}

From this, I'm trying to write the equivalent .tfvars file (to be used in another module). Something like:

resource "local_file" "file" {
  content  = <<EOF
replication_tasks = "${local.replication_tasks}"
EOF
  filename = "${path.module}/tasks.auto.tfvars"
}

But I get this error:

Cannot include the given value in a string template: string required.

Any suggestion about how to achieve this?


Solution

  • Not sure why you would want to do this, but to generate the desired file you can just serialize the local value:

    resource "local_file" "file" {
      content  = <<EOF
    replication_tasks =  ${jsonencode(local.replication_tasks)}
    EOF
      filename = "${path.module}/tasks.auto.tfvars"
    }