Reference a file that is generated by the same script

521 Views Asked by At

Having a trouble referencing a json file that is to be generated by null-resource local-exec.

Here is the snippet of the resource creating the file:

resource "null_resource" "clusterDO" {
  provisioner "local-exec" {
    command = "cat > DO_template.json <<EOL\n ${module.bigip.onboard_do}\nEOL"
  }
  depends_on = [module.bigip.onboard_do]
}

Here is the snippet of the definition causing the error:

resource "bigip_do" "do-example" {
    do_json = "${file("DO_template.json")}"
    timeout = 120
    depends_on = [module.bigip_module]
}

Here is a snippet of the error:

Invalid value for "path" parameter: no file exists at "DO_template.json"; this function works only with files that are distributed as part of the configuration source code, so if this file will be
│ created by a resource in this configuration you must instead obtain this result from an attribute of that resource.

I understand from the error that I can't reference the filename as is, not sure how to make it work, can someone provide an operational example?

Attempted to create the filename as a triggers in the null_resource and then reference it, but I'm getting the same error

2

There are 2 best solutions below

7
Marko E On

You can fix this by using the templatefile built-in function [1] and local_file [2] instead:

resource "local_file" "do_template" {
  content  = jsonencode(templatefile("${path.module}/DO_template.json.tpl", {
    onboard_do = module.bigip.onboard_do
  }))
  filename = "${path.module}/DO_template.json"
}

resource "bigip_do" "do-example" {
    do_json = file("${path.module}/DO_template.json")
    timeout = 120
    depends_on = [local_file.do_template]
}

Then, you would need to slightly adjust the JSON template (now called DO_template.json.tpl):

${onboard_do}

[1] https://developer.hashicorp.com/terraform/language/functions/templatefile

[2] https://registry.terraform.io/providers/hashicorp/local/latest/docs/resources/file#schema

0
Krasnii On

Found a solution, reuse the same variable (being used to generate the local json file) within do_json, as follows:

resource "bigip_do" "do-example" {
    do_json = "${module.bigip.onboard_do}"
    timeout = 120
    depends_on = [local_file.do_template]
}