Gateway rest API resource can't find the file I provide

resource "aws_api_gateway_rest_api" "api" {
  body = "${file("apigateway/json-resolved/swagger.json")}"
  name = "api"
}

---------------------------------------------------------------------------------
Invalid value for "path" parameter: no file exists at apigateway/json-resolved/swagger.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.

When I try to deploy my API by providing the actual path to the API JSON, this is what it throws. Even though the file is there, even though I tried different paths, from relative to absolute, etc. It works when I paste the entire JSON in the body, but not when I provide a file. Why is that?


Since Terraform is not aware of the location of the file, you should specify it explicitly:

  1. If the file is in the same directory, then use ./apigateway/json-resolved/swagger.json
  2. If the file is one directory up from the directory you are running Terraform from, you could use ../apigateway/json-resolved/swagger.json
  3. Alternatively, it is a good idea to use Terraform built-in functions for path manipulation: path.cwd, path.module, or path.root. More detailed explanation about what these three functions represent can be found in [1].
  4. Provide a full path to the file by running pwd in the directory where the file is located (this works on Linux and MacOS) and paste the result of the command in the file function input.

Additionally, any combination of the points 2. and 3. could also work, but you should be careful.

There is also another great answer to a similar question [2].

NOTE: in some cases the path.* functions might not give expected results on Windows. As per this comment [3] from Github, if the paths are used consistently (i.e., all / or all \), Windows should also be able to work with path.* but only for versions of Terraform >=0.12. Based on the code snippet form the question it seems in this case an older version is used.


[1] https://www.terraform.io/language/expressions/references#filesystem-and-workspace-info

[2] Invalid value for "path" parameter: no file exists at

[3] https://github.com/hashicorp/terraform/issues/14986#issuecomment-448756885