terraformterraform-provider-awsterraform0.12+

How do I add more permissions to this policy?


I have created a Fargate ECS service that has a execution role with the following policy attached:

data "aws_iam_policy_document" "ecs_task_execution_role" {
  version = "2012-10-17"
  statement {
    sid     = ""
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }
  }
}

I also need it to be able to access a secret from secrets manager for the image registry credentials so I tried the following:

data "aws_iam_policy_document" "ecs_task_execution_role" {
  version = "2012-10-17"
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }
  }
  statement {
    effect  = "Allow"
    actions = ["secretsmanager:GetSecretValue"]
    resources = ["${resource.aws_secretsmanager_secret.secret.arn}"]
  }
}

The Terraform plan works fine but the apply fails with the following error:

Error: updating IAM Role (dev-fidc-identity-gateway-ecs-role) assume role policy: MalformedPolicyDocument: Has prohibited field Resource

Any ideas why this might be happening? I have been unable to find the answer.


Solution

  • Assuming you have created an ECS Execution Role in Terraform, using the Assume Role Policy in your question, like so:

    resource "aws_iam_role" "ecs_task_execution_role" {
      name = "my_ecs_task_execution_role"
    
      assume_role_policy = data.aws_iam_policy_document.ecs_task_execution_role.json
    }
    

    All you have done so far is create an empty role that ECS can assume, with no permissions assigned to it. To add permissions to the role, you need to attach some policies.

    You can attach an existing policy like so:

    resource "aws_iam_role_policy_attachment" "ecs_execution" {
      role       = aws_iam_role.ecs_task_execution_role.name
      policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
    }
    

    If you want to create a new policy, and attach it to the role, you would do the following:

    data "aws_iam_policy_document" "ecs_task_secrets_policy" {
      version = "2012-10-17"
      statement {
        effect  = "Allow"
        actions = ["secretsmanager:GetSecretValue"]
        resources = ["${resource.aws_secretsmanager_secret.secret.arn}"]
      }
    }
    
    resource "aws_iam_role_policy" "ecs_task_secrets_policy" {
      name   = "my_ecs_task_secrets_policy"
      role   = aws_iam_role.ecs_task_execution_role.id
      policy = data.aws_iam_policy_document.ecs_task_secrets_policy.json
    }