Skip to content

Instantly share code, notes, and snippets.

@endofcake
Created May 28, 2018 22:59
Show Gist options
  • Save endofcake/c38a0952ae483d2d7b0444d6593bb1aa to your computer and use it in GitHub Desktop.
Save endofcake/c38a0952ae483d2d7b0444d6593bb1aa to your computer and use it in GitHub Desktop.
Run an ECS task and grab its output
#!/bin/bash
set -euo pipefail
# some env vars here
STARTED_BY="$(date +"%T") - $USERNAME"
AWS_DEFAULT_REGION="${REGION}"
TASK_ID=""
# '|| echo $overrides' is used to disable exit on error
# read returns a non-zero exit status if it doesn't find a delimiter, which is always the case when the delimiter is an empty string.
# https://unix.stackexchange.com/questions/265149/why-is-set-o-errexit-breaking-this-read-heredoc-expression/265151#265151
# :facepalm:
echo "Setting task overrides"
read -r -d '' OVERRIDES << EOL || echo $OVERRIDES
{
"containerOverrides": [
{
"name": "$TASK_NAME",
"environment": [
{
"name": "PROJECT",
"value": "$PROJECT"
}
]
}
]
}
EOL
run_ecs_task () {
echo "Starting $TASK_NAME task"
TASK_ID=$(aws ecs run-task \
--cluster $CLUSTER \
--task-definition $TASK_NAME \
--overrides "$OVERRIDES" \
--started-by "$STARTED_BY" \
--query 'tasks[0].taskArn' --output text |
cut -d "/" -f2)
echo "Waiting for task $TASK_ID to complete"
aws ecs wait tasks-stopped \
--cluster $CLUSTER \
--tasks $TASK_ID
echo "Task completed"
}
get_ecs_logs () {
TASK_ID=$1
echo "Getting logs for task $TASK_ID"
aws logs get-log-events \
--log-group-name "$LOG_GROUP" \
--log-stream-name "db/$TASK_NAME/$TASK_ID" \
--query 'events[*].{message: message}' --output text
}
get_exit_code () {
TASK_ID=$1
EXIT_CODE=$(aws ecs describe-tasks \
--cluster "$CLUSTER" \
--tasks "$TASK_ID" \
--query 'tasks[*].containers[0].exitCode' --output text)
exit $EXIT_CODE
}
run_ecs_task
get_ecs_logs $TASK_ID
get_exit_code $TASK_ID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment