Shutdown Single or Multiple AWS EC2 Instances

Exported on 28-Sep-2021 10:58:14

Using Attune to shutdown AWS EC2 Instance

This Blueprint is used for shutting down single or multiple AWS EC2 Instances.

An EC2 instance is a virtual server in Amazon Web services. It stands for Elastic Compute Cloud.

It is a web service where an AWS user can provision a compute server in the AWS cloud.

Pre-Blueprint Attune setup
  1. On the Inputs tab, create a Windows Node for the host you wish to run the AWS EC2 shutdown script.
  2. On the Inputs tab, create a Windows Credentials to connect to the host you wish to run the AWS EC2 shutdown script.
  3. On the Inputs tab, create a Text value to store the values below:
    • AccessKey: This is the AWS IAM User access key (DataType: String).
    • SecretKey: This is the AWS IAM User secret key (DataType: String).
    • HashValue: This holds a hash table containing the EC2 InstanceId and Region (DataType: Hashtable).

HashValue Syntax:

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

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

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

NOTE: The InstanceId and Region should be edited as well to match the EC2 Instance(s).


Blueprint Steps
  1. Check and Install the AWS PowerShell Module
  2. Shuts down the AWS EC2 Instance(s)

Parameters

Name Type Script Reference Default Value Comment
AccessKEY Text accesskey ALIBUHIVJOQQNLSXO4GP This is an Access Key for AWS IAM User
Attune Node Windows Server attuneNode This is an Attune Node
Attune Node Credential Windows OS Credential attuneNodeCredential This is an Attune Node Credential
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 PscrMsa/5YFbybwdAlnoKUDGpgRkgXNj1ADI4xju This is a Secret Key for AWS IAM User

1 - Install AWS PowerShell Module

This step installs the AWS PowerShell Module

The Blueprint first gets the Execution Policy of the current PowerShell session.

Then, checks if the Execution Policy is set to Unrestricted.

If it's not, it then sets the Execution Policy to Unrestricted for the current PowerShell session.

Next, it checks if the AWSPowerShell module is installed.

If it's not installed, it then goes ahead to install the module.

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) {

    # Write 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) {

        # Write 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 
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 :)"
    }
}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 Check if AWSPowerShell Module is installed

2 - Shutdown EC2 Instance

This step shuts down the AWS EC2 instance(s)

The Blueprint first gets the Execution Policy of the current PowerShell session.

Then, checks if the Execution Policy is set to Unrestricted.

If it's not, it then sets the Execution Policy to Unrestricted for the current PowerShell session.

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

Then the values below are set:

  1. AccessKeyValue: This is the AWS IAM User access key corresponding to the AccessKey set in the Inputs Tab.
  2. SecretKeyValue: This is the AWS IAM User secret key corresponding to the SecretKey set in the Inputs Tab.
  3. HashValue: This holds a hashtable containing the AWS EC2 InstanceId and Region corresponding to the HashValue set in the Inputs Tab.

Next, the AWS IAM User Credential is set and saved in the local credential store.

Then it loops through the values of the InstanceID and their corresponding Region and stops the EC2 instance(s).

Finally, the credential profile created in the session is removed from the local credential store.

This step has the following parameters

Name Script Reference Default Value
HashValue {hashvalue.value} @{"i-0fffdd7a07b128f57" = "eu-west-2";"i-01108b6pb6b8d30dc" = "eu-west-1"}
SecretKey {secretkey.value} PscrMsa/5YFbybwdAlnoKUDGpgRkgXNj1ADI4xju
AccessKEY {accesskey.value} ALIBUHIVJOQQNLSXO4GP

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) {

    # Write 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) {

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



#Region for Shutting down 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()) {

    # Write 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