Tuesday, January 23, 2018

Starting and stopping AWS instances via Powershell

On my long-overdue return to this blog, here's a script I wrote recently to solve my usually long process to start a full environment, do some work on it, then stop it.


I regularly have to run POCs or tests, on somewhat complex environments involving 10+ machines. Since I am a cost-conscious person, I will normally start the environment, do my testing/work, and then stop it at the end. All good with this, except that:

  1. Logging in to AWS console, switching profiles, switching zones takes a good 2-3 minutes
  2. Finding the the instances I need, starting them, takes another 30 seconds
  3. Updating all links to my test instances in Remote Desktop Manager (which I use) takes another good 5 minutes (remember we're talking 10 instances).
So I decided I should automate this process, given that's what APIs are for.

The script below will:
  • Find all instances that use a given AWS Security Group
  • Start all those instances
  • Modify my Remote Desktop Manager xml file that contains the links to the VMs
As usual... the code is written in a very "results oriented way"... some code purists may be annoyed with my lack of code consistency.

Hope this helps anyone out there.

I promise I'll figure out code highlighting on this blog another day.
# Get list of instances 

# Important Variables
$groupName = "NHS-ALL-LOCAL" #Name of security group to search for in instances
$rdgFilePath = "C:\Users\Nuno\OneDrive\Documents\NHS.rdg" #Path to RD Manager group file with links to Machines/RDP
$instanceStartWaitTime = 20 # Time in seconds to wait for EC2 instances to start

function GetName($instance) {
    foreach ($tag in $instance.Tags) {
        if ($tag.Key -eq "Name")
        {return $tag.Value}
        return $null

function GetAllInstances() {
    $allAWSInstances = aws ec2 describe-instances | ConvertFrom-Json
    $instances = @{}
    foreach ($instance in $allAWSInstances.Reservations.Instances) {
        foreach ($group in $instance.SecurityGroups) {
            if ($group.GroupName -eq $groupName) {
                $nameTag = GetName($instance)
                $instances.Add($nameTag, $instance)
    return $instances

function GetInstanceIds($instances) {
    $listInstances = @()
    foreach ($instance in $instances.GetEnumerator()) {
        $listInstances += $instance.Value.InstanceId
    return $listInstances
$instances = GetAllInstances 
Write-Host "Found the following Instances:"
foreach ($instance in $instances.GetEnumerator()) {
    Write-Host $instance.Name " - " $instance.Value.InstanceId

# Start all instances
$list = GetInstanceIds($instances)

Write-Host "Starting all instances with security group $groupName..."
aws ec2 start-instances --instance-ids $list
Write-Host "Waiting $instanceStartWaitTime seconds"
for($i=1; $i -le $instanceStartWaitTime; $i++)
    $timeRemaining = $instanceStartWaitTime - $i
    Write-Progress -Activity "Waiting $timeRemaining seconds" -PercentComplete (($i/$instanceStartWaitTime)*100)
    Start-Sleep -Seconds 1
$instances = GetAllInstances

# Should be updated now.
foreach ($instance in $instances.GetEnumerator()) {
    Write-Host $instance.Value.InstanceId is now $instance.Value.State.Name

# Modify C:\Users\Nuno\OneDrive\Documents\NHS.rdg to place all the right URLs
[xml]$rdg = Get-Content -Path $rdgFilePath

foreach ($instance in $instances.GetEnumerator()) {
    $instanceName = $instance.Key
    $publicUrl = $instance.Value.PublicDnsName
    foreach ($server in $rdg.RDCMan.file.server.properties) {
        if ($server.displayName -eq $instanceName) {
            Write-Host "Updating Node: $instanceName with Url $publicUrl"
            $server.name = $publicUrl


Alvin Reyes said...

Welcome back. :-)

Sneha rathod said...

Thanks for providing your information, keep update AWS Online Training Bangalore

Buna Treks & Expedition Pvt. Ltd. said...

Why Trekking in Nepal Nepal?, a land of high hills, mountains, raging rivers and verdant deep jungles of Terai & its rich lifestyle makes one of the most sought locations inside the map of the world. a destination for all season as it's miles one of the most numerous and varied international locations on this planet a unique us of a nestled inside the excellent snow capped variety is some other advent of the mom earth and it embraces worlds' 8 highest peaks from mt.everest, mt.kanchenjonga, mt.lhotse, Makalu, Cho Oyu, Dhaulagiri, Manaslu to Annapurna massive. nepal is likewise the beginning location of Buddha (light of Asia). The Buna Treks is Local Base Under Nepal Government Trekking Agency in Nepal. blessed with wealthy nature, the brilliant Himalayan in Nepal range stretches from the far north-west to the way east where the worlds highest 8th eight-thousanders are in Nepal. nepal gives a enthralling adventure with enough time to wonder the encompassing beautiful landscapes and immerse with its warm human beings, imparting you full of range and enchantment from the low lands of Gangetic plains and its verdant dense jungle where the endangered species of Royal Bengal tigers and the one-horned rhinoceros roam, to the mythical yak and yeti trail to Everest.as the adventure and leisure tourism was hooked up in view that late 1960 and 70’s quality travel & trekking enterprise have mushroomed by using a tourism professionals Nepalese, and were leading countless of adventure trips in the course of Himalaya consisting of rafting, mountain climbing also organize adventure trekking, and entertainment trips which includes tailor-made itineraries for own family, college companies and company executives. Many of Trekking Company in Nepal are not perfect trip dealing, they have not enough Experienced. Trekking in Nepal, Nepal is domestic to community of trails also known as the amazing Himalaya trails, an extensive trail gadget that covers Nepal from humble and Darchula within the west to Kanchenjunga in the east. the range of Trekking in Nepal cannot be located in any other location of the world. in fact, the lowest factor in Nepal is fifty-nine m above sea-level inside the terai location even as the very best point is Everest, eight,848 m above sea-level, the two factors are, in a direct line, most effective two hundred kilometers aside. the majority of visitors to Nepal are available through the Tribhuvan international airport in Kathmandu. it's far in Kathmandu that trekkers want to accumulate their permits and other documentation, both from a trekking agent or from the best places of work. those files will be checked along the hiking route. for people with little time to spend in Nepal, there are half of-day hikes from Kathmandu to witness breathtaking Himalayan Trekking in Nepal perspectives in any other case trek for weeks over stunning tough mountain passes. as much as the mid-1960s just a few trekkers had generally visited Nepal and lower back then as part of corporations of excursion fans. the various huge expeditions of the day recommended trekkers to join up in an try to help balance the investment.