Terraform Tips, Invalid value for ”path” parameter: no file exists...

課題

下記のようなコードで、Terraformのモジュールのディレクトリからfile()を使ってファイルを読もうとすると、

resource "aws_iam_policy" "send_mail" {
  name        = "${var.env}-lambda-send-mail"
  path        = "/"
  description = "For IAM Role, ${var.env}-lambda-send-mail"
  policy      = file("templates/iam_policy_send_mail.json")
}

次のようなエラーが出る。

╷
│ Error: Invalid function argument
│
│   on ..\modules\personal-website-backend\main.tf line 10, in resource "aws_iam_policy" "send_mail":
│   10:   policy      = file("templates/iam_policy_send_mail.json")
│     ├────────────────
│     │ while calling file(path)
│
│ Invalid value for "path" parameter: no file exists at "templates/iam_policy_send_mail.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.

解決

絶対パスを使って指定する。

${path.module}でモジュールのパスが取れるので、以下のように書けば解決。

resource "aws_iam_policy" "send_mail" {
  name        = "${var.env}-lambda-send-mail"
  path        = "/"
  description = "For IAM Role, ${var.env}-lambda-send-mail"
  policy      = file("${path.module}/templates/iam_policy_send_mail.json")
}

参考