Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
cron job check spot instance 2 minutes termination to deregister from application load balancer target group
#!/bin/bash
echo "start spot termination check"
meta_url=http://169.254.169.254/latest/meta-data
if curl -s $meta_url/spot/termination-time | grep -q .*T.*Z; then
target_group=${tgARN};
role_arn='${role}'
keyId=`curl -s $meta_url/iam/security-credentials/$role_arn | python -c "import sys, json; obj = json.load(sys.stdin); print(obj['AccessKeyId'])"`
secretKey=`curl -s $meta_url/iam/security-credentials/$role_arn | python -c "import sys, json; obj = json.load(sys.stdin); print(obj['SecretAccessKey'])"`
token=`curl -s $meta_url/iam/security-credentials/$role_arn | python -c "import sys, json; obj = json.load(sys.stdin); print(obj['Token'])"`
export AWS_ACCESS_KEY_ID=$keyId
export AWS_SECRET_ACCESS_KEY=$secretKey
export AWS_SESSION_TOKEN=$token
export AWS_DEFAULT_REGION=${AWS::Region}
instance_id=`curl -s $meta_url/instance-id`;
for target in $target_group
do
:
instance_ports=`aws elbv2 describe-target-health --target-group-arn $target | python -c "import sys, json; obj = json.load(sys.stdin); results = [ node for node in obj['TargetHealthDescriptions'] if node['Target']['Id']=='$instance_id']; ports = [ str(node['Target']['Port']) for node in results if node['TargetHealth']['State']=='healthy']; print ' '.join(ports)"`
echo instance mapping port to elb is $instance_ports
for port in $instance_ports
do
:
echo deregister instance $instance_id port $port from target group $target
aws elbv2 deregister-targets --target-group-arn $target --targets Id=$instance_id,Port=$port
done
done
else
echo "complete spot termination check"
fi
@ryohang
Copy link
Author

ryohang commented Jul 26, 2017

target_group is an array variable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment