amazon-web-servicesamazon-s3terraformaws-policiesaws-roles

Cannot create Amazon S3 access policy with terraform


I'm trying to create the following policy to give full access to Amazon S3 to one of my task definitions (ECS). This is the terraform code I'm using:

data "aws_iam_policy_document" "inline_policy_s3" {
  version = "2012-10-17"
  statement {
    sid       = ""
    actions   = ["sts:AssumeRole", "s3:*"]
    effect    = "Allow"
    resources = ["*"]

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

resource "aws_iam_role" "task_role" {
  name               = "ecs_service_task_role"
  assume_role_policy = data.aws_iam_policy_document.inline_policy_s3.json
}

The problem is that I'm getting this error when I run terraform apply:

╷
│ Error: Error creating IAM Role ecs_service_task_role: MalformedPolicyDocument: Has prohibited field Resource
│       status code: 400, request id: 25afe8f8-cc66-4533-8f66-9a1f2aeb656b
│ 
│   with module.service.aws_iam_role.task_role,
│   on service/task_role_policy.tf line 16, in resource "aws_iam_role" "task_role":
│   16: resource "aws_iam_role" "task_role" {
│ 
╵

I have tried changing some of the attributes of the policy, but I cannot find the problem. Any idea what's going on?


Solution

  • Thrust policies don't have resources and can't have any other permissions than sts:AssumeRole. So it should be:

    data "aws_iam_policy_document" "inline_policy_s3" {
      version = "2012-10-17"
      statement {
        sid       = ""
        actions   = ["sts:AssumeRole"]
        effect    = "Allow"
    
        principals {
          type        = "Service"
          identifiers = ["ecs-tasks.amazonaws.com"]
        }
      }
    }
    

    For your s3 permissions, you need to create them through, for example, inline_policy.