Files

116 lines
5.2 KiB
Bash

#!/bin/bash
set -e
export AWS_PAGER=""
function scale_services(){
UP_DOWN="${1:?}"
SERVICE_NAME="${2:?}" # Take service name as an argument
SERVICE_TASK_ARNS=""
ADJUST_AUTOSCALING="${3:-}"
COUNT="${4:-1}"
# Set the minimum capacity and desired count in the cluster to 0 to scale down or to the original size to scale back to normal.
# This is a bit hacky, but the update-service has to happen first when scaling up and second when scaling down.
# Assume scaling down unless "up".
CAPACITY=0
CAPACITY_MAX=0
if [ "${UP_DOWN:?}" = "up" ]; then
aws ecs update-service --region "${REGION:?}" --cluster "${ECS_CLUSTER:?}" --service "${SERVICE_NAME:?}" --desired-count "${COUNT:?}"
CAPACITY="${MIN_CAPACITY:?}"
CAPACITY_MAX="${MAX_CAPACITY:?}"
fi
if [ -n "${ADJUST_AUTOSCALING}" ]; then
aws application-autoscaling register-scalable-target --region "${REGION:?}" --service-namespace ecs --resource-id "service/${ECS_CLUSTER:?}/${SERVICE_NAME:?}" --scalable-dimension "ecs:service:DesiredCount" --min-capacity "${CAPACITY:?}" --max-capacity "${CAPACITY_MAX:?}"
fi
# Capture the service's current tasks before scaling down so we can wait for
# those exact tasks to reach STOPPED, not just for the service to report stable.
if [ "${UP_DOWN:?}" != "up" ]; then
SERVICE_TASK_ARNS="$(aws ecs list-tasks --region "${REGION:?}" --cluster "${ECS_CLUSTER:?}" --service-name "${SERVICE_NAME:?}" --desired-status RUNNING --query 'taskArns' --output text)"
fi
# We are scaling down, make it 0
if [ "${UP_DOWN:?}" != "up" ]; then
aws ecs update-service --region "${REGION:?}" --cluster "${ECS_CLUSTER:?}" --service "${SERVICE_NAME:?}" --desired-count 0
fi
# The first task definition might never get stable because it never had initial migrations so don't wait before continuing
if [ "${TASK_DEFINITION_REVISION}" != "1" ]; then
# Wait for scale-down to succeed
aws ecs wait services-stable --region "${REGION:?}" --cluster "${ECS_CLUSTER:?}" --services "${SERVICE_NAME:?}"
fi
# services-stable only guarantees there are no RUNNING tasks for the service.
# Wait for the tasks we observed before scale-down to be fully STOPPED as well.
if [ "${UP_DOWN:?}" != "up" ] && [ -n "${SERVICE_TASK_ARNS}" ] && [ "${SERVICE_TASK_ARNS}" != "None" ]; then
# Intentionally unquoted so the tab/space-delimited ARN list is passed as
# separate --tasks arguments to the AWS CLI.
aws ecs wait tasks-stopped --region "${REGION:?}" --cluster "${ECS_CLUSTER:?}" --tasks ${SERVICE_TASK_ARNS}
fi
}
for ARGUMENT in "$@"
do
KEY=$(echo $ARGUMENT | cut -f1 -d=)
KEY_LENGTH=${#KEY}
VALUE="${ARGUMENT:$KEY_LENGTH+1}"
export "$KEY"="$VALUE"
done
# If an IAM role ARN is provided, assume it and export AWS temporary credentials
if [ -n "${ASSUME_ROLE_ARN:-}" ]; then
SESSION_NAME="${ASSUME_ROLE_SESSION_NAME:-migrate-$(date +%s)}"
echo "Assuming role ${ASSUME_ROLE_ARN} with session name ${SESSION_NAME}" >&2
# Retrieve temporary credentials via AWS STS
read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN <<< "$(
aws sts assume-role \
--role-arn "${ASSUME_ROLE_ARN}" \
--role-session-name "${SESSION_NAME}" \
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \
--output text
)"
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
fi
scale_services down "${ECS_SERVICE:?}" true "${DESIRED_COUNT}"
if [ -n "${VULN_SERVICE}" ]; then
scale_services down "${VULN_SERVICE:?}"
fi
# Call aws ecs run-task
TASK_ARN="$(aws ecs run-task --region "${REGION:?}" --cluster "${ECS_CLUSTER:?}" --task-definition "${TASK_DEFINITION:?}":"${TASK_DEFINITION_REVISION:?}" --launch-type FARGATE --network-configuration "awsvpcConfiguration={subnets="${SUBNETS:?}",securityGroups="${SECURITY_GROUPS:?}"}" --query 'tasks[].taskArn' --overrides '{"containerOverrides": [{"name": "fleet", "command": ["fleet", "prepare", "db"]}]}' --output text | rev | cut -d'/' -f1 | rev)"
# Wait for completion with configurable timeout
ELAPSED=0
while [ "$ELAPSED" -lt "${TIMEOUT_SECONDS:-600}" ]; do
sleep 30
ELAPSED=$((ELAPSED + 30))
TASK_STATUS=$(aws ecs describe-tasks --region "${REGION:?}" --cluster "${ECS_CLUSTER:?}" --tasks "${TASK_ARN:?}" --query "tasks[0].lastStatus" --output text)
if [ "$TASK_STATUS" = "STOPPED" ]; then
break
fi
echo "Migration task status: ${TASK_STATUS} (elapsed: ${ELAPSED}s / ${TIMEOUT_SECONDS:-600}s)" >&2
done
if [ "$TASK_STATUS" != "STOPPED" ]; then
echo "ERROR: Migration task timed out after ${TIMEOUT_SECONDS:-600} seconds." >&2
echo "Task ARN: ${TASK_ARN}" >&2
echo "Task Status: ${TASK_STATUS}" >&2
echo "Check the task manually:" >&2
echo " aws ecs describe-tasks --region ${REGION} --cluster ${ECS_CLUSTER} --tasks ${TASK_ARN}" >&2
echo "If the task completed successfully, re-running terraform apply will detect this and continue." >&2
exit 1
fi
scale_services up "${ECS_SERVICE:?}" true "${DESIRED_COUNT}"
if [ -n "${VULN_SERVICE}" ]; then
scale_services up "${VULN_SERVICE:?}"
fi
# Exit with task's exit code
TASK_EXIT_CODE=$(aws ecs describe-tasks --region "${REGION:?}" --cluster "${ECS_CLUSTER:?}" --tasks "${TASK_ARN:?}" --query "tasks[0].containers[?name=='fleet'].exitCode" --output text)
exit "${TASK_EXIT_CODE}"