Search code examples
amazon-web-servicespowershelldo-while

infinite loop for checking aws instance status in ec2 targetgroup while draining


I am trying to capture the status of an ec2 instance which is part of a target group. I try to de-register the instance and then inside a do until look I constantly check for the status of the instance when it migrates from draining to unused and then exit out of the loop at that point. I am unable to figure out why it is getting into an infinite loop even though I constantly check for the status. Here is the power-shell snippet I am using

       $instance_id = "i-ec2ID"
       $targetGroupArn = "arn:aws:elasticloadbalancing:region:accountID:targetgroup/tg-name/guid12345"
       aws elbv2 deregister-targets --target-group-arn $targetGroupArn --targets Id=$instance_id
       
       Do {
            
            $instance_status = aws elbv2 describe-target-health --target-group-arn $targetGroupArn --query "TargetHealthDescriptions[].{Id:Target.Id,Health:TargetHealth.State}" --output text|Select-String -Pattern $instance_id
            $a = $instance_status.ToString()
            $instance_state = $a.Substring(0, $a.Length - 20)
            echo "Instance is still: "$instance_state
            Start-Sleep -s 10
        }
        Until ($instance_state -match "unused") 

Any suggestion on how to overcome this issue or any better suggestion to achieve what I am trying to do is welcome


Solution

  • I figured out the issue and was able to resolve it by putting an if-else block inside the do until loop which will basically evaluate the status if it is null and exit out of the loop gracefully

       Do {
            
            $instance_status = aws elbv2 describe-target-health --target-group-arn $targetGroupArn --query "TargetHealthDescriptions[].{Id:Target.Id,Health:TargetHealth.State}" --output text|Select-String -Pattern $instance_id
            if($instance_status -eq $null) {
                $instance_state = $null
            }
            else{
                $a = $instance_status.ToString()
                $instance_state = $a.Substring(0, $a.Length - 20)
                echo "Instance is still: "$instance_state
                Start-Sleep -s 10
            }
    
        }
        Until ($instance_state -eq $null)
    

    Hopefully this helps someone