Created
July 20, 2019 04:21
-
-
Save windix/1cdfb2a77ba7d1a7de473c1f67253bb7 to your computer and use it in GitHub Desktop.
Bash script to get ec2 instance-id from ecs service
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
#!/usr/bin/env bash | |
ENV=dev | |
AWS_PROFILE=${ENV} | |
CLUSTER=${ENV}-cluster | |
if [[ -z $1 ]]; then | |
echo "USAGE: $0 service-keyword" | |
exit 1 | |
fi | |
echo "CLUSTER: ${CLUSTER}" | |
SERVICE=($(aws ecs list-services --cluster ${CLUSTER} | jq -r '.serviceArns[]' | grep $1)) | |
echo "SERVICE:" | |
printf '%s\n' "${SERVICE[@]}" | |
if [[ ${#SERVICE[@]} -ne 1 ]]; then | |
echo "Mutiple services found. Quit..." | |
exit 1 | |
fi | |
TASKS=($(aws ecs list-tasks --cluster ${CLUSTER} --service-name ${SERVICE[0]} | jq -r '.taskArns[]')) | |
# If the output may contain spaces | |
# while IFS= read -r line; do | |
# TASKS+=( "$line" ) | |
# done < <( aws ecs list-tasks --cluster ${CLUSTER} --service-name ${SERVICE} | jq -r '.taskArns[]' ) | |
# If bash 4 is available | |
#mapfile -t TASKS < <( aws ecs list-tasks --cluster ${CLUSTER} --service-name ${SERVICE} | jq -r '.taskArns[]' ) | |
echo "TASKS:" | |
printf '%s\n' "${TASKS[@]}" | |
CONTAINER_INSTANCES=($(aws ecs describe-tasks --cluster ${CLUSTER} --tasks ${TASKS[@]} | jq -r '.tasks[].containerInstanceArn')) | |
echo "CONTAINER_INSTANCES:" | |
printf '%s\n' "${CONTAINER_INSTANCES[@]}" | |
EC2_INSTANCES=$(aws ecs describe-container-instances --cluster ${CLUSTER} --container-instances ${CONTAINER_INSTANCES[@]} | jq -r '.containerInstances[].ec2InstanceId') | |
echo "EC2_INSTANCES:" | |
printf '%s\n' "${EC2_INSTANCES[@]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment