Im new at Terraform and im trying to create ecsTaskExcecutionRoles for each service i have, i create a module that allows to send a list of secrets, i want to make the inline policy that allows the access optional.
i tried putting inside the inline_policy something like:
count = length(var.secrets_arn_list) > 0 ? 1 : 0
but it’s not possible use count in that place
data "aws_iam_policy_document" "ecs_tasks_execution_role" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ecs-tasks.amazonaws.com"]
}
}
}
resource "aws_iam_role" "ecs_tasks_execution_role" {
name = "TaskExecutionRole-${var.environment}-${var.project}"
assume_role_policy = "${data.aws_iam_policy_document.ecs_tasks_execution_role.json}"
inline_policy {
name = "SecretsManagerAccess-${var.project}-${var.environment}"
policy = jsonencode({
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"secretsmanager:GetResourcePolicy",
"secretsmanager:GetSecretValue",
"secretsmanager:DescribeSecret",
"secretsmanager:ListSecretVersionIds"
],
"Resource": var.secrets_arn_list
}
]
})
}
tags = var.tags
}
resource "aws_iam_role_policy_attachment" "ecs_tasks_execution_role" {
role = "${aws_iam_role.ecs_tasks_execution_role.name}"
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}
Someone knows how to solve it?
2
Answers
Either use a dynamic block, instead of
count
, or move the policy into a separate Terraform aws_iam_role_policy resource and put thecount
on that resource.Yes, there is a way using
dynamic
[1] andfor_each
meta-argument [2]:[1] https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks
[2] https://developer.hashicorp.com/terraform/language/meta-arguments/for_each