If you use AWS Elastic Load Balancers in front of your EC2 instances, you know that sometimes EC2 ELBs can take forever to recognize that the instance has come back up. This can happen long after the load balancer starts getting HTTP 200 responses to the health check you have specified for the ELB. I usually see this behavior after I have shut an instance down for a couple of hours for maintenance or for instances that require ELBs but which aren’t run all the time.
My solution to this is (surprise!) a PowerShell script, below, using Remove-ELBInstanceFromLoadBalancer
followed by Register-ELBInstanceWithLoadBalancer
. Both calls are using a “Name” tag associated with the EC2 instance so that it isn’t necessary to feed the PowerShell script the actual EC2 instance ID.
One odd thing I’ve noticed about using Register-ELBInstanceWithLoadBalancer
is that it seems to return in $AWSHistory
all the instances registered to that ELB, not just the one that was just enabled. Still, this code works well for me…and I hope for you, too.
<# De-register an EC2 instance from an AWS ELB using a tag (in this case, a tag labelled "Name", then re-register that instance. Copyright 2015 Air11 Technology LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> $hashTable = @{"ec2-instance-1" = "ec2-elb-1"; # key = instance name; item = ELB "ec2-instance-2" = "ec2-elb-1"; "ec2-instance-3" = "ec2-elb-1"; "ec2-instance-4" = "ec2-elb-2"; "ec2-instance-5" = "ec2-elb-2"; "ec2-instance-6" = "ec2-elb-2"; } foreach ($hashKey in $hashTable.Keys) { $elbInstanceObj = New-Object Amazon.ElasticLoadBalancing.Model.Instance $instance = Get-EC2Instance -Filter @{name='tag:Name'; values= "${hashKey}" } | Select -ExpandProperty instances #Get instance object $elbInstanceObj.InstanceId = $instance.InstanceId Remove-ELBInstanceFromLoadBalancer -LoadBalancerName "$($hashTable.Item($hashKey))" -Instances $elbInstanceObj -Force # Deregister instance Register-ELBInstanceWithLoadBalancer -LoadBalancerName "$($hashTable.Item($hashKey))" -Instances $elbInstanceObj # Reregister instance to reset health check }
Leave a Reply