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

Viewed 4765

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:*"
        }
    ]
}
2 Answers

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.

The command you are using:

ecs.list_tasks(cluster='cluster_name')

is correct. However the error you are getting:

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

indicates that whichever IAM user/role you are using to run it, has no permissions to ecs:ListTasks. Thus you have to double check which user/role is used to execute your script.

Related