Last active
November 17, 2023 08:32
-
-
Save alexgit/df89c7447fe4e17c0ce70333452112c0 to your computer and use it in GitHub Desktop.
ECS logs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
function logs { | |
# Parameters: Cluster Name and Service Name | |
local cluster_name="$1" | |
local service_name="$2" | |
echo "Retrieving tasks for ECS service '$service_name' in cluster '$cluster_name'..." | |
# 1. List Tasks for the Service | |
local tasks=$(aws ecs list-tasks --cluster "$cluster_name" --service-name "$service_name" --query 'taskArns' --output text) | |
if [ -z "$tasks" ]; then | |
echo "No tasks found for service $service_name." | |
return 1 | |
fi | |
# 2. Describe the Tasks to get Task Definitions | |
echo "Describing tasks..." | |
local task_definitions=$(aws ecs describe-tasks --cluster "$cluster_name" --tasks $tasks --query 'tasks[].taskDefinitionArn' --output text) | |
# 3. Get Log Configuration from Task Definitions | |
local log_group_name log_stream_prefix | |
for task_def in $task_definitions; do | |
log_group_name=$(aws ecs describe-task-definition --task-definition "$task_def" --query 'taskDefinition.containerDefinitions[].logConfiguration.options."awslogs-group"' --output text) | |
log_stream_prefix=$(aws ecs describe-task-definition --task-definition "$task_def" --query 'taskDefinition.containerDefinitions[].logConfiguration.options."awslogs-stream-prefix"' --output text) | |
# 4. Retrieve and Print Logs for each Task | |
for task_id in $tasks; do | |
local log_stream_name=$(aws logs describe-log-streams --log-group-name "$log_group_name" --log-stream-name-prefix "$log_stream_prefix" --query 'logStreams[0].logStreamName' --output text) | |
if [ "$log_stream_name" != "None" ]; then | |
echo "Logs for task $task_id:" | |
aws logs get-log-events --log-group-name "$log_group_name" --log-stream-name "$log_stream_name" --start-from-head | jq -r '.events[].message' | |
else | |
echo "No logs found for task $task_id." | |
fi | |
done | |
done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment