Running your own load balancers on AWS for external traffic is usually cheaper than using Amazon’s provided external balancers solutions. But there’s a catch. What if maintenance is needed to be done on load balancers virtual machines with downtime or services restarts?

We can use keepalived service that actually controls it’s virtual IPs as AWS Elastic IPs and assigns them on working machines to avoid downtimes. Here’s a shell script gist for keepalived to execute on state change:

#!/bin/bash

# parameter
INSTANCE_ID=$1

# variables
export AWS_ACCESS_KEY_ID=XXXXXXXXXXX
export AWS_SECRET_ACCESS_KEY=XXXXXXXXXXX
EIP1=eipalloc-XXXXXXXXXXX 	# EIP1 xx.xx.xx.xx
EIP2=eipalloc-XXXXXXXXXXX 	# EIP2 xx.xx.xx.xx
N1ETHID=eni-XXXXXXXXXXX	        # xx.xx.xx.xx / ec2-instance-1 eth1
N2ETHID=eni-XXXXXXXXXXX 	# xx.xx.xx.xx / ec2-instance-2 eth1
N1IP1=xx.xx.xx.xx		# ec2-instance-1
N1IP2=xx.xx.xx.xx		# ec2-instance-1
N2IP1=xx.xx.xx.xx 		# ec2-instance-2
N2IP2=xx.xx.xx.xx 		# ec2-instance-2
HOSTNAME=`hostname -s`

# if INSTANCE_ID=1 instance is master then set $N1ETHID and N1IP on ec2-instance-1; 
# if INSTANCE_ID=2 instance is master then set $N2ETHID nad N2IP on ec2-instance-2;
if [[ ${HOSTNAME} == "ec2-instance-1" ]]; then
    if [[ ${INSTANCE_ID} == "1" ]]; then
      IF=${N1ETHID}
      IP=${N1IP1}
      EIP=${EIP1}
    elif [[ ${INSTANCE_ID} == "2" ]]; then
      IF=${N1ETHID}
      IP=${N1IP2}
      EIP=${EIP2}
    fi
    # AWS CLI to Assign EIP to Master (self) host
    aws ec2 associate-address --region $region --allocation-id ${EIP} --private-ip-address ${IP} --network-interface-id ${IF} --allow-reassociation
fi

# if INSTANCE_ID=1 instance is master then set $N1ETHID and N1IP on ec2-instance-1; 
# if INSTANCE_ID=2 instance is master then set $N2ETHID nad N2IP on ec2-instance-2;
if [[ ${HOSTNAME} == "ec2-instance-2" ]]; then
    if [[ ${INSTANCE_ID} == "1" ]]; then
      IF=${N2ETHID}
      IP=${N2IP2}
      EIP=${EIP1}		
    elif [[ ${INSTANCE_ID} == "2" ]]; then
      IF=${N2ETHID}
      IP=${N2IP1}
      EIP=${EIP2}
    fi
    # AWS CLI to Assign EIP to Master (self) host
    aws ec2 associate-address --region $region --allocation-id ${EIP} --private-ip-address ${IP} --network-interface-id ${IF} --allow-reassociation
fi