Last active
July 26, 2017 14:50
-
-
Save ryohang/bad41208454aca9c861e3b1d12288c86 to your computer and use it in GitHub Desktop.
cron job check spot instance 2 minutes termination to deregister from application load balancer target group
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 | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
target_group is an array variable