Why my file function cannot read an existing file on disk?

Hi everyone,

I am trying to use a shell file to be executed using terraform on a linux VM.
I have created the file in a scripts folder on the root of all my terraform files and I am currently using as this:

data “template_file” “set_VM_script” {
template = file(“userdata/scripts/setvm.sh”)

vars = {
pwd = “12345”
}
}

I am getting an error like this when I execute terraform plan:

│ Error: Invalid function argument
│
│   on compute.tf line 278, in data "template_file" "set_VM_script":
│  278:   template = file("userdata/scripts/setvm.sh")
│
│ Invalid value for "path" parameter: no file exists at "userdata/scripts/setvm.sh"; 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.

Can anyone help understand what is wrong?

Thank you

Hi @luissimoesneom!

Unfortunately since I can’t see what you have in your filesystem I’m only able to guess here, but I do have a few observations and suggestions.

First: in your question you mentioned “a scripts folder on the root of all of your Terraform files”, but the configuration example you shared has a scripts directory nested inside a “userdata” directory. Are you sure the filesystem layout agrees with the configuration here?

Typically I would recommend that most uses of the file function should use a path that starts with ${path.module} so that Terraform can automatically insert the path of the current module and thus the module will be “portable” to use in various different contexts. I would suggest changing your path expression to be the following and then see what difference that makes:

"${path.module}/userdata/scripts/setvm.sh"

This may still produce a similar error, but if it does then I suggest to look closely at exactly what path the error message is referring to, and make sure your file is really at that path.

It might be interesting to take the exact path from the new error message and use it with a shell command that will print that file into your terminal, to see if that works. If you are on a Unix system then you could use the cat command, or use the type command on a Windows system.

1 Like

Hey thanks for the help.

I actually ended up finding out that the error was a mispelled filename… one was referred as vnc and on another I had vcn… It was just confusing to the eyes and a silly mistake.

In any case, thanks for your feedback. Much appreciated.