Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start/Stop Instances in AWS and Wait with powershell

I understand that it is quite easy to start and stop instances through Powershell:

$awsCreds = Get-AWSAutomationCreds
Set-AWSCredentials -AccessKey $awsCreds.AccessKey -SecretKey $awsCreds.SecretKey
Set-DefaultAWSRegion -Region us-east-1

$instances = Get-EC2Instance -Filter @{name="tag:Name"; values="SERVERNAMES"} | Select -ExpandProperty Instances
$instances.InstanceId | foreach {Stop-EC2Instance $_ -ErrorAction SilentlyContinue}

Is there a quick and dirty way that I am just not seeing through the AWS Powershell Cmdlets or even the .NET SDK that would allow me to either wait until the action is complete. And/Or update the collection of instance objects I gathered?

Or am I stuck with running the:

$instances = Get-EC2Instance -Filter @{name="tag:Name"; values="SERVERNAMES"} | Select -ExpandProperty Instances

Command over and over until the state completely changes?

like image 223
Johnrad Avatar asked Dec 06 '25 13:12

Johnrad


1 Answers

Sam Martin has a PowerShell module in Github with some PowerShell helper functions for AWS that you can find here: https://github.com/Sam-Martin/AWSWindowsHelpers/

His approach to this problem can be seen in his Wait-AWSWindowsHelperInstanceToStop and Wait-AWSWindowsHelperInstanceReady cmdlets, and is (as you've already suggested) simply to run a loop with a start-sleep until the instance is in the state you expect. E.g:

While((Get-EC2Instance -InstanceId $InstanceID -Region $Region).Instances[0].State.Name -ne 'stopped'){
    Write-Verbose "Waiting for instance to stop"
    Start-Sleep -s 10
}
like image 194
Mark Wragg Avatar answered Dec 08 '25 14:12

Mark Wragg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!