Last active
February 9, 2021 17:04
-
-
Save mjaromi/2207bbbdacc599e7489ac41710b26ef8 to your computer and use it in GitHub Desktop.
Connect via ssh to EC2 instance in $environment on which $ecsServiceName container is running
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 | |
ecsServiceName=$1 | |
environment=$2 | |
taskNameEcsCluster=$(aws ecs list-clusters | jq -r '.clusterArns[]' | grep $environment | while read cluster; do aws ecs list-services --cluster $cluster | jq -r '.serviceArns[]' | grep "$ecsServiceName$" && echo $cluster; done | rev | cut -d'/' -f1 | rev | sed 'N;s/\n/ /') | |
echo "taskNameEcsCluster: ${taskNameEcsCluster}" | |
taskName=$(echo $taskNameEcsCluster | cut -d' ' -f1) | |
echo "taskName: ${taskName}" | |
ecsCluster=$(echo $taskNameEcsCluster | cut -d' ' -f2) | |
echo "ecsCluster: ${ecsCluster}" | |
ec2Address=$(aws ecs describe-tasks --task $(aws ecs list-tasks --cluster $ecsCluster | jq -r '.taskArns[]' | grep $(aws ecs describe-services --services $taskName --cluster $ecsCluster | jq -r '.services[].events[] | "\(.id) \(.message)"' | grep 'has started' | head -1 | grep -o "[0-9a-f]\{32\}")) --cluster $ecsCluster | jq -r '.tasks[].containers[] | (.networkInterfaces[0].privateIpv4Address, .networkBindings[0].bindIP) | select(length > 0)') | |
if ! [[ ${ec2Address} ]]; then | |
containerInstanceArn=$(aws ecs describe-tasks --task $(aws ecs list-tasks --cluster $ecsCluster | jq -r '.taskArns[]' | grep $(aws ecs describe-services --services $taskName --cluster $ecsCluster | jq -r '.services[].events[] | "\(.id) \(.message)"' | grep 'has started' | head -1 | grep -o "[0-9a-f]\{32\}")) --cluster $ecsCluster | jq -r '.tasks[].containerInstanceArn' | rev | cut -d'/' -f1 | rev) | |
echo "containerInstanceArn: ${containerInstanceArn}" | |
ec2InstanceId=$(aws ecs describe-container-instances --cluster ${ecsCluster} --container-instances ${containerInstanceArn} | jq -r '.containerInstances[].ec2InstanceId') | |
echo "ec2InstanceId: ${ec2InstanceId}" | |
ec2Address=$(aws ec2 describe-instances --instance-ids ${ec2InstanceId} | jq -r '.Reservations[].Instances[].NetworkInterfaces[].PrivateIpAddress') | |
echo "ec2Address: ${ec2Address}" | |
fi | |
if [[ ${ec2Address} ]]; then | |
ssh -o 'StrictHostKeyChecking no' $ec2Address | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment