Skip to content

Instantly share code, notes, and snippets.

@dsoprea
Last active September 13, 2024 18:13
Show Gist options
  • Save dsoprea/788ad1862913b8a18608ddc18a18f312 to your computer and use it in GitHub Desktop.
Save dsoprea/788ad1862913b8a18608ddc18a18f312 to your computer and use it in GitHub Desktop.
aws: Poll the tasks running for a certain cluster and task-definition
#!/usr/bin/env python3
"""
Copyright 2024 Dustin Oprea
MIT LICENSE
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import datetime
import sys
import subprocess
import json
import argparse
import tabulate
_DESCRIPTION = "List current tasks for the given cluster and task-definition."
def _get_args():
parser = \
argparse.ArgumentParser(
description=_DESCRIPTION)
parser.add_argument(
'cluster',
help="Cluster")
parser.add_argument(
'--task-definition',
help="Task definition")
parser.add_argument(
'--service',
help="Service name")
args = parser.parse_args()
return args
def _get_current_tasks_with_task_definition(cluster, task_definition):
cmd = [
'aws',
'--output', 'json',
'ecs', 'list-tasks',
'--cluster', cluster,
'--family', task_definition,
]
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
# {
# "taskArns": [
# "arn:aws:ecs:us-east-1:326764833890:task/internal-webserver-ssl/36fe1af02a2c40ffae41f6902b78e9d3",
# "arn:aws:ecs:us-east-1:326764833890:task/internal-webserver-ssl/dcf53797df9a4b4c9841ba463a0be9f6"
# ]
# }
info = json.loads(output)
return info['taskArns']
def _get_current_tasks_with_service(cluster, service_name):
cmd = [
'aws',
'--output', 'json',
'ecs', 'list-tasks',
'--cluster', cluster,
'--service', service_name,
]
try:
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as cpe:
print('')
print("Output:")
print('')
print(cpe.output)
print('')
raise
# {
# "taskArns": [
# "arn:aws:ecs:us-east-1:326764833890:task/internal-webserver-ssl/36fe1af02a2c40ffae41f6902b78e9d3",
# "arn:aws:ecs:us-east-1:326764833890:task/internal-webserver-ssl/dcf53797df9a4b4c9841ba463a0be9f6"
# ]
# }
info = json.loads(output)
return info['taskArns']
def _get_task_statuses_gen(cluster, task_arns):
cmd = [
'aws',
'--output', 'json',
'ecs', 'describe-tasks',
'--cluster', cluster,
'--tasks',
] + task_arns
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
# {
# "tasks": [
# {
# "attachments": [],
# "attributes": [
# {
# "name": "ecs.cpu-architecture",
# "value": "x86_64"
# }
# ],
# "availabilityZone": "us-east-1f",
# "clusterArn": "arn:aws:ecs:us-east-1:326764833890:cluster/internal-webserver-ssl",
# "connectivity": "CONNECTED",
# "connectivityAt": "2021-12-08T15:48:42.577000-05:00",
# "containerInstanceArn": "arn:aws:ecs:us-east-1:326764833890:container-instance/internal-webserver-ssl/c22c05e430a4463fa512c007d929e75a",
# "containers": [
# {
# "containerArn": "arn:aws:ecs:us-east-1:326764833890:container/internal-webserver-ssl/dcf53797df9a4b4c9841ba463a0be9f6/12d8c16a-097f-4611-99c9-66cc324a8f98",
# "taskArn": "arn:aws:ecs:us-east-1:326764833890:task/internal-webserver-ssl/dcf53797df9a4b4c9841ba463a0be9f6",
# "name": "extraction-app",
# "image": "326764833890.dkr.ecr.us-east-1.amazonaws.com/extraction-api:20211208154416-74162c6",
# "imageDigest": "sha256:73c9b8e1f00e6f6341db7a3cb7cc0049bffbec48e666fd3332a09386d98d778e",
# "runtimeId": "49bd6710cbf633c7bdae4167269cb9afb40583010d00d3690c2e8b6bf30d537b",
# "lastStatus": "RUNNING",
# "networkBindings": [],
# "networkInterfaces": [],
# "healthStatus": "HEALTHY",
# "cpu": "0",
# "memoryReservation": "384"
# },
# {
# "containerArn": "arn:aws:ecs:us-east-1:326764833890:container/internal-webserver-ssl/dcf53797df9a4b4c9841ba463a0be9f6/990a9da0-b6fe-45a8-be93-2f073fe89da3",
# "taskArn": "arn:aws:ecs:us-east-1:326764833890:task/internal-webserver-ssl/dcf53797df9a4b4c9841ba463a0be9f6",
# "name": "extraction-web",
# "image": "326764833890.dkr.ecr.us-east-1.amazonaws.com/extraction-web:0d10dda",
# "imageDigest": "sha256:3ad8118d24e40a3504b077cbe860d1642b23132e214afa22b3e71954a2685d2e",
# "runtimeId": "6be5462cd67661e8aac8c3b98dccc8abe0c258afe97ef639be48224b0ce01cbe",
# "lastStatus": "RUNNING",
# "networkBindings": [
# {
# "bindIP": "0.0.0.0",
# "containerPort": 443,
# "hostPort": 443,
# "protocol": "tcp"
# }
# ],
# "networkInterfaces": [],
# "healthStatus": "UNKNOWN",
# "cpu": "0",
# "memoryReservation": "128"
# }
# ],
# "cpu": "0",
# "createdAt": "2021-12-08T15:48:42.577000-05:00",
# "desiredStatus": "RUNNING",
# "enableExecuteCommand": false,
# "group": "service:extraction-api-app",
# "healthStatus": "HEALTHY",
# "lastStatus": "RUNNING",
# "launchType": "EC2",
# "memory": "512",
# "overrides": {
# "containerOverrides": [
# {
# "name": "extraction-app"
# },
# {
# "name": "extraction-web"
# }
# ],
# "inferenceAcceleratorOverrides": []
# },
# "pullStartedAt": "2021-12-08T15:48:46.319000-05:00",
# "pullStoppedAt": "2021-12-08T15:48:48.678000-05:00",
# "startedAt": "2021-12-08T15:48:49.324000-05:00",
# "startedBy": "ecs-svc/2320040379308926476",
# "tags": [],
# "taskArn": "arn:aws:ecs:us-east-1:326764833890:task/internal-webserver-ssl/dcf53797df9a4b4c9841ba463a0be9f6",
# "taskDefinitionArn": "arn:aws:ecs:us-east-1:326764833890:task-definition/extraction-api:100",
# "version": 2
# }
# ],
# "failures": []
# }
info = json.loads(output)
yield from info['tasks']
def _main():
args = _get_args()
if args.task_definition is not None:
task_arns = \
_get_current_tasks_with_task_definition(
args.cluster,
args.task_definition)
elif args.service is not None:
task_arns = \
_get_current_tasks_with_service(
args.cluster,
args.service)
else:
raise Exception("Pass --task-definition or --service.")
if not task_arns:
print("No tasks.")
print('')
sys.exit(0)
tasks = _get_task_statuses_gen(args.cluster, task_arns)
lines = []
for task in tasks:
digests = sorted([
'{}={}'.format(
container['name'],
container.get('imageDigest', '').replace('sha256:', '')[:10] or '-')
for container
in task['containers']
])
task_arn = task['taskArn']
parts = task_arn.split('/')
task_id_last_part = parts[-1]
task_definition = task['taskDefinitionArn']
parts = task_definition.split('/')
task_definition_last_part = parts[-1]
lines.append((
task.get('startedAt') or '-',
task_definition_last_part,
task_id_last_part,
','.join(digests),
task['lastStatus'],
task.get('startedBy') or '-',
))
# Sort by, effectively, the stringified started-at timestamp.
lines = sorted(lines)
now_dt = datetime.datetime.utcnow()
now_dt = now_dt.replace(microsecond=0)
print(now_dt)
print('')
headers = [
'Timestamp',
'Definition',
'Task ID',
'Digests',
'Status',
'Started By',
]
print(tabulate.tabulate(lines, headers=headers))
print('')
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment