Many of us take snapshots of virtual machines before performing any maintenance on them as it allows for a quick rollback point should the unexpected occur.
I am going to show a use case where you can automate the snapshot creation via MyCloudSpace using a few lines of PowerShell. This could be any language you want as ultimately it is just firing HTTPS requests to our API.
There are many use cases but one we see frequently on the platform are snapshots created before Windows Patching occurs. You could hook this up to your automated patching mechanisms such as a SCCM Task Sequence or just have a list of your servers defined and automate the creation of the snapshots all at once.
Here is what we want the script to do;
- Login to MyCloudSpace to get a valid session
- Get the virtual machine in the tenancy matching on the provided guest hostname
- Take a snapshot of the matched virtual machine with the provided title/name
- Wait for the snapshot to be active and return the result (otherwise provide an error if not active in the defined time period)
The source for this is hosted over on our MyCloudSpace API Examples git repository which we will begin to add more too as the series progresses.
View the full source to this example here. But let's break it down.
.\TakeSnapshotOfVirtualMachine.ps1 -vmHostname "WEBSERVER01" -snapshotName "This was automated from Powershell"
Setup & Configuration
There are a couple of bits of information you need to set in the script before you run the script.
Line 21 - Log Path - Give this a path on the local system so you can emit the logs from the script to it, useful if you are batching this with multiple machines
Line 30/31/32 - Credentials - You login credentials to MyCloudSpace which will be used to generate an authentication token for use with the API.
NOTE! it is not recommended to store these values as plain text - you should secure them out - couple of options below;
- Secure String (single user) - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/convertto-securestring?view=powershell-6
- Encrypt string with machine key (run from same machine) https://stackoverflow.com/questions/46400234/encrypt-string-with-the-machine-key-in-powershell
- From an Azure Function (the bit in yellow half way down) https://blog.tyang.org/2016/10/08/securing-passwords-in-azure-functions/
That's all there is too it! We would love to hear from you around any use cases you put this code to work with.
View the full source to this example here.