Skip to content

Instantly share code, notes, and snippets.

@foxutech
Last active September 24, 2018 17:24
Show Gist options
  • Save foxutech/7975a6973584df4c2f1f20503d4c8f48 to your computer and use it in GitHub Desktop.
Save foxutech/7975a6973584df4c2f1f20503d4c8f48 to your computer and use it in GitHub Desktop.
Monitor AWS ECS Agent & restart agent automatically if any failure
#!/bin/bash
set -e
source /etc/ecs/ecs.config
CONTAINERS_ID=$(aws ecs list-container-instances --cluster $ECS_CLUSTER --output text --query 'containerInstanceArns')
echo $(CONTAINERS_ID)
INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)
echo $(INSTANCE_ID)
DATE=$(date +%Y-%m-%d-%H:%M)
read -p "enter aws-account-id: " aws-account-id
read -p "enter SNS topic: " topic
TOPIC="arn:aws:sns:us-west-2:$aws-account-id:$topic-name"
echo $TOPIC
for container in $CONTAINERS_ID
do
STATUS=$(aws ecs describe-container-instances --container-instances $container --cluster $ECS_CLUSTER --output json --query 'containerInstances[0].agentConnected')
CHECK_INSTANCE_ID=$(aws ecs describe-container-instances --container-instances $container --cluster $ECS_CLUSTER --output text --query 'containerInstances[0].ec2InstanceId')
if [ $INSTANCE_ID == $CHECK_INSTANCE_ID ]
then
if [ $STATUS == "false" ]
then
echo "Agent Disconnected" $DATE >> /var/log/script.log
aws sns publish --message "AWS ECS Agent Failed $INSTANCE_ID $DATE" --topic $TOPIC
sudo stop ecs
sudo start ecs
else
echo "Agent Connected" $DATE >> /var/log/script.log
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment