AWS - Change EC2 Instance State

Octopus.Script exported 2018-01-30 by tclydesdale belongs to ‘AWS’ category.

This step can Start, Stop or Terminate an EC2 instance.

Works well with the “AWS - Launch EC2 Instance” Community Step Template.

AWS Tools for Windows PowerShell must be installed on the Server/Target you plan on running this step template on.

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

Instance ID

odInstanceId = i-xxxxxxxxxxxxxxxxx

The EC2 Instance ID of the Instance you would like to add Tags to.

Instance State

odState = running

The State you would like the specified EC2 Instance to be in. For example “Running” (ie Start EC2 Instance).

Access Key (Kind-of Optional)

odAccessKey =

An Access Key with permissions to create the desired EC2 instance. Note: If empty, this step will attempt to use the value contained in the Machine Environment Variable “AWS_ACCESS_KEY”.

Further Reading: https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html

Secret Key (Kind-of Optional)

odSecretKey =

The Secret Key associated with the above Access Key. Note: If empty, this step will attempt to use the value contained in the Machine Environment Variable “AWS_SECRET_KEY”.

Further Reading: https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html

Script body

Steps based on this template will execute the following PowerShell script.

# Running outside octopus
param(
    [string]$odInstanceId,
    [string]$odState,
    [string]$odAccessKey,
    [string]$odSecretKey,
    [switch]$whatIf
) 

$ErrorActionPreference = "Stop" 

function Get-Param($Name, [switch]$Required, $Default) {
    $result = $null

    if ($OctopusParameters -ne $null) {
        $result = $OctopusParameters[$Name]
    }

    if ($result -eq $null) {
        $variable = Get-Variable $Name -EA SilentlyContinue   
        if ($variable -ne $null) {
            $result = $variable.Value
        }
    }

    if (!$result -or $result -eq $null) {
        if ($Default) {
            $result = $Default
        } elseif ($Required) {
            throw "Missing parameter value $Name"
        }
    }

    return $result
}


& {
    param(
        [string]$odInstanceId,
        [string]$odState,
        [string]$odAccessKey,
        [string]$odSecretKey
    )
    
    # If AWS key's are not provided as params, attempt to retrieve them from Environment Variables
    if ($odAccessKey -or $odSecretKey) {
        Set-AWSCredentials -AccessKey $odAccessKey -SecretKey $odSecretKey -StoreAs default
    } elseif (([Environment]::GetEnvironmentVariable("AWS_ACCESS_KEY", "Machine")) -or ([Environment]::GetEnvironmentVariable("AWS_SECRET_KEY", "Machine"))) {
        Set-AWSCredentials -AccessKey ([Environment]::GetEnvironmentVariable("AWS_ACCESS_KEY", "Machine")) -SecretKey ([Environment]::GetEnvironmentVariable("AWS_SECRET_KEY", "Machine")) -StoreAs default
    } else {
        throw "AWS API credentials were not available/provided."
    }

    if ($odInstanceId) {
        $instanceObj = (Get-EC2Instance $odInstanceId | select -ExpandProperty Instances)
        $instanceCount = ($instanceObj | measure).Count

        if ($instanceCount -eq 1) {
            $instanceId = ($instanceObj).InstanceId
            
            Write-Output ("------------------------------")
            Write-Output ("Checking/Setting the EC2 Instance state:")
            Write-Output ("------------------------------")
            
            $currentState = (Get-EC2Instance $instanceId).Instances.State.Name

            if ($odState -eq "running" -and $currentState -ne "running") {
                $changeInstanceStateObj = (Start-EC2Instance -InstanceId $instanceId)
            }
            elseif ($odState -eq "absent" -and $currentState -ne "terminated") {
                $changeInstanceStateObj = (Remove-EC2Instance -InstanceId $instanceId -Force)
            }
            elseif ($odState -eq "stopped" -and $currentState -ne "stopped") {
                $changeInstanceStateObj = (Stop-EC2Instance -InstanceId $instanceId)
            }

            $timeout = new-timespan -Seconds 120
            $sw = [diagnostics.stopwatch]::StartNew()

            while ($true) {
                $currentState = (Get-EC2Instance $instanceId).Instances.State.Name

                if ($currentState -eq "running" -and $odState -eq "running") {
                    break
                }
                elseif ($currentState -eq "terminated" -and $odState -eq "absent") {
                    break
                }
                elseif ($currentState -eq "stopped" -and $odState -eq "stopped") {
                    break
                }

                Write-Output ("$(Get-Date) | Waiting for Instance '$instanceId' to transition from state: $currentState")

                if ($sw.elapsed -gt $timeout) { throw "Timed out waiting for desired state" }

                Sleep -Seconds 5
            }
 
            Write-Output ("------------------------------")
            Write-Output ("$(Get-Date) | $($instanceId) state: $currentState")
            Write-Output ("------------------------------")
        }
        else
        {
            Write-Output ("Instance '$instanceId' could not be found...?")
        }
    }
 } `
 (Get-Param 'odInstanceId' -Required) `
 (Get-Param 'odState' -Required) `
 (Get-Param 'odAccessKey') `
 (Get-Param 'odSecretKey')

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "302a1282-c139-4e0f-9076-cd4b16d8b795",
  "Name": "AWS - Change EC2 Instance State",
  "Description": "This step can Start, Stop or Terminate an EC2 instance.\n\nWorks well with the \"_AWS - Launch EC2 Instance_\" Community Step Template.\n\n[AWS Tools for Windows PowerShell](http://aws.amazon.com/powershell/) must be installed on the Server/Target you plan on running this step template on.",
  "Version": 1,
  "ExportedAt": "2018-01-30T13:25:57.198Z",
  "ActionType": "Octopus.Script",
  "Author": "tclydesdale",
  "Parameters": [
    {
      "Id": "3eec5a11-9095-40f6-bebb-71ccb94c73db",
      "Name": "odInstanceId",
      "Label": "Instance ID",
      "HelpText": "The EC2 Instance ID of the Instance you would like to add Tags to.",
      "DefaultValue": "i-xxxxxxxxxxxxxxxxx",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      },
      "Links": {}
    },
    {
      "Id": "94b68517-858c-4232-bd1a-c760a22750a1",
      "Name": "odState",
      "Label": "Instance State",
      "HelpText": "The State you would like the specified EC2 Instance to be in. For example \"Running\" (ie Start EC2 Instance).",
      "DefaultValue": "running",
      "DisplaySettings": {
        "Octopus.ControlType": "Select",
        "Octopus.SelectOptions": "running|Start EC2 Instance\nstopped|Stop EC2 Instance\nabsent|Terminate EC2 Instance"
      },
      "Links": {}
    },
    {
      "Id": "e1c98924-6f3b-45fe-a4b8-16329a9a50ea",
      "Name": "odAccessKey",
      "Label": "Access Key (Kind-of Optional)",
      "HelpText": "An Access Key with permissions to create the desired EC2 instance.\nNote: If empty, this step will attempt to use the value contained in the Machine Environment Variable \"AWS\\_ACCESS\\_KEY\".\n\nFurther Reading:\n[https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html](https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html)",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      },
      "Links": {}
    },
    {
      "Id": "45557d48-5f1a-4523-9f42-f4a53571d0ce",
      "Name": "odSecretKey",
      "Label": "Secret Key (Kind-of Optional)",
      "HelpText": "The Secret Key associated with the above Access Key.\nNote: If empty, this step will attempt to use the value contained in the Machine Environment Variable \"AWS\\_SECRET\\_KEY\".\n\nFurther Reading:\n[https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html](https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html)",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      },
      "Links": {}
    }
  ],
  "Properties": {
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptSource": "Inline",
    "Octopus.Action.RunOnServer": "false",
    "Octopus.Action.Script.ScriptBody": "# Running outside octopus\nparam(\n    [string]$odInstanceId,\n    [string]$odState,\n    [string]$odAccessKey,\n    [string]$odSecretKey,\n    [switch]$whatIf\n) \n\n$ErrorActionPreference = \"Stop\" \n\nfunction Get-Param($Name, [switch]$Required, $Default) {\n    $result = $null\n\n    if ($OctopusParameters -ne $null) {\n        $result = $OctopusParameters[$Name]\n    }\n\n    if ($result -eq $null) {\n        $variable = Get-Variable $Name -EA SilentlyContinue   \n        if ($variable -ne $null) {\n            $result = $variable.Value\n        }\n    }\n\n    if (!$result -or $result -eq $null) {\n        if ($Default) {\n            $result = $Default\n        } elseif ($Required) {\n            throw \"Missing parameter value $Name\"\n        }\n    }\n\n    return $result\n}\n\n\n& {\n    param(\n        [string]$odInstanceId,\n        [string]$odState,\n        [string]$odAccessKey,\n        [string]$odSecretKey\n    )\n    \n    # If AWS key's are not provided as params, attempt to retrieve them from Environment Variables\n    if ($odAccessKey -or $odSecretKey) {\n        Set-AWSCredentials -AccessKey $odAccessKey -SecretKey $odSecretKey -StoreAs default\n    } elseif (([Environment]::GetEnvironmentVariable(\"AWS_ACCESS_KEY\", \"Machine\")) -or ([Environment]::GetEnvironmentVariable(\"AWS_SECRET_KEY\", \"Machine\"))) {\n        Set-AWSCredentials -AccessKey ([Environment]::GetEnvironmentVariable(\"AWS_ACCESS_KEY\", \"Machine\")) -SecretKey ([Environment]::GetEnvironmentVariable(\"AWS_SECRET_KEY\", \"Machine\")) -StoreAs default\n    } else {\n        throw \"AWS API credentials were not available/provided.\"\n    }\n\n    if ($odInstanceId) {\n        $instanceObj = (Get-EC2Instance $odInstanceId | select -ExpandProperty Instances)\n        $instanceCount = ($instanceObj | measure).Count\n\n        if ($instanceCount -eq 1) {\n            $instanceId = ($instanceObj).InstanceId\n            \n            Write-Output (\"------------------------------\")\n            Write-Output (\"Checking/Setting the EC2 Instance state:\")\n            Write-Output (\"------------------------------\")\n            \n            $currentState = (Get-EC2Instance $instanceId).Instances.State.Name\n\n            if ($odState -eq \"running\" -and $currentState -ne \"running\") {\n                $changeInstanceStateObj = (Start-EC2Instance -InstanceId $instanceId)\n            }\n            elseif ($odState -eq \"absent\" -and $currentState -ne \"terminated\") {\n                $changeInstanceStateObj = (Remove-EC2Instance -InstanceId $instanceId -Force)\n            }\n            elseif ($odState -eq \"stopped\" -and $currentState -ne \"stopped\") {\n                $changeInstanceStateObj = (Stop-EC2Instance -InstanceId $instanceId)\n            }\n\n            $timeout = new-timespan -Seconds 120\n            $sw = [diagnostics.stopwatch]::StartNew()\n\n            while ($true) {\n                $currentState = (Get-EC2Instance $instanceId).Instances.State.Name\n\n                if ($currentState -eq \"running\" -and $odState -eq \"running\") {\n                    break\n                }\n                elseif ($currentState -eq \"terminated\" -and $odState -eq \"absent\") {\n                    break\n                }\n                elseif ($currentState -eq \"stopped\" -and $odState -eq \"stopped\") {\n                    break\n                }\n\n                Write-Output (\"$(Get-Date) | Waiting for Instance '$instanceId' to transition from state: $currentState\")\n\n                if ($sw.elapsed -gt $timeout) { throw \"Timed out waiting for desired state\" }\n\n                Sleep -Seconds 5\n            }\n \n            Write-Output (\"------------------------------\")\n            Write-Output (\"$(Get-Date) | $($instanceId) state: $currentState\")\n            Write-Output (\"------------------------------\")\n        }\n        else\n        {\n            Write-Output (\"Instance '$instanceId' could not be found...?\")\n        }\n    }\n } `\n (Get-Param 'odInstanceId' -Required) `\n (Get-Param 'odState' -Required) `\n (Get-Param 'odAccessKey') `\n (Get-Param 'odSecretKey')"
  },
  "Category": "AWS",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/aws-change-ec2-instance-state.json",
  "Website": "/step-templates/302a1282-c139-4e0f-9076-cd4b16d8b795",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADNQTFRF////9o0R/eLD/Nu0/erS95Qg+bhr95sv/vHh+r96/vjw+bFc/NSl+KI++82W+saI+KpNeDqM1wAAA41JREFUeNrsnG2XazAURiuo0Cr//9feliIvR3DvXJFZe3+a6XpW5+xWEpyY2w0AAAAAAAAAAAAAAAAAAADgf1J0bda/9N70q83a3enzUHWVjbR1sW0xp6sd6fPI72VmUt3zA+kymD6N5vnIBMrHsxHTjsUXOX0e+iVaTNU5Q0A/Q+k+4oAp+ixMbw6A4rGVVjGHR92ulNXWuTAlBNJN/FFyr5yy3qN9rawmF9IxR4hqX4U1WMplmGtruVBDuiuswbKkzaGhX+cfXsqbZlXXv0dsYR13nw9fLenGXD7f6U5Ony4yTpzyZLNMUcpMr0xNzfwdRRMR1/LP2cqMctNqKx1LZFydm2U022ueEtLL6HbHfmSRYRn4HDXaXyzU4XRkkZWK/+JlRBBBBBFEEEEEEUQQQQQRRBBB5B9uYJc7SyuLw+nI7R2ptKWJcywd18Utza0rnM4iN66M6qzS5E93Lf1zLaviUL/ISs/Nt6W00DEyuRgiP2Yxvrd15z/Y26ncG76jy1Ta5jEy/L0p/VMWy33woVm8UYN1Y9fqKrzfZ5iedtaV34+kNxHak2Wg2SSkY7djx/bQWkNP6nkE0lH3Lyx7D1aak1Z1erWJ+U130Vz0Sude7mZqv995nW7mZxJd27Sg5XQppuMdWY3xl1XXOge8MasWjZfund0KbvrkE9fK7OPNne+2U9YEWX3nemtSbvLv6LJ7gZ9X45yBl9ZxrZ9d3vjT8rz62tOsny7jXkpYPX9jQmvF8yF55TdaslGviZy1vAmfoTobsZztGNEv7qZZSr/6HRc/0yzlb3HiKhURRBBBBBFEEEEEEUQQQQQRRBD5XSLav38tllbVzeH02Ww/UWA+6XgsHdXFKc2vK5Quoz/duVRnlrb26crpizzXOVU3l2Zb5Pfe+d1OX8ViqW7qH9gt51K44bukr2XxrW54vMaoy7mxa/cgvPRVKcQG7uOCD58HLQLt3r17Iy6AqjYeDG7TUenWW+p9Ot/IOF/lwuHV1nk6o8M469PWXhtr+0BeX/x7Ue40W3xacfb2gXFxUZcX8TYB3Kyfp+GThsjKti2zgZuMiLshxW3gpiQyrn/DXhR/i1NqIte5pkUEEUQQQQQRRBBBBBFEEEEEEUR+g4jQUZBEqjqFO9mOiyeShoXvYoukZOG4GCLpWZgu83/vTNRidhlE0rYAAAAAAAAAAAAAAAAAAACAZPkjwAAMDi+bsnPP/wAAAABJRU5ErkJggg==",
  "$Meta": {
    "Type": "ActionTemplate"
  }
}

History

Page updated on Tuesday, January 30, 2018