Reputation: 193
Please help to understand how to create something like this?
data "aws_iam_policy_document" "assume_role_policy" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
dynamic "statement" {
for_each = var.assume_role_identities != [] ? [true] : []
content {
actions = ["sts:AssumeRole"]
principals {
type = "AWS"
identifiers = var.assume_role_identities
}
}
}
dynamic "statement" {
for_each = var.assume_role_services != [] ? [true] : []
content {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = var.assume_role_services
}
}
}
}
The problem with this code is that if I will not specify any roles or services which should have access, it's an exit with an error that no principals. Is it possible to set on the dynamic block some count condition? or how to workaround it?
Explanation of problem :
The problem that if I want to pass only some one value, it will not work cause it forming an empty value
This is what terraform apply on this casem if I add only identity records
+ assume_role_policy = jsonencode(
{
+ Statement = [
+ {
+ Action = "sts:AssumeRole"
+ Effect = "Allow"
+ Principal = {
+ Service = "ec2.amazonaws.com"
}
+ Sid = ""
},
+ {
+ Action = "sts:AssumeRole"
+ Effect = "Allow"
+ Principal = {
+ AWS = "arn:aws:iam::account_id:user/some_user"
}
+ Sid = ""
},
+ {
+ Action = "sts:AssumeRole"
+ Effect = "Allow"
+ Principal = {
+ Service = []
}
+ Sid = ""
},
]
+ Version = "2012-10-17"
}
)
And from this appearing the problem :
Error creating IAM Role name-role: MalformedPolicyDocument: Invalid principal in policy: com.amazon.balsa.error.InvalidPolicyException: The passed in policy has a statement with no principals!
Upvotes: 0
Views: 2501
Reputation: 1273
This should do the trick:
data "aws_iam_policy_document" "assume_role_policy" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
dynamic "statement" {
for_each = length(var.assume_role_identities) > 0 ? [var.assume_role_identities] : []
content {
actions = ["sts:AssumeRole"]
principals {
type = "AWS"
identifiers = var.assume_role_identities
}
}
}
dynamic "statement" {
for_each = length(var.assume_role_services) > 0 ? [var.assume_role_services] : []
content {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = var.assume_role_services
}
}
}
}
You don't event need the first statement, you can pass it as an argument to var.assume_role_services
Upvotes: 6