Shutdown Single or Multiple AWS EC2 Instances

Exported on 31-Aug-2021 18:27:30

This is a Blueprint for shutting down single or multiple AWS EC2 instances

Parameters

Name Type Script Reference Default Value Comment
AccessKEY Text accesskey AKIAPHIVJOOQL3YNLCPP This is an Access Key for AWS IAM User
Attune Node Windows Server attuneNode This is my Attune Node
Attune Node Credential Windows OS Credential attuneNodeCredential This is my Attune Node Credential
Attune Node Credentials Windows OS Credential attuneNodeCredentials
HashValue Text hashvalue @{"i-0fffdd7a07b128f57" = "eu-west-2";"i-01108b6pb6b8d30dc" = "eu-west-1"} This is a Hash table holding InstanceID and Region of the AWS EC2 instance(s)
SecretKey Text secretkey PFZj7oBcNMTe+R+TTIWdQqXLYcttQ8IOAh1O8zJu This is a Secret Key for AWS IAM User

1 - AWSPowerShell-Module

This step Installs the AWSPowerShell Module

Region for ExecutionPolicy
  • The script in this region first gets the execution policy of the current PowerShell session.
  • Then checks if it is set to Unrestricted.
  • If it is set, it does nothing but writes a message to the screen.
  • Else will set the execution policy to Unrestricted for the current session.

Region to check if AWSPowerShell Module is installed
  • First checks if the AWSPowerShell module is installed.
  • If installed, it does nothing but writes a message to the screen.
  • Else goes ahead to installs the module and writes a message to the screen.
The connection details have changed from the last step.

Login as user on node

  1. Connect via RDP
    mstsc /admin /v:Attune Node
  2. Login as user {Attune Node Credential}
  3. Then open a command prompt
This is a PowerShell Script make sure you run it with powershell.exe Click start menu, enter "powershell" in the search bar, then select the powersehll program
#Region for ExecutionPolicy
# ===========================================================================
# Get Execution Policy of the current process
$Script:ProcessEP = Get-ExecutionPolicy -Scope Process

#Get the value of the Execution Policy and save it in the Variable
$Script:ValueProcessEP = ($Script:ProcessEP).value__

# Check if the Execution Policy of the process is set to Unrestricted
if ($Script:ValueProcessEP -eq 0) {

    # echo the message
    Write-Output "Execution Policy is already set to Unrestricted for the Process"
# Check if the Execution Policy of the process is already set
}else{

    # Set the ExecutionPolicy of the Process to Unrestricted
    Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted -Force -Confirm:$false

    # Checks if the Execution Policy has been set
    if ((Get-ExecutionPolicy -Scope Process).value__ -eq 0) {

        # echo the message
        Write-Output "Execution Policy is now set to Unrestricted for the Process"
    }
}
# ===========================================================================
#EndRegion for ExecutionPolicy 



#Region to Check if AWSPowerShell Module is installed 
# ===========================================================================
#Region if module is installed, update module if version is not up to Version "4.1.13.0"
if($null -ne (Get-InstalledModule -Name AWSPowerShell -MinimumVersion "4.1.13.0" -ErrorVariable +ErrorAWSV -ErrorAction SilentlyContinue)) {

    # Get the AWS module installed and save it in a variable
    $Script:GetAWSModule = Get-InstalledModule -Name AWSPowerShell -MinimumVersion "4.1.13.0" -ErrorVariable +ErrorAWSV -ErrorAction SilentlyContinue

    # echo the message
    Write-Output "AWS PowerShell Module exists ... checking ..."

    # Gets the build number for the AWS Module 
    $Script:AWSModuleBuild = ($Script:GetAWSModule).Version

    # Checks the build number to meet requirements 
    if($Script:AWSModuleBuild -like "*4.1.13.0*") {

        # Saves and converts Module version name to a variable
        $Script:OutVersion = ((($Script:GetAWSModule).Version)).tostring()

        # echo the message
        Write-Output "AWSPowerShell Module Version $Script:OutVersion meets the minimum requirement."

    # Check if the build version is on 13
    }else{
        
        # echo the message
        Write-Output "AWS PowerShell Module is updated :)"
    }
#EndRegion if the module is installed, update module if the version is not up to Version "4.1.13.0"
# ===========================================================================
#Region If the module is not installed, install it 
}else{

    # echo the message
    Write-Output "AWS PowerShell Module is not installed"
    
    # echo the message
    Write-Output "AWS PowerShell Module is installing..."

    # Install AWS Powershell Module 
    Install-Module -Name AWSPowerShell -MaximumVersion "4.1.13.0" -Scope "CurrentUser" -AllowClobber:$true -Confirm:$false -Force

    # echo the message
    Write-Output "AWS PowerShell Module is installed :)"
}
#EndRegion If the module is not installed, install it
# ===========================================================================
#EndRegion Check if AWSPowerShell Module is installed

2 - Stop-EC2Instance

This step Stops the AWS EC2 instance(s)

Region for Execution Policy
  • The script in this region first gets the execution policy of the current PowerShell session.
  • Then checks if it is set to Unrestricted.
  • If it is set, it does nothing but writes a message to the screen.
  • Else will set the execution policy to Unrestricted for the current session.

Region for Stop EC2 Instance

