Reputation: 1503
I have the following in my main.tf:
data "aws_iam_policy_document" "task_role_policy" {
dynamic "statement" {
for_each = var.policy_statements
content {
actions = statement.value.actions
resources = statement.value.resources
effect = "Allow"
}
}
}
When var.policy_statements is empty list or nothing I get the following error when running terraform apply
:
Error: Error creating IAM policy dev-chatbot-engine-policy: MalformedPolicyDocument: Syntax errors in policy.
status code: 400, request id: a181b065-b659-4261-87d5-9aae8c4454aa
on .terraform/modules/service/main.tf line 68, in resource "aws_iam_policy" "task_role":
68: resource "aws_iam_policy" "task_role" {
Upvotes: 2
Views: 5940
Reputation: 1095
This is a slightly more concise version of stevemao's answer
resource "aws_iam_policy" "task_role" {
count = min(length(var.policy_statements), 1)
// Your other args here...
}
Upvotes: 0
Reputation: 8957
It looks like this policy is still being reference in the aws_iam_policy.task_role
resource when var.policy_statements
is empty.
This would cause aws_iam_policy.task_role
to be created with an empty Statement
(which causes that malformed-policy error you are seeing).
I would recommend setting a count
flag on the policy itself so that it doesn't even attempt to create it when the statements are empty, e.g.
resource "aws_iam_policy" "task_role" {
count = length(var.policy_statements) == 0 ? 0 : 1
// Your other args here...
}
This may have cascading effects to other resources (such as those that consume aws_iam_policy.task_role
). You'll need to handle those effects by providing defaults that don't break or adding a count
there as well.
Upvotes: 5