AWS Snapshot Backup for Instance Patching

NOTE – For this script to work your instances must have a unique name tag. I use this tag for machine host-names.

The requirement for this script was to snapshot all volumes of a machine before deploying Windows updates to ensure a safe and quick rollback option.

This script is to snapshot and tagĀ all attached volume ID’s from a single instance Name Tag within AWS Powershell. The sections below describe the action of script sections

  1. Import AWS Powershell module (needs to be downloaded and installed)
  2. Asks for the server name from the initiator then find’s the Instance ID from the Server name
  3. Collect all volumes attached to the instance ID
  4. Reformat the volume IDs
  5. Create volume snapshot and tag with the snapshot with a description and new tag called PrePatch and the value being Yes
  6. Find newly created snapshots
  7. Text output
## ## ## ## ## ## ## ## ## ## ## ##
## AWS Snapshot Backup ##
## Pre-Patching AWS Snapshot ##
## Ben Prudence - 09/02/2016 ##
## ## ## ## ## ## ## ## ## ## ## ##

## 1 Add AWS cmdlets and connect
Import-Module AWSPowerShell

## 2 Instance ID from server name
$Server = Read-host "Server Name"
$Servertag = Get-EC2Tag -Filter @{ Name="key";Values="Name"},@{ Name="value";Values=$Server} | Where {$_.ResourceType -like '*instance*'} 
$ServerId = $Servertag | % { $_.ResourceId}
$instance = $ServerId

## 3 Get a collection of all volumes attached to the instance
$volumes = @(get-ec2volume) | ? { $_.Attachments.InstanceId -eq $instance}
$volumeNames = $volumes | Select VolumeId, Size, VolumeType, State, CreateTime | ft -AutoSize

## 4 Get a collection of each volume's ID property
$volumeId = $volumes | % {$_.VolumeId}

## 5 Create snapshot of each volume attached to the instance
$PatchDate = Read-host "Date of Patching"
$volumeId | New-EC2Snapshot -Description "Pre Patch Snapshot - Patching $PatchDate" | % {New-EC2Tag -Resource $_.SnapshotId -Tag @{Key="Name"; Value=$Server}, @{Key="PrePatch";Value="Yes"}}

## 6 Get Volume/Snapshot Tags
$Volumetag = Get-EC2Tag -Filter @{ Name="key";Values="Name"},@{ Name="value";Values="*$Server*"} | Where {$_.ResourceType -like '*volume*'} | Select ResourceId, Value
$Snapshotview = foreach ($vid in $volumeId) {Get-EC2Snapshot | where {$_.volumeId -eq $vid -and $_.Description -like '*Patch*'}}
$snapview = $Snapshotview | Select SnapshotId, Description, VolumeId

## 7 Script output
Write-Host "Volumes snapshots are now being created. Login to AWS console to view status, wait for them to be Complete before patching" -foregroundcolor Green
$Volumetag

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.