Have you ever had the problem where you quickly need to know what IP does a container use when running in the ECS?
Well, here’s one for that…
- Upload to your cloudshell.
- run
chmod +x ecs2ip.sh - then, execute such as
./ecs2ip.sh devor./ecs2ip.sh dev 'container-name'
#!/bin/bash
CLUSTER="$1"
SEARCH="$2"
if [ -z "$CLUSTER" ]
then
echo "Usage: $0 ['optional search phrase']"
exit 1
fi
# Change to match your region, or add as an argument...
REGION=eu-west-1
TASK_ARNS=$(aws ecs list-tasks \
--cluster "$CLUSTER" \
--desired-status RUNNING \
--region "$REGION" \
--query 'taskArns' \
--output text)
[ -z "$TASK_ARNS" ] && echo "No running tasks found" && exit 0
printf '%s\n' $TASK_ARNS | xargs -n100 | while read -r CHUNK; do
aws ecs describe-tasks \
--cluster "$CLUSTER" \
--region "$REGION" \
--tasks $CHUNK \
--output json \
| jq -r '
.tasks[] as $t
| (
$t.attachments[]
| select(.type=="ElasticNetworkInterface")
| .details[]
| select(.name=="privateIPv4Address")
| .value
) as $ip
| $t.containers[].name as $c
| "container=\($c) ip=\($ip) taskArn=\($t.taskArn)"
'
done 2>&1 > /tmp/ecslist.txt
if [ -z "$SEARCH" ]
then
cat /tmp/ecslist.txt
else
grep "$SEARCH" /tmp/ecslist.txt
fi
rm /tmp/ecslist.txt
The output would look something like:
[cloudshell-user@ip-*****~]$ ./ecs2ip.sh dev container-name
container=container-name ip=10.0.0.1 taskArn=arn:aws:ecs:eu-west-1:**************:task/dev/****…***
container=container-name ip=10.0.0.2 taskArn=arn:aws:ecs:eu-west-1:**************:task/dev/****…***
Njoy!
