Search code examples
boto3amazon-ecsaws-fargate

How to list ecs tasks using boto3 client when launch type is Fargate?


I am trying to get list of task arns from a cluster (launch type Fargate) using boto3 client.

If launch type is EC2 then this works:

ecs = boto3.client('ecs')
ecs.list_tasks(
    cluster='cluster_name',
    containerInstance='container_instance_arn',
)

But when launch type is fargate there are no container instances to give to the function. I tried with only cluster name

ecs = boto3.client('ecs')
ecs.list_tasks(
    cluster='cluster_name'
)

but it then fails to “not authorized to perform: ecs:ListTasks on resource: *”

When I use ECS API directly only cluster name is required. (launch type is Fargate)

aws ecs list-tasks --cluster <cluster_name>

{
    "taskArns": [
        "arn:aws:ecs:eu-west-1:xxxxxxxxxxxx:task/679ac0fa-107b-4e7c-b630-9d8ae3a1cb8b",
        "arn:aws:ecs:eu-west-1:xxxxxxxxxxxx:task/8abe5ea2-6323-46fd-b937-c976f273e517",
        "arn:aws:ecs:eu-west-1:xxxxxxxxxxxx:task/98c4e42b-a6a9-4353-b5b9-9ba78f116aa0"
    ]
}

How would I get this same list using boto3?

Edit: Here is a sample policy that I use:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ecs:ListTasks",
                "logs:CreateLogGroup"
            ],
            "Resource": [
                "arn:aws:ecs:*:xxxxxxxxxxx:container-instance/*",
                "arn:aws:logs:eu-central-1:xxxxxxxxxxx:*"
            ]
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:eu-central-1:xxxxxxxxxxx:log-group:/aws/lambda/aTestFunction:*"
        }
    ]
}

Solution

  • The error message told the answer directly.

    “not authorized to perform: ecs:ListTasks on resource: *”
    

    What was needed was to add this statement to the policy:

    {
         "Sid": "VisualEditor0",
         "Effect": "Allow",
         "Action": "ecs:ListTasks",
         "Resource": "*"
    }
    

    Thank you for @Marcin to point me in the right direction.