Last active
April 24, 2019 11:33
-
-
Save AaronTorgerson/b330bd22ca0815b860b2594d2e1d9ae7 to your computer and use it in GitHub Desktop.
SSH into a running Docker container on ECS (depends on awless)
This file contains hidden or 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 | |
| set -e | |
| cluster=$1 | |
| service=$2 | |
| container=$3 | |
| debug=$4 # pass word "debug" as 4th arg to see debug output | |
| check_val () { | |
| if [[ -z "${1}" ]]; then | |
| echo "ERROR: Value did not resolve! ${2}" | |
| exit 1 | |
| elif [[ "${debug}" == "debug" ]]; then | |
| echo "${2} = ${1}" | |
| fi | |
| } | |
| # list the tasks | |
| task_arns=$(aws ecs list-tasks --cluster "${cluster}" --service-name "${service}" | jq -r .taskArns[] | tr '\n' ' ') | |
| check_val "${task_arns}" "Task ARNs" | |
| # get a running task | |
| running_task=$(aws ecs describe-tasks --cluster "${cluster}" --tasks ${task_arns} | jq '.tasks | map(select(.lastStatus == "RUNNING"))[0]') | |
| task_arn=$(echo ${running_task} | jq -r .taskArn) | |
| check_val ${task_arn} "Task ARN" | |
| # get the container instance it's running on | |
| instance_arn=$(echo ${running_task} | jq -r .containerInstanceArn) | |
| check_val ${instance_arn} "Instance ARN" | |
| # get the AWS instance ID for that container instance | |
| instance_id=$(aws ecs describe-container-instances --cluster "${cluster}" --container-instances ${instance_arn} | jq -r .containerInstances[0].ec2InstanceId) | |
| check_val ${instance_id} "Instance ID" | |
| # use SSH to get the container id | |
| ssh_cmd=$(awless ssh --force --print-cli --private -i ~/.ssh/foolwealthawskey ${instance_id}) | |
| check_val "${ssh_cmd}" "SSH Command" | |
| container_id=$(${ssh_cmd} "docker ps --filter \"label=com.amazonaws.ecs.task-arn=${task_arn}\" --filter \"label=com.amazonaws.ecs.container-name=${container}\" --format \"{{.ID}}\"") | |
| check_val ${container_id} "Container ID" | |
| # use SSH again to run docker exec | |
| ${ssh_cmd} -t "docker exec -it ${container_id} /bin/bash" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is some major bending-over-backwards just to get the container ID of a running ECS task (of a service). I'm sure there is a more efficient way to find it, but I wasn't able to figure it out.
NOTE: This script requires
aws[1] to be installed as well asawless[2].awlessis really just a shortcut to help us resolve the private IP and SSH user name for the container instance - that could be done using only theawsCLI and a few more commands.[1]
pip install awscli[2] https://github.com/wallix/awless/wiki/Installation