Home > Mobile >  Allowing ECS Task to read from Kinesis data stream
Allowing ECS Task to read from Kinesis data stream

Time:11-03

I'm deploying an app through ECS (with FARGATE being the capacity provider). My app needs to access a Kinesis stream (already existing and running). I can't figure out the exact IAM assume policy I need to provide. I have the below configuration in Terraform (removed tags, log configuration and proprietary names). Every time I deploy the task I receive an error that the task couldn't assume the role.

What am I missing?

resource "aws_ecs_cluster" "cluster" {
  name = var.cluster_name
}
resource "aws_ecs_service" "service" {
  name            = var.service_name
  cluster         = aws_ecs_cluster.cluster.id
  task_definition = aws_ecs_task_definition.task.arn
  desired_count   = var.task_count
  launch_type     = var.task_launch_type

  load_balancer {
    target_group_arn = var.alb_target
    container_name   = "container"
    container_port   = 3000
  }

  network_configuration {
    subnets          = [for subnet in var.subnets : "${subnet}"]
    assign_public_ip = true
    security_groups  = [var.sg_id]
  }
}
resource "aws_ecs_task_definition" "task" {
  family = "task_family"

  container_definitions = file( var.container_definitions_json )

  requires_compatibilities    = ["FARGATE"]
  network_mode                = "awsvpc"
  memory                      = 1024
  cpu                         = 512

  execution_role_arn          = "${aws_iam_role.ecsTaskExecutionRole.arn}"

  task_role_arn               = "${aws_iam_role.ecsTaskRole.arn}"
}

resource "aws_iam_role" "ecsTaskRole" {
  name = "ecsTaskRole"
  assume_role_policy = "${data.aws_iam_policy_document.ecsTaskRole.json}"
  
}

data "aws_caller_identity" "current" {}

data "aws_partition" "current" {}

data "aws_region" "current" {}

data "aws_iam_policy_document" "ecsTaskRole" {
  statement {
    effect  = "Allow"
    actions = ["sts:AssumeRole"]
    principals {
      type = "AWS"
      identifiers = [
        format("arn:%s:iam::%s:root", data.aws_partition.current.partition, data.aws_caller_identity.current.account_id)
      ]
    }
  }
}
resource "aws_iam_role" "ecsTaskExecutionRole" {
  name               = "ecsTaskExecutionRole"
  assume_role_policy = "${data.aws_iam_policy_document.assume_role_policy.json}"
}

data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

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

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

CodePudding user response:

Both roles must have a trust policy that allows ecs-tasks.amazonaws.com.

See this document for the task role, and this document for the execution role.

  • Related