Wednesday, October 12, 2016

Powershell Script to Amend ASG values - AWS Cloud

<#  
.SYNOPSIS  
Amend ASG for updating & reverting Values. ASGs will be read through file

.FILE NAME
SetASGtoZero.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

$Asg_LCGFilePath = $scriptDir + "\ASG.txt"
$logOrigPath = $scriptDir + "\" + "Log_Orig.txt"
$logFilePath = $scriptDir + "\" + "Log.txt"

try
{
    $AutoScalingGroups = Get-Content $Asg_LCGFilePath

    foreach($AutoScalingGroup in $AutoScalingGroups)
    {
        $AutoScalingGroupDetails = Get-ASAutoScalingGroup -AutoScalingGroupName $AutoScalingGroup 
        $AutoScalingGroup + "#" + $AutoScalingGroupDetails.MinSize + "#" + $AutoScalingGroupDetails.DesiredCapacity >> $logOrigPath
        Update-ASAutoScalingGroup -AutoScalingGroupName $AutoScalingGroup -MinSize 0 -DesiredCapacity 0
    }
}

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

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

    Exit 1
}

<#  
.SYNOPSIS  
Amend ASG for updating & reverting Values. ASGs will be read through file

.FILE NAME
RevertASG.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

$logOrigPath = $scriptDir + "\" + "Log_Orig.txt"
$logZeroPath = $scriptDir + "\" + "Log_Zero.txt"
$logFilePath = $scriptDir + "\" + "Log.txt"

try
{
    $OriginalASGValues = Get-Content $logOrigPath

    foreach($OriginalASGVal in $OriginalASGValues)
    {
        $AutoScalingGroupName = $OriginalASGVal.Split("#")[0]
        $MinVal = $OriginalASGVal.Split("#")[1]
        $DesVal = $OriginalASGVal.Split("#")[2]
        "Values are:" + $AutoScalingGroupName + " " + $MinVal + " " + $DesVal >> $logZeroPath
        Update-ASAutoScalingGroup -AutoScalingGroupName $AutoScalingGroupName -MinSize $MinVal -DesiredCapacity $DesVal >> $logZeroPath
    }
}

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

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

    Exit 1
}

No comments:

Post a Comment