Skip to content

Instantly share code, notes, and snippets.

@aasmith
Created February 12, 2018 04:12
Show Gist options
  • Save aasmith/7986077ed98df7a704fca359bf62e13e to your computer and use it in GitHub Desktop.
Save aasmith/7986077ed98df7a704fca359bf62e13e to your computer and use it in GitHub Desktop.
Place an instance exclusively into an AWS LB Target Group
#!/bin/bash
set -euo pipefail
function log {
echo "$(date +%T): $@"
}
tgname=$1
iid=$2
log "Getting ARN for Target Group '$tgname'..."
# Find tg ARN
target_group=$(aws elbv2 describe-target-groups \
--no-paginate \
--names "$tgname" \
--query "TargetGroups[0].TargetGroupArn" \
--output text)
log "Adding instance '$iid' to Target Group '$target_group'"
# add instance to target group
aws elbv2 register-targets \
--target-group-arn "$target_group" \
--targets Id="$iid"
log "Added instance '$iid' to Target Group '$target_group'"
# List instances in TG, excluding the new one just added
old_iids=$(aws elbv2 describe-target-health \
--target-group-arn "$target_group" \
--query 'TargetHealthDescriptions[].Target[].Id|join(`\n`, @)' \
--output text | grep -v "$iid")
log "Removing instances: $old_iids"
remove_iids=
for i in $old_iids; do
remove_iids="$remove_iids Id=$i"
done
# deregister old ones, joined with Id=
aws elbv2 deregister-targets \
--target-group-arn "$target_group" \
--targets $remove_iids
log "Removal complete"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment