Created
September 28, 2020 09:16
-
-
Save rahulinux/d48ee5931d438af898e76dcbfa9ef2d6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
# This script will run from ec2 user data | |
# and it will deattach secondary network interface(ENI) | |
# from previous instance if any old instance found | |
# If ENI is not attach then it will not run deattach command | |
# at the last it will run eni attach command to add eni in current instance | |
# | |
# Note: Make sure to update ENI Name Tag in variable NAME_TAG | |
# exit if anything goes wrong | |
set -e | |
# Configure Value of Name tag for ENI | |
NAME_TAG="MY_NETWORK_ENI_NAM_TAG_CHANGE_THIS" | |
AWS_CMD="aws --region $AWS_DEFAULT_REGION" | |
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id) | |
AWS_DEFAULT_REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | \ | |
awk 'BEGIN { FS="\""; RS="," };/region/{ print $4}') | |
# Get Network Interface ID | |
ENI_ID=$($AWS_CMD ec2 describe-network-interfaces \ | |
--filters Name=tag:Name,Values=$NAME_TAG \ | |
--query NetworkInterfaces[].NetworkInterfaceId \ | |
--output text) | |
# Attachment ID | |
ENI_ID=$($AWS_CMD ec2 describe-network-interfaces \ | |
--filters Name=tag:Name,Values=$NAME_TAG \ | |
--query NetworkInterfaces[].NetworkInterfaceId \ | |
--output text) | |
# Get Active Instance ID for Interface | |
ENI_ATTACHMENT_ID=$($AWS_CMD ec2 describe-network-interfaces \ | |
--filters Name=tag:Name,Values=$NAME_TAG \ | |
--query NetworkInterfaces[].Attachment[].AttachmentId \ | |
--output text) | |
# Deattach ENI assuming that it was attach to old instance | |
# in autoscaling group | |
if [[ $ENI_ATTACH_INSTANCE_ID != $INSTANCE_ID ]] | |
then | |
$AWS_CMD ec2 detach-network-interface \ | |
--attachment-id $ENI_ATTACHMENT_ID \ | |
--force | |
fi | |
# Attach ENI | |
$AWS_CMD ec2 attach-network-interface \ | |
--instance-id $INSTANCE_ID \ | |
--network-interface-id $ENI_ID |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment