CloudStack API PowerShell Example

Summary: This script uses a simple command, sent via PowerShell and REST to a CloudStack API, in order to list all visible Virtual Machines as well as their current state (‘Running’, ‘Stopped’, etc.).

CloudStack is an Apache Open Source project for managing a cloud service (much like OpenStack, but it’s been around a LOT longer). CloudStack also has an impressive list of customers (check out their Wikipedia post above). Like most cloud services, CloudStack has an API (REST) for programmatically interacting with the service.

Note: A valid account’s API public key and secret are required for this script.

This API authenticates requests by using an account’s public key and secret to create a signature for the API request. In order the create the signature, the command being signed must be broken down into key/value pairs, sorted, reassembled for signing, then converted to lower case.

On-going problems: This script mostly works. But it (or the API) has problems with certain command strings. And PowerShell doesn’t seem to like the API’s output in JSON (so this script uses the default XML). If you find a solution, please reach out.

Datapipe’s documentation of their implementation of the CloudStack API can be found here: https://docs.cloud.datapipe.com/developers/api/developers-guide

Here is a sample list of command strings that leverage the listVirtualMachines method (your mileage may vary):

command=listVirtualMachines
command=listVirtualMachines&state=Running
command=listVirtualMachines&account=General
command=listVirtualMachines&zoneid=13
command=listVirtualMachines&groupid=21&account=General
command=listVirtualMachines&groupid=21&account=General&state=Running
command=listVirtualMachines&state=Stopped&response=json
command=listVirtualMachines&id=3a57b2d3-b95a-4892-903a-34f4662ed475&response=json
command=listVirtualMachines&id=3a57b2d3-b95a-4892-903a-34f4662ed475
command=listVirtualMachines&state=Running&response=json

Note: This script requires PowerShell v.3+ due to the use of the Invoke-RestMethod cmdlets.

openstackApiExample.ps1

#
# Name:: openstackApiExample.ps1
# Version:: 0.1.0 (6/27/2016)
# Script Description:: Queries the Datapipe Cloud (Cloud-Stack) REST API
#
# API Documentation:: https://docs.cloud.datapipe.com/developers/api/developers-guide
#
# Author(s):: Otto Helweg
#
# PowerShell v.3+ is required for the Invoke-RestMethod cmdlet
#
# Parameters: -k = apikey, -s = secret (both are required)
# Example: .\apiExample.ps1 -k "F2rrzJiluwK39LpD6PvyF2rrzJiluwK39LpD6PvyF2rrzJiluwK39LpD6PvyF2rrzJiluwK39LpD6PvyF2rrzJ" -s "iluwK39LpD6PvyF2rrzJiluwK39LpD6PvyF2rrzJiluwK39LpD6PvyF2rrzJiluwK39LpD6PvyF2rrzJiluwK3"

param($k,$s)

$uri=@{}
$baseUri = "https://cloud.datapipe.com/api/compute/v1?"
$command = "command=listVirtualMachines"
# The following is a command string that should work, but doesn't
# $command = "command=listVirtualMachines&state=Running"
$uri["apikey"] = $k
$secret = $s

# Build the Command String for getting an authorization signature
# First extract all key/value pairs in the command into the uri hash
$subCommand = $command.split("&")
foreach ($item in $subCommand | Sort-Object) {
  if ($item -like "*=*") {
    $items = $item.Split("=")
    $uri[$items[0]] = $items[1]
  } else {
    $uri[$item] = ""
  }
}

# Build the signing String by sorting the command key/values then make lowercase for signing
$signString = ""
foreach ($key in $uri.Keys | Sort-Object) {
  if ($uri[$key]) {
    $signString = $signString + $key + "=" + $uri[$key] + "&"
  } else {
    $signString = $signString + $key + "&"
  }
}
$signString = $signString.ToLower()
$signString = $signString.TrimEnd("&")

# Get the HMAC SHA-1 signature for the specific Command String
$hmacSha = New-Object System.Security.Cryptography.HMACSHA1
$hmacSha.key = [Text.Encoding]::ASCII.GetBytes($secret)
$signature = $hmacSha.ComputeHash([Text.Encoding]::ASCII.GetBytes($signString))
$signature = [Convert]::ToBase64String($signature)

# Build the signed REST URI
$newUri = $baseUri + $command + "&apiKey=" + $uri["apikey"] + "&signature=" + $signature
Write-Host "URI: $newUri"
Write-Host "signString: $signString"
Write-Host "Signature: $signature"

# Query for a list of all VMs
Write-Host "Querying the Cloud-Stack API..."
[xml]$vmList = Invoke-RestMethod -Method GET -Uri $newUri -ContentType "application/xml"

# List all VMs visible by the account
Write-Host ""
Write-Host "Virtual Machines:"
foreach ($vm in $vmList.listvirtualmachinesresponse.virtualmachine) {
  if ($vm.state -eq "Stopped") {
    $color = "yellow"
  } else {
    $color = "white"
  }
  Write-Host -ForegroundColor $color "$($vm.displayname) - $($vm.state)"
}

 

Enjoy!

 

Advertisements

Use PowerShell to Refresh CenturyLink Cloud VM Snapshots

Summary: VMs created in the CenturyLink Cloud, can have a snapshot (only 1 per VM), and that snapshot has a maximum life of 10 days. Therefore if it’s necessary to maintain a perpetual snapshot (like for test VMs that have a baseline configuration), VMs need to have their snapshots routinely refreshed. The following PowerShell script leverages the powerful CenturyLink Cloud REST v2 API to automate this process. This script relies on the presence of a ‘bearer token’ for authentication into the CLC API. Details on how to create this ‘bearer token’ can be found in this blog post (as well as details on how to discover your Group ID). The complete reference to CenturyLink’s Cloud REST API can be found here: https://www.ctl.io/api-docs/v2/

This script basically leverages CLC APIs to restore, delete, and create a VM snapshot. After each API is called, the script will wait until the task is complete, by querying the status of the task requested.

Note: This script sample requires PowerShell v4+

Refresh-Snapshot.ps1

#
# Name:: Refresh-Snapshot.ps1
# Version:: 0.1.2 (3/5/2016)
# Script Description:: Refreshes a server's snapshot by restoring the snapshot, deleting it, then creating a new one.
#
# API Documentation:: https://www.ctl.io/api-docs/v2/
#
# Author(s):: Otto Helweg
#

param($s)

# Display help
if (($Args -match "-\?|--\?|-help|--help|/\?|/help") -or !($s)) {
  Write-Host "Usage: Refresh-Snapshot.ps1"
  Write-Host "     -s [server name]       (Required) Server's name according to Centurylink Cloud"
  Write-Host "     -r                     Revert VM to existing snapshot before refreshing"
  Write-Host ""
  Write-Host "EXAMPLES:"
  Write-Host "     Refresh-Snapshot.ps1 -s CA3TESTTEST01 -r"
  Write-Host ""
  exit
}

$goodStatus = @("notStarted","executing","succeeded","resumed")

# PowerShell v4 is required for the REST cmdlets
if (!($psversiontable.PSVersion.Major -ge 4)) {
  Write-Host -ForegroundColor "red" "Requires PowerShell v.4 or greater. Please install the Windows Management Framework 4 or above."
  exit
}

# Check to make sure the Bearer Token is less than 2 weeks old
if (!(Test-Path .\bearerToken.txt)) {
  Write-Host -ForegroundColor Red "Error: Bearer Token file is missing. Run Save-BearerToken.ps1"
  exit
} else {
  $fileInfo = dir .\bearerToken.txt
  if ($fileInfo.LastWriteTime -lt (Get-Date).AddDays(-11)) {
    Write-Host -ForegroundColor Yellow "Warning: Bearer Token file is almost out of date. Run Save-BearerToken.ps1"
  }
  if ($fileInfo.LastWriteTime -lt (Get-Date).AddDays(-13)) {
    Write-Host -ForegroundColor Red "Error: Bearer Token file is out of date. Run Save-BearerToken.ps1"
    exit
  }
}

$bearerTokenInput = Get-Content ".\bearerToken.txt"
$accountAlias = "SXSW"
$bearerToken = " Bearer " + $bearerTokenInput
$header = @{}
$header["Authorization"] = $bearerToken
$serverName = $s

