Wednesday, October 12, 2016

Powershell Script to retrieve Instances Status under ELB associated with ASG - AWS Cloud

<#  
.SYNOPSIS  
Script to retrieve Instances and their status under ELB aligned to ASG. Import the credentials file in the same script

.FILE NAME

LBChecks.ps1
#>

clear

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

$CommonFilePath = $scriptDir + "\AWSCredentials.ps1"
. $CommonFilePath

$file = $scriptDir + "\" + "Details-" + (Get-Date).tostring("dd-MM-yyyy-HH-mm-ss") + ".txt"

try
{
    $Environment = "PROD"
    
    $AutoScalingGroups = (Get-ASAutoScalingGroup | Where-Object -FilterScript {
                        $_.Tags | Where-Object {
                                ($_.Key -eq "Environment" -and $_.Value -eq $Environment)
                                }
                            }) 

    foreach($AutoScalingGroup in $AutoScalingGroups)
    {

        $ELBs = $AutoScalingGroup.LoadBalancerNames

        foreach ($elb in $ELBs)
        {
            $LBDetails = Get-ELBLoadBalancer -LoadBalancerName $elb
            foreach($Instance in $LBDetails.Instances)
            {
                $InstanceHealth = Get-ELBInstanceHealth -LoadBalancerName $elb -Instance $Instance
                $InstAvailZ = (Get-EC2InstanceStatus -InstanceId $Instance.InstanceId).AvailabilityZone
                
                if($InstanceHealth.State -eq "OutOfService")
                    { 
                     $Message = $AutoScalingGroup.AutoScalingGroupName + " || " + $Instance.InstanceId + " || " + $elb + " || " + $InstAvailZ + " || state is " + $InstanceHealth.State
                     Write-Host $Message -ForegroundColor Red
                    }
                else 
                    {
                    $Message = $AutoScalingGroup.AutoScalingGroupName + " || " + $Instance.InstanceId + " || " + $elb + " || " + $InstAvailZ + " || state is " + $InstanceHealth.State
                    Write-Host $Message -ForegroundColor Green
                    $Message >> $file
                    }
            }
        }

    }
}

catch 
{
$originalException = $_.Exception 
try
{
"Error: " + $originalException.Message
}
catch

"Original Error: " + $originalException.Message 
"Logging Error:" + $_.Exception.Message
}

    Exit 1
}

No comments:

Post a Comment