Python - Pulling ECS Service logs for a task/container that is terminating

0

I have a python script which is grabbing logs for a ECS cluster that has multiple services. It works for tasks that are running without any issues. I have tasks in few services that are terminating due to errors in the container scripts. I can see the logs/erros when I go to the ECS Cluster -> Click on Service and go to the Logs tab. How do I modify the script to grab those logs thrown by tasks that have terminated

My python script has the following logic.

response = ecs_client.list_services(cluster=cluster_name)
for service in response['serviceArns']:
  serviceResponse = ecs_client.describe_services(cluster=cluster_name, services=[service])
  serviceName = serviceResponse['services'][0]['serviceName']
  taskResponse = ecs_client.list_tasks(
            cluster=cluster_name,
            serviceName=serviceName
  )

 if 'taskArns' not in taskResponse or not taskResponse['taskArns']:
            print(f"No tasks found for {serviceName}")

Since the task is terminating, the script always ends up saying "No tasks found.."

1 Answer
1
Accepted Answer

By default it looks for running tasks. You need to look for stopped tasks.

taskResponse = ecs_client.list_tasks(
            cluster=cluster_name,
            serviceName=serviceName,
            desiredStatus='STOPPED'
 )

desiredStatus (string) – The task desired status to use when filtering the ListTasks results. Specifying a desiredStatus of STOPPED limits the results to tasks that Amazon ECS has set the desired status to STOPPED. This can be useful for debugging tasks that aren’t starting properly or have died or finished. The default status filter is RUNNING, which shows tasks that Amazon ECS has set the desired status to RUNNING.

profile picture
EXPERT
answered 5 months ago
profile pictureAWS
EXPERT
reviewed 5 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions