Collection<String> candidateEIPs = getCandidateEIPs(myInstanceId, myZone);
AmazonEC2 ec2Service = getEC2Service();
boolean isMyinstanceAssociatedWithEIP = false;
Address selectedEIP = null;
for (String eipEntry : candidateEIPs) {
try {
String associatedInstanceId;
// Check with AWS, if this EIP is already been used by another instance
DescribeAddressesRequest describeAddressRequest = new DescribeAddressesRequest().withPublicIps(eipEntry);
DescribeAddressesResult result = ec2Service.describeAddresses(describeAddressRequest);
if ((result.getAddresses() != null) && (!result.getAddresses().isEmpty())) {
Address eipAddress = result.getAddresses().get(0);
associatedInstanceId = eipAddress.getInstanceId();
// This EIP is not used by any other instance, hence mark it for selection if it is not
// already marked.
if (((associatedInstanceId == null) || (associatedInstanceId.isEmpty()))) {
if (selectedEIP == null) {
selectedEIP = eipAddress;