First, the AWSPowerShell module is imported to the current session.

Then the values below are set:

| Variable Name | Description | Value | | :----: | :----: | :----: | | AccessKeyValue | This is the AWS IAM User access key | {accesskey.value} | | SecretKeyValue | This is the AWS IAM User secret key | {secretkey.value} | | ProfileNameVaule | This holds the user defined AWS credentials | DefaultSetKeys | | HashValue | This holds a hash table containing the EC2 InstanceId and Regoin | {hashvalue.value} |


Below is a table explaining how to create the variables on Attune with matching data types

| Value in script | Value Location in Attune | Parameter location in Attune| Data Type | Example | | :----: | :----: | :----: | :----: | :----: | | {accesskey.value} | (value) Inputs-Text Vaules-Variable | (access) Inputs-Text Vaules-Name | String | HKOPUHIVJOQQN3YNLCIL | | {secretkey.value} | (value) Inputs-Text Vaules-Variable | (secretkey) Inputs-Text Parameter-Name | String | MJYj7oBcNMTe+R+TTIWdQqXLYcttQ8IOwh1O9zH5 | | {hashvalue.value} | (value) Inputs-Text Vaules-Variable | (hashvalue) Inputs-Text Parameter-Name | Hash Table | @{"i-0ffhdd7a07b129f59"="eu-west-2";"i-01109b6fb6b9d30fe"="eu-west-1"} |


The Hash Table holds the InstanceID with its corresponding Region.

Hash Table Value Syntax:

powershell @{"instanceid1"="region1";"instanceid2"="region2"}

powershell @{"i-0ffhdd7a07b129f59"="eu-west-2";"i-01109b6fb6b9d30fe"="eu-west-1"}


Next, the IAM AWS User Credential is set using the Set-AWSCredential CMDLET.

NOTE: Ensure to edit the value of the parameters AccessKey and SecretKey in Attune to match the IAM AWS User Credential with the privilege to perform this operation.

Next, it loops through the values of the InstanceID and their corresponding Region and stops the EC2 instance(s) using the Stop-EC2Instance CMDLET.

NOTE: The InstanceId and Region parameters are gotten from the Hash Table created in Attune.

Finally, a CMDLET Remove-AWSCredentialProfile runs to remove the credential profile created in the session from the local credential store.

This step has the following parameters

Name Script Reference Default Value
SecretKey {secretkey.value} PFZj7oBcNMTe+R+TTIWdQqXLYcttQ8IOAh1O8zJu
HashValue {hashvalue.value} @{"i-0fffdd7a07b128f57" = "eu-west-2";"i-01108b6pb6b8d30dc" = "eu-west-1"}
AccessKEY {accesskey.value} AKIAPHIVJOOQL3YNLCPP
The connection details have changed from the last step.

Login as user on node

  1. Connect via RDP
    mstsc /admin /v:Attune Node
  2. Login as user {Attune Node Credentials}
  3. Then open a command prompt
This is a PowerShell Script make sure you run it with powershell.exe Click start menu, enter "powershell" in the search bar, then select the powersehll program
#Region for ExecutionPolicy
# ===========================================================================
# Get Execution Policy of the current process
$Script:ProcessEP = Get-ExecutionPolicy -Scope Process

#Get the value of the Execution Policy and save it in the Variable
$Script:ValueProcessEP = ($Script:ProcessEP).value__

# Check if the Execution Policy of the process is set to Unrestricted
if ($Script:ValueProcessEP -eq 0) {

    # echo the message
    Write-Output "Execution Policy is already set to Unrestricted for the Process"
# Check if the Execution Policy of the process is already set
}else{

    # Set the ExecutionPolicy of the Process to Unrestricted
    Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted -Force -Confirm:$false

    # Checks if the Execution Policy has been set
    if ((Get-ExecutionPolicy -Scope Process).value__ -eq 0) {

        # echo the message
        Write-Output "Execution Policy is now set to Unrestricted for the Process"
    }
}
# ===========================================================================
#EndRegion for ExecutionPolicy 



#Region Start EC2 Instance
# ===========================================================================
# Import Module for AWS PowerShell
Import-Module -Name AWSPowerShell

# Save accesskey to this Variable
$Script:AccessKeyValue = "{accesskey.value}"

# Save secretkey to this variable
$Script:SecretKeyValue = "{secretkey.value}"

# Set value to store profile 
$Script:ProfileNameVaule = "DefaultSetKeys"

# Hash Table of InstanceId with coressponding region pair
$Script:HashValue = {hashvalue.value}

# Set AWS Credentials
Set-AWSCredential -AccessKey $Script:AccessKeyValue -SecretKey $Script:SecretKeyValue -StoreAs $Script:ProfileNameVaule

# Loop through has table of EC2 instances and their region
foreach ($item in $Script:HashValue.GetEnumerator()) {

    # echo the message
    Write-Output "EC2 instance with InstanceId $($item.Name) in $($item.Value) region is stoping..." 

    # Stop the instance
    Stop-EC2Instance -InstanceId $($item.Name) -Region $($item.Value) -ProfileName $Script:ProfileNameVaule

}

# Remove Profile
Remove-AWSCredentialProfile -ProfileName $Script:ProfileNameVaule -Force

#EndRegion Start EC2 Instance
# ===========================================================================