0
votes
  1. I'm creating a list of IAM policy, which is stored in .json format.
  2. I have only 1 resource block, by using count = length(count) I want to create a multiple IAM policy.
  3. The policies are stored in .json format. I am referring to them in Terraform by using file().

If I create a multiple resources block, the program works.

main.tf:

resource "aws_iam_role_policy" "cloudcheckr" {
  count     = "${length(var.file_name)}"
  role      = "${aws_iam_role.cloudcheckr.id}"   // An IAM role is created in another resource block
  name      = "${var.file_name[count.index]}"
  policy    = "${file("${var.file_name[count.index]}.json")}"

variables.tf:

variable "file_name" {
  type = "list"
  default = [
    "xxxxxx",
    "xxxxxx",
    "xxxxxx",
    "xxxxxx",
  ]
}

Expected results:

  Multiple IAM policies are created.

Actual results:

aws_iam_role_policy.cloudcheckr: 3 error(s) occurred:  

* aws_iam_role_policy.cloudcheckr[3]: file: open iam_policy_cloudcheckr_security.json: no such file or directory in:

${file("${var.file_name[count.index]}.json")}
* aws_iam_role_policy.cloudcheckr[0]: file: open iam_policy_cloudcheckr_cloudwatchflowlogs.json: no such file or directory in:

${file("${var.file_name[count.index]}.json")}
* aws_iam_role_policy.cloudcheckr[2]: file: open iam_policy_cloudcheckr_inventory.json: no such file or directory in:

${file("${var.file_name[count.index]}.json")}
1
Think about using 'Path' : terraform.io/docs/configuration-0-11/interpolation.html A summary: The syntax is path.TYPE. TYPE can be cwd, module, or root. cwd will interpolate the current working directory. module will interpolate the path to the current module. root will interpolate the path of the root module.RtmY

1 Answers

1
votes

There is no problem from first view. But there are still several ways to work out the file path issue.

${path.module} is useful when using file() from inside a module, you generally want to make the path relative to the module base, like this: file("${path.module}/file").

So your code can be changed to

resource "aws_iam_role_policy" "cloudcheckr" {
  count     = "${length(var.file_name)}"
  role      = "${aws_iam_role.cloudcheckr.id}"   // An IAM role is created in another resource block
  name      = "${var.file_name[count.index]}"
  policy    = "${file("${path.module}/${var.file_name[count.index]}.json")}"
}

If this doesn't work, try with format()

  policy    = "${file(format("%s/%s.json", "${path.module}, ${var.file_name[count.index]}"))}"