Home > Mobile >  Conditional inline_policy in aws_iam_role
Conditional inline_policy in aws_iam_role

Time:10-15

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?

CodePudding user response:

Yes, there is a way using dynamic [1] and for_each meta-argument [2]:

dynamic "inline_policy" {
  for_each = length(var.secrets_arn_list) > 0 ? [1] : []
  content {
    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 
          }
        ]
    })
  }
}

[1] https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks

[2] https://developer.hashicorp.com/terraform/language/meta-arguments/for_each

CodePudding user response:

Either use a dynamic block, instead of count, or move the policy into a separate Terraform aws_iam_role_policy resource and put the count on that resource.

  • Related