Start/Stop EC2 instances by Tags using PowerShell

In most cases, organizations will be running their AWS instances 24-hours a day, 7 days a week. You can reduce your costs significantly by scheduling non-production EC2  instances to shutdown when they are not required.

  • Start and Shutdown EC2 instances to run during business hours
  • Stop all non-production EC2 instances at evenings and weekends

Lambda function below can be scheduled to stop the instances and save costs

#Ge AWS credentials from metadata
$proxy = "x.x.x.x"
$webClient = new-object System.Net.WebClient
$proxy = new-object System.Net.WebProxy $proxyServerToDefine,"True","169.*"
$webclient.proxy=$proxy
$iam = $webClient.DownloadString("http://169.254.169.254/latest/meta-data/iam/security-credentials")
$iamProfileInfo= ConvertFrom-Json ($webClient.DownloadString("http://169.254.169.254/latest/meta-data/iam/security-credentials/$iam"))
Set-AWSCredentials -AccessKey $iamProfileInfo.AccessKeyId -SecretKey $iamProfileInfo.SecretAccessKey -SessionToken $iamProfileInfo.Token
#This is to get all the instanced with a tag name Environment with value DEV
$instances = (Get-EC2Tag | where {$_.Key -eq "Environment" -and $_.ResourceType -eq "instance" -and $_.Value -eq "DEV"}).ResourceId
foreach ($instance in $instances)
{
$instancestatus = Get-EC2InstanceStatus -InstanceIds $instance
$InstanceName = (Get-EC2Tag | where {$_.ResourceId -eq $instance -and $_.Key -eq "Name" }).Value
#Instance Value is NULL for all stopped instances on AWS using Powershell
if($instancestatus -eq $null)
{
Write-Host "(NO ACTION)" $InstanceName "is stopped"
}
else
{
Write-Host "Stopping Instance: " $InstanceName
Stop-EC2Instance -Instance $instance
}}

Leave a Reply

Your email address will not be published. Required fields are marked *