Showing posts with label AWS Cloud. Show all posts
Showing posts with label AWS Cloud. Show all posts

Tuesday, December 6, 2016

Setting Profiles for AWS Credentials in PowerShell

Following procedure descibes setting up Profiles in PowerShell for AWS Credentials/Accounts:

 
A) Obtain the AWS keys (-AccessKey and -SecretKey) from AWS IAM User Accounts

B) Run the following commands to store these keys

:> Set-AWSCredentials –AccessKey <AccessKey> –SecretKey <SecretKey> -StoredCredentials <profileName>

Repeat the above command for multiple profiles

C) Discard the current powershell and start a new one. To load the credentials into the new shell, run the same cmdlet, but this time pass the profile name you specified as the -StoredCredentials parameter:

:> Set-AWSCredentials -StoredCredentials <profileName>

D) Make Profiles added to PS Session

Right-click Windows PowerShell, and then click Run as administrator.

  1. At the Windows PowerShell prompt, type the following command, and then press ENTER:
    :> Test-path $profile
    If the results of the this command are false, go to step 2.
    If the results are true, go to step 3.
  2. Type the following command, and then press ENTER.
    :> New-item –type file –force $profile
  3. Type the following command, and then press ENTER.
    :> Notepad $profile
  4. Add the following lines, save and exit:
    Set-AWSCredentials -StoredCredentials <Profile-1>
    Set-AWSCredentials -StoredCredentials <Profile-2>
    Set-DefaultAWSRegion <Region Name>
  5. Discard the current powershell and start a new one.
    :> Get-AWSCredentials -ListProfiles

E)  Local file of profiles are stored in - C:\Users\%username%\AppData\Local\AWSToolkit\RegisteredAccounts.json.
In case they get corrupted for some reason, rename the file and add the keys.

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
}

Powershell Script to add Notification for all ASGs - AWS Cloud

<#  
.SYNOPSIS  
Script to add Notification for all ASGs

FILE NAME

AddNotifASG.ps1
#>

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$CommonFilePath = $scriptDir + "\AWSCredentials.ps1"
. $CommonFilePath


$Environment = "PROD"

$AutoScalingGroupName=""

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

    foreach($AutoScalingGroup in $AutoScalingGroups)
    {
        $AutoScalingGroupName = $AutoScalingGroup.AutoScalingGroupName
        Write-ASNotificationConfiguration -AutoScalingGroupName $AutoScalingGroupName -NotificationType @("autoscaling:EC2_INSTANCE_LAUNCH", "autoscaling:EC2_INSTANCE_TERMINATE") -TopicARN "{Specify the ARN Value here}"
    }

}

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

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

    Exit 1
}

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
}