Write-Host -ForegroundColor Green "Getting server properties for $serverName..."
$requestUri = "https://api.ctl.io/v2/servers/$accountAlias/$serverName"
$serverProperties = Invoke-RestMethod -Method GET -Headers $header -Uri $requestUri -ContentType "application/json"

if (!$serverProperties) {
  Write-Host -ForegroundColor Red "Error: $serverName does not appear to exist!"
  exit
}

if (($Args -contains "-r") -and $serverProperties.details.snapshots) {
  Write-Host -ForegroundColor Green "Restoring snapshot for $serverName..."
  $startTime = Get-Date
  $requestUri = "https://api.ctl.io$($serverProperties.details.snapshots.links.href[0])/restore"
  $restoreResult = Invoke-RestMethod -Method POST -Headers $header -Uri $requestUri -ContentType "application/json"
  $statusUri = "https://api.ctl.io/v2/operations/$accountAlias/status/$($restoreResult.id)"
  $continue = $true
  Write-Host "Waiting for snapshot restore to complete..."
  while ($continue) {
    $statusResult = Invoke-RestMethod -Method GET -Headers $header -Uri $statusUri -ContentType "application/json"
    [int]$elapsedSeconds = ($(Get-Date) - $startTime).TotalSeconds
    Write-Host "   [$elapsedSeconds seconds] $($statusResult.status)"
    if ($statusResult.status -eq "succeeded") {
      $continue = $false
    }
    if ($statusResult.status -notin $goodStatus) {
      Write-Host -ForegroundColor Red "Error: Restoring snapshot for $serverName failed!"
      exit
    }
    Sleep 2
  }
}

if ($serverProperties.details.snapshots) {
  Write-Host -ForegroundColor Green "Deleting snapshot for $serverName..."
  $startTime = Get-Date
  $requestUri = "https://api.ctl.io$($serverProperties.details.snapshots.links.href[0])"
  $restoreResult = Invoke-RestMethod -Method DELETE -Headers $header -Uri $requestUri -ContentType "application/json"
  $statusUri = "https://api.ctl.io/v2/operations/$accountAlias/status/$($restoreResult.id)"
  $continue = $true
  Write-Host "Waiting for snapshot delete to complete..."
  while ($continue) {
    $statusResult = Invoke-RestMethod -Method GET -Headers $header -Uri $statusUri -ContentType "application/json"
    [int]$elapsedSeconds = ($(Get-Date) - $startTime).TotalSeconds
    Write-Host "   [$elapsedSeconds seconds] $($statusResult.status)"
    if ($statusResult.status -eq "succeeded") {
      $continue = $false
    }
    if ($statusResult.status -notin $goodStatus) {
      Write-Host -ForegroundColor Red "Error: Deleting snapshot for $serverName failed!"
      exit
    }
    Sleep 2
  }
}

Write-Host -ForegroundColor Green "Creating snapshot for $serverName..."
$startTime = Get-Date
$createBody = "{
  ""snapshotExpirationDays"":""10"",
  ""serverIds"":[
      ""$serverName""
    ]
}"

$requestUri = "https://api.ctl.io/v2/operations/$accountAlias/servers/createSnapshot"
$restoreResult = Invoke-RestMethod -Method POST -Headers $header -Body $createBody -Uri $requestUri -ContentType "application/json"
$statusUri = "https://api.ctl.io/v2/operations/$accountAlias/status/$($restoreResult.links.id)"

$continue = $true
Write-Host "Waiting for snapshot creation to complete..."
while ($continue) {
  $statusResult = Invoke-RestMethod -Method GET -Headers $header -Uri $statusUri -ContentType "application/json"
  [int]$elapsedSeconds = ($(Get-Date) - $startTime).TotalSeconds
  Write-Host "   [$elapsedSeconds seconds] $($statusResult.status)"
  if ($statusResult.status -eq "succeeded") {
    $continue = $false
  }
  if ($statusResult.status -notin $goodStatus) {
    Write-Host -ForegroundColor Red "Error: Creating snapshot for $serverName failed!"
    exit
  }
  Sleep 2
}

 

Enjoy!