Showing posts with label Instance. Show all posts
Showing posts with label Instance. Show all posts

Wednesday, October 12, 2016

Powershell Script to Remove Tags for ASG and associated instances - AWS Cloud

<#  
.SYNOPSIS  
Script to Remove Tags for ASG and associated instances by reading the ASG's from file

.FILE NAME
RemoveTags.ps1
#>

clear

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

$Asg_FilePath = $scriptDir + "\ASG.txt"

$AutoScalingGroups = Get-Content $Asg_FilePath

foreach($AutoScalingGroup in $AutoScalingGroups)
{
    $Tag = New-Object Amazon.AutoScaling.Model.Tag
    $Tag.ResourceId = $AutoScalingGroup
    $Tag.ResourceType = "auto-scaling-group"
    $Tag.Key = "{Specify the Tag Key}"
    Remove-ASTag -Tag $Tag -Force
    "Removed Tag for ASG " + $AutoScalingGroup

    $Instances = (Get-ASAutoScalingGroup -AutoScalingGroupName $AutoScalingGroup).Instances
    foreach ($Instance in $Instances)
    {
        $tag = New-Object Amazon.EC2.Model.Tag
        $tag.Key = "{Specify the Tag Key}"
        Remove-EC2Tag -Resource $Instance.InstanceId -tag $tag -Force
        "Removed Tag for Instance " + $Instance.InstanceId
    }
}

Powershell Script to retrieve Instance Details under AWS Account - AWS Cloud

<#  
.SYNOPSIS  
Script to retrieve Instance Details under AWS Account

This script will also gather last 24hrs Average CPU Value using the function getStats


.FILE NAME

Instance.ps1
#>

clear

Set-ExecutionPolicy Unrestricted
Set-DefaultAWSRegion -Region {Specify the region}
Set-AWSCredentials –AccessKey {Specify the Access Key} –SecretKey {Specify the Secret Key}
Import-Module 'C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1'; Initialize-AWSDefaults

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

try
{
    $Environment = "PROD"
            
    $Insts = ((Get-EC2Instance -Region {Specify the region}).RunningInstance | Where-Object -FilterScript {
                                    $_.Tags | Where-Object {
                                        ($_.Key -eq "Environment" -and $_.Value -eq $Environment )
                                    }
                                })
           
    $Instances = $Insts | Where-Object {$_.State.Name.Value -eq "Running"}
    
    $Ins = @{Expression={$_.InstanceId};Label="Instance ID"}, `
    @{Expression={$_.Tags | ? { $_.key -eq "Name" } | select -expand Value};Label="Instance Name"},
    @{Expression={$_.PrivateIpAddress};Label="Private IP"},
    @{Expression={$_.Tags | ? { $_.key -eq "Environment" } | select -expand Value};Label="Environment"},
    @{Expression={$_.Architecture};Label="Architecture"},
    @{Expression={$_.Tags | ? { $_.key -eq "Component" } | select -expand Value};Label="Component"},
    @{Expression={$_.Platform};Label="Platform"},
    @{Expression={(Get-EC2InstanceStatus -InstanceId $_.InstanceId).AvailabilityZone};Label="AvailZone"},
    @{Expression={getStats($_.InstanceId)};Label="Avg Cpu (last 24hrs)"}
        
    $Instances | Format-Table -AutoSize $Ins
}

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

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

    Exit 1
}

Function getStats($InstID)
{

    $Stats = Get-CWMetricStatistics -MetricName CPUUtilization -Dimension @{Name = "InstanceId"; Value = $InstID} -StartTime (Get-Date).AddDays(-1) -EndTime (Get-Date) -Namespace "AWS/EC2" -Period 12000 -Statistic Average | Select-Object -ExpandProperty DataPoints
    $aveCpu = $Stats | sort TimeStamp | select -ExpandProperty Average | measure -Average | select -ExpandProperty Average
    
    return $aveCpu
}

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
}