Using PowervROps cmdlets (part 3) – Adding metrics and properties to objects

Introduction

In the third part in this series of blog posts we are going to use the cmdlets to add metrics and properties to various objects, these metrics and properties can be used in exactly the same way as those from management packs, although you should be aware that metrics age and are not available on dashboards or for use in super metric calculations after a period of time. For dashboards this appears to be roughly four hours and for super metrics this is after 48 hours.

The functions

There are three functions available within PowervROps for adding properties and metrics:

  1. addProperties
  2. addStats
  3. addStatsforResources

The first and second functions enable properties and stats (metrics) to be added to a single vROps object (multiple properties and metrics can be added in a single command). The third command allows metrics to be added to multiple objects in a single command, which is much more efficient in large environments, although there is a limit of 1000 objects in a single execution. There is no comparable API method to add properties to multiple objects via a single command.

How to use

As discussed in part 1 of this blog series, before any cmdlets can be run a means of authentication needs to be configured. As with previous blog posts the examples shown will use token based authentication, although credentials based is perfectly fine. In all examples shown a variable of $token will be used.

All three functions require body content to be submitted along with the command. The functions will accept both JSON and XML (as the vROps API accepts both). For the purposes of this blog JSON will be used throughout. More information can be found about different request examples via the vROps API document (https://vropsfqdn/suite-api/docs/rest/index.html). The functions within PowervROps match the name shown in the documentation so should be easy to locate.

The addProperties and addStats functions also require an objectid to be submitted along with the request. Examples are shown in part 1 of this blog series

Examples

addProperties

In this example we are going to add a property called ‘CloudKindergarten|Demo|DevicePurpose’ with a value of ‘Active Directory Domain Controller’ to the virtual machine ‘vm-a’

import-module c:\users\taguser\documents\github\powervrops\powervrops.psm1
$resthost = 'vrops-01a.cloudkindergarten.local'
$token = acquiretoken -resthost $resthost -username admin -password VMware1! -authsource local
$object = getresources -resthost $resthost -token $token -name 'vm-a' -resourceKind 'VirtualMachine'
$body = @{
 'property-content' = @( @{
 'statKey' = 'CloudKindergarten|Demo|DevicePurpose'
 'timestamps' = @(getTimeSinceEpoch)
 'values' = @('Active Directory Domain Controller')
 'others' = @()
 'otherAttributes' = @{}
 }
 )
}
addProperties -resthost $resthost -token $token -objectid $object.resourcelist.identifier -body ($body | convertto-json -depth 5) -contenttype 'json'

This example shows a JSON body content. If the body was in XML format then the addProperties command would be altered as below:

addProperties -resthost $resthost -token $token -objectid $object.resourcelist.identifier -body ($body | convertto-json -depth 5) -contenttype 'xml'

We can see below that the property is displayed in the All Metrics page and can be selected in the same way as any other property:

Screen Shot 2018-01-30 at 13.22.34

We can also retrieve this property using the getResourceProperties function:

import-module c:\users\taguser\documents\github\powervrops\powervrops.psm1
$resthost = 'vrops-01a.cloudkindergarten.local'
$token = acquiretoken -resthost $resthost -username admin -password VMware1! -authsource local
$object = getresources -resthost $resthost -token $token -name 'vm-a' -resourceKind 'VirtualMachine'
$resourceproperties = (getresourceproperties -resthost $resthost -token $token -objectid $object.resourcelist.identifier).property | where { $_.name -eq 'CloudKindergarten|Demo|DevicePurpose'}
$resourceproperties

This returns the following:

Screen Shot 2018-01-30 at 13.40.48

addStats

The second example shows adding a single metric to a virtual machine. The metric name is ‘CloudKindergarten|Demo|SingleMetricOne and a random value of between 1 and 100  will be added. The code includes an additional unnecessary line that generates the random number, and this variable is used within the JSON body.

import-module c:\users\taguser\documents\github\powervrops\powervrops.psm1
$resthost = 'vrops-01a.cloudkindergarten.local'
$token = acquiretoken -resthost $resthost -username admin -password VMware1! -authsource local
$object = getresources -resthost $resthost -token $token -name 'vm-b' -resourceKind 'VirtualMachine'
$metricvalue = get-random -Minimum 1 -Maximum 100
$body = @{
'stat-content' = @( @{
'statKey' = 'CloudKindergarten|Demo|SingleMetricOne'
'timestamps' = @(getTimeSinceEpoch)
'data' = @($metricvalue)
'others' = @()
'otherAttributes' = @{}
}
)
}
addStats -token $token -resthost $resthost -objectid $object.resourcelist.identifier -body ($body | convertto-json -depth 5) -contenttype json

In the image below the results of running the command many times in a short space are shown.

Screen Shot 2018-01-30 at 15.56.27

When running this command, it is not limited to single metric, nor a single data point. In the example below values for two different metrics are being added for datapoints at five minute intervals for the last hour.

import-module c:\users\taguser\documents\github\powervrops\powervrops.psm1import-module c:\users\taguser\documents\github\powervrops\powervrops.psm1
$resthost = 'vrops-01a.cloudkindergarten.local'
$token = acquiretoken -resthost $resthost -username admin -password VMware1! -authsource local
$object = getresources -resthost $resthost -token $token -name 'vm-c' -resourceKind 'VirtualMachine'
$metricvaluesone = @()
$metricvaluestwo = @()
$timestamps = @()
for ($i = 0;$i -lt 12;$i++) {
$metricvaluesone += (get-random -Minimum 1 -Maximum 100)
$metricvaluestwo += (get-random -Minimum 1 -Maximum 100)
$timestamps += gettimesinceepoch -date (get-date).AddMinutes(($i*-5))}
$body = @{
'stat-content' = @( @{
'statKey' = 'CloudKindergarten|Demo|SingleMetricOne'
'timestamps' = $timestamps
'data' = $metricvaluesone
'others' = @()
'otherAttributes' = @{}
}
@{
'statKey' = 'CloudKindergarten|Demo|SingleMetricTwo'
'timestamps' = $timestamps
'data' = $metricvaluestwo
'others' = @()
'otherAttributes' = @{}
}
)
}
addStats -token $token -resthost $resthost -objectid $object.resourcelist.identifier -body ($body | convertto-json -depth 5) -contenttype json

The results can be seen in the image below

Screen Shot 2018-01-30 at 16.33.39.png

addStatsforResources

In the last example multiple metrics are going to be added to multiple VMs. Specifically the following metrics are going to be added:

  • CloudKindergarten|Demo|MultiMetricOne – with a random value between 1 and 100
  • CloudKindergarten|Demo|MultiMetricTwo – with a random value between 1 and 100
  • CloudKindergarten|Demo|MultiMetricThree – with a random value between 1 and 100

These metrics are going to be added to the following VMs:

  • vm-a
  • vm-b
  • vm-c
  • vm-d
  • vm-e
    import-module c:\users\taguser\documents\github\powervrops\powervrops.psm1
    $resthost = 'vrops-01a.cloudkindergarten.local'
    $token = acquiretoken -resthost $resthost -username admin -password VMware1! -authsource local
    $metrictime = getTimeSinceEpoch
    $allvms = @('vm-a','vm-b','vm-c','vm-d','vm-e')
    $allvmstatcontent = @()
    foreach ($vm in $allvms) {
    $object = getresources -resthost $resthost -token $token -name $vm -resourceKind 'VirtualMachine'
    $statcontent = @()
    $statcontent += (@{statKey='CloudKindergarten|Demo|MultiMetricOne';timestamps=@($metrictime);data=@((get-random -Minimum 1 -Maximum 100));others=@();otherAttributes=@{};}) 
    $statcontent += (@{statKey='CloudKindergarten|Demo|MultiMetricTwo';timestamps=@($metrictime);data=@((get-random -Minimum 1 -Maximum 100));others=@();otherAttributes=@{};})
    $statcontent += (@{statKey='CloudKindergarten|Demo|MultiMetricThree';timestamps=@($metrictime);data=@((get-random -Minimum 1 -Maximum 100));others=@();otherAttributes=@{};})
    $vmstatdetail = @{
     'id' = $object.resourcelist.identifier
     'stat-contents' = $statcontent
    }
    
    $allvmstatcontent += $vmstatdetail
    
    }
    $vmstatcontent = @{
     'resource-stat-content' = $allvmstatcontent
     }
    
    addstatsforresources -resthost $resthost -token $token -body ($vmstatcontent | convertto-json -depth 10)

The outcome of this can be seen via a view in vROps

Screen Shot 2018-01-30 at 17.00.20

As with the addStats function, multiple data points can be added with the addstatsforresources function:

import-module c:\users\taguser\documents\github\powervrops\powervrops.psm1
$resthost = 'vrops-01a.cloudkindergarten.local'
$token = acquiretoken -resthost $resthost -username admin -password VMware1! -authsource local
$allvms = @('vm-a','vm-b','vm-c','vm-d','vm-e')
$allvmstatcontent = @()
foreach ($vm in $allvms) {
$object = getresources -resthost $resthost -token $token -name $vm -resourceKind 'VirtualMachine'
$metricvaluesone = @()
$metricvaluestwo = @()
$metricvaluesthree = @()
$timestamps = @()
for ($i = 0;$i -lt 12;$i++) {
$metricvaluesone += (get-random -Minimum 1 -Maximum 100)
$metricvaluestwo += (get-random -Minimum 1 -Maximum 100)
$metricvaluesthree += (get-random -Minimum 1 -Maximum 100)
$timestamps += gettimesinceepoch -date (get-date).AddMinutes(($i*-5))}
$statcontent = @()
$statcontent += (@{statKey='CloudKindergarten|Demo|MultiMetricOne';timestamps=$timestamps;data=$metricvaluesone;others=@();otherAttributes=@{};})
$statcontent += (@{statKey='CloudKindergarten|Demo|MultiMetricTwo';timestamps=$timestamps;data=$metricvaluestwo;others=@();otherAttributes=@{};})
$statcontent += (@{statKey='CloudKindergarten|Demo|MultiMetricThree';timestamps=$timestamps;data=$metricvaluesthree;others=@();otherAttributes=@{};})
$vmstatdetail = @{ 'id' = $object.resourcelist.identifier 'stat-contents' = $statcontent}
$allvmstatcontent += $vmstatdetail}
$vmstatcontent = @{ 'resource-stat-content' = $allvmstatcontent }
addstatsforresources -resthost $resthost -token $token -body ($vmstatcontent | convertto-json -depth 10)

The results can be seen for the three metrics on three different virtual machines:

Screen Shot 2018-01-30 at 19.39.19

All posts in this series:

Using PowervROps cmdlets (part 1) – Introduction

Using PowervROps cmdlets (part 2) – Retrieving metrics from objects

Using PowervROps cmdlets (part 3) – Adding metrics and properties to objects

Using PowervROps cmdlets (part 4) – Working with objects

Using PowervROps cmdlets (part 5) – Working with relationships

Using PowervROps cmdlets (part 6) – Working with custom groups

Using PowervROps cmdlets (part 7) – Working with supermetrics

Using PowervROps cmdlets (part 8) – Working with reports

Using PowervROps cmdlets (part 9) – Working with alerts

 

Using PowervROps cmdlets (part 2) – Retrieving metrics from objects

Introduction

This is the second in a series of posts about PowervROps and the available functions. This post will focus on the ability to query metric data from objects in vROps. Two functions are available to query the stats held for resources:

  • getLatestStatsofResources
  • getStatsForResources

The former returns just the latest value for the given resource IDs and metrics, whilst the latter allows a large degree of customisation over the time frame of metrics and rollup of data e.g. averages or maximums within specified time frames

getLatestStatsofResources

This is the simpler of the two functions available, but as a consequence only returns the latest data point for each metric. The example below shows the value for the metric ‘mem|guest_demand’ for the VM ‘esxi-04a’

import-module c:\users\taguser\documents\github\powervrops\powervrops.psm1
$resthost = 'vrops-01a.cloudkindergarten.local'
$token = acquiretoken -resthost $resthost -username admin -password VMware1! -authsource local
$object = getresources -resthost $resthost -token $token -resourceKind 'VirtualMachine' -name 'esxi-04a'
$stats = getLatestStatsofResources -resthost $resthost -token $token -objectid $object.resourceList.identifier -statkey 'mem|guest_demand'
$stats.values.'stat-list'.stat

The output of this script is as follows:

Screen Shot 2018-01-30 at 21.38.28

getStatsForResources

The getStatsForResources function can return a vast amount of data and perform transformation of that data in a similar manner available within vROps views. The function requires a body element that contains the query parameters.

The example below queries all virtual machines for a single metric; mem|guest_demand. The data returned in this example returns all data at five minute intervals for the last hour

import-module c:\users\taguser\documents\github\powervrops\powervrops.psm1
$resthost = 'vrops-01a.cloudkindergarten.local'
$token = acquiretoken -resthost $resthost -username admin -password VMware1! -authsource local
$allvms = getresources -resthost $resthost -token $token -resourceKind 'VirtualMachine'
$resourcelist = @()
$metricstoquery = @('mem|guest_demand')
foreach ($vm in $allvms) {
$resourcelist += $vm.resourcelist.identifier
}
$body = @{
'resourceId' = $resourcelist
'statKey' = $metricstoquery
'begin' = (getTimeSinceEpoch -date ((get-date).AddHours(-1)))
'end' = (getTimeSinceEpoch)
'rollUpType' = 'LATEST'
'intervalType' = 'MINUTES'
'intervalQuantifier' = 5
'dt' = $false
'latestMaxSmaples' = 1
} | convertto-json -depth 10
$statsofresources = getStatsForResources -resthost $resthost -token $token -body $body
foreach ($statentry in $statsofresources.values) {
write-host ''
write-host ("Virtual Machine: " + ($allvms.resourceList | where { $_.identifier -eq $statentry.resourceid }).resourcekey.name)
foreach ($stat in $statentry.'stat-list') {
write-host ('Metric: ' + $stat.stat.statkey.key)
for ($i=0;$i -lt $stat.stat.timestamps.count;$i++) {
write-host (((Get-Date '1/1/1970').AddMilliseconds($stat.stat.timestamps[$i])).datetime + ' | ' + $stat.stat.data[$i])
}
}
}

The example above outputs the data to the powershell session, but in practice once the data has been returned then it can be used in any way.

Screen Shot 2018-01-30 at 20.49.20

The data held in vROps can be queried and returned in a number of different ways. The relevant elements to modify are as follows:

'resourceId' = $resourcelist

An array of vROps identifiers

'statKey' = $metricstoquery

An array of metrics to query

'begin' = (getTimeSinceEpoch -date ((get-date).AddDays(-7)))
'end' = (getTimeSinceEpoch)

The start and end times for the queried data. In the example above all data from the current time and for the last seven days will be queried.

'rollUpType' = 'LATEST'

How the data will be transformed. Available options are as follows:

SUM – The sum of all datapoints in each interval period
AVG – The average of the datapoints in each interval period

Screen Shot 2018-01-30 at 21.19.13
MIN – The minimum value of the datapoints in each interval period
MAX – The maximum value of the datapoints in each interval period

Screen Shot 2018-01-30 at 21.20.17
LATEST – The most recent sample of the datapoints in each interval period (see the example for interval type below to better describe the data that will be returned)
COUNT – The number of samples within each interval period

Screen Shot 2018-01-30 at 21.18.24

Take care when using a large time frame with a small interval type and a large number of metrics and resources as it can take a long time for the data to be returned

'intervalType' = 'MINUTES'
'intervalQuantifier' = 5

The time interval between data points. Note that if using any interval period beyond hours then the values returned will have time stamps of the last second of each hour. They will not be for hour points directly preceding the time at which the query is executed. An example of this is shown below:

Screen Shot 2018-01-30 at 21.15.09

In this example, the data point for 21:59:59 is the last data point in the hour between 21:00:00 and 21:59:59 which in this case is actually 9:09:13 – the query was run at approximately 21:14:00. The data point for 20:59:59 is the last value between 20:00:00 and 21:59:59 which was actually at 21:59:13

Using PowervROps cmdlets (part 1) – Introduction

Using PowervROps cmdlets (part 2) – Retrieving metrics from objects

Using PowervROps cmdlets (part 3) – Adding metrics and properties to objects

Using PowervROps cmdlets (part 4) – Working with objects

Using PowervROps cmdlets (part 5) – Working with relationships

Using PowervROps cmdlets (part 6) – Working with custom groups

Using PowervROps cmdlets (part 7) – Working with supermetrics

Using PowervROps cmdlets (part 8) – Working with reports

Using PowervROps cmdlets (part 9) – Working with alerts

Using the PowervROps Cmdlets (Part 1) – Introduction

This is the first in a multi part series on how the cmdlets within the PowervROps module (https://github.com/andydvmware/PowervROps) can be used, and gives specific examples for use.

Loading the module

The first thing that needs to be done prior to using the module is to load it into the current PowerShell session. This can be accomplished by running the following command:

import-module <path-to-module>\powervrops.psm1

To list all of the available commands within the module issue the get-command cmdlet:

get-command -module powervrops

Screen Shot 2017-08-21 at 14.32.07

As with all PowerShell cmdlets the get-help cmdlet can be run to return information about a specific one:

get-help addStats -detailed

Authentication

Before any meaningful commands can be executed against vROps we must have a mechanism to authenticate to it. With PowervROps there are two options; a credentials based method and a token based method. Both authentication methods work with all of the cmdlets and indeed they could be mixed and matched as necessary.

Credentials based authentication

Credentials based authentication allows identical functionality when running in interactive mode in that a credentials object can be generated and then used in the same way as using token based authentication:

$credentials = get-credential -username <username>

The advantage of using credentials based authentication is that (although a security risk), the password used for authentication can be saved to a file and then read in during credentials creation. There is lots of information on this subject and below is a link to a blog post I’ve referenced a number of times:

https://blog.kloud.com.au/2016/04/21/using-saved-credentials-securely-in-powershell-scripts/

With this method scripts can be written and then used with task scheduler in a non-interactive fashion.

Token based authentication

Token based authentication requires that a user authenticates to vROps and in turn receives a token that lasts for 24 hours and can then be used on all subsequent requests. To make the process simpler there is a cmdlet called acquireToken which handles this for you. In order to be able to use the token during the session save it to a variable:

$token = acquiretoken -resthost <fqdn-of-the-vrops-node-or-cluster> -username <username> -password <password> -authsource <authsource>

If we execute this and then query the $token variable we should return something like below:

cac9cdc1-c2b3-487c-a51f-4ccb45e2b246::571da88c-a643-4706-a4d5-2e67d9ab1254

A few things to note about this command:

  • The password if using this command directly will be shown in plain text on screen, although there are methods around this when using the command in a script and prompting the user for their password an example is as follows:
  • $token = acquireToken -resthost $resthost -username $username -password ([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((read-host 'Password: ' -assecurestring)))) -authSource $authsource)))
  • The authsource argument can either be local for local vROps accounts or the name of the domain name as configured via the authentication sources section in vROps.

Running our first command

Now that we have an authentication method we can execute our first command. For the purposes of the rest of this post (and the others in this series) I will use variables for things like the authentication token and the rest host that I will be connecting to. There is a cmdlet called getNodeStatus which returns information about the status of your vROps nodes:

getNodeStatus -resthost $resthost -token $token

This will return information similar to the following:

Screen Shot 2017-09-12 at 10.38.19

This command could be used along with a credentials object in a scheduled task to perform daily checks against vROps in a script format. If the variable is set by the command such as $notestatus then $nodestatus.status would quickly and easily allow you to retrieve the status of your vROps nodes without needing to open up a browser

Getting specific property information about an object

As interesting as retrieving the status of your vROps cluster is, that is far from the most interesting thing that can be achieved with PowervROPs. The scenario is to retrieve whether vSphere HA is enabled on a specific cluster. Now this information can be retrieved in many different ways and this is by far the most efficient (that’s what PowerCLI is for….). However, it shows what can be achieved via PowervROps.

There are a number of stages necessary in order to retrieve this information

  1. We need to obtain the ID of the object we want to query (the GUID that you see in the browser window when viewing the object in the vROps UI)
  2. We then need to get the specific property we are interested in from that object

Obtain the resources vROps ID

To get a resource we use the getResources cmdlet. Along with the standard arguments used in all of the cmdlets this has additional arguments for ‘name’, ‘resourceKind’ and ‘objectID’ which can be used to get a specific resource. This cmdlet can also be used to get all cluster resources, or all resources that have a common name element. For now we are going to get the cluster object called ‘Cluster A’ and save it to the variable $cluster

$cluster = getResources -token $token -resthost $resthost -name 'Cluster A' -resourceKind 'ClusterComputeResource'

If we query the cluster object and get its members we can see what a vROps resource query returns:

Screen Shot 2017-09-12 at 10.58.02

To get at the actual cluster object we need to step through the resourceList element:

Screen Shot 2017-09-12 at 10.58.43

We’ll go through the resourceList element in further detail in a future post but for now what we are interested in is the identifier element which is the object ID within vROps. We can get at this ID directly via:

$cluster.resourceList.identifier

Get all properties

Whilst we are specifically interesting in the HA enabled property it is worth knowing how to retrieve all properties as it has the benefit of showing you how the property is named when it is returned via such a query:

$clusterproperties =getResourceProperties -resthost $resthost -token $token -objectid $cluster.resourceList.identifier

If we look at the members of this variable we can see there is an element called property and if we query that then we can see all of the properties for this object

Screen Shot 2017-09-12 at 11.09.42

Get the HA setting property

To get at the specific property via a single command then we need to alter it slightly

$clusterhaproperty = getResourceProperties -resthost $resthost -token $token -objectid $cluster.resourceList.identifier).property | where { $_.name -eq 'configuration|dasConfig|enabled' }

Screen Shot 2017-09-12 at 11.12.38

As you can see knowing what the name of property is comes in handy when querying it directly.

This is the end of the first part in this series, check back soon for additional instalments where we will look at (amongst other things), generating reports, adding properties to an object, creating new objects, creating custom groups and investigating supermetrics.

All posts in this series:

Using PowervROps cmdlets (part 1) – Introduction

Using PowervROps cmdlets (part 2) – Retrieving metrics from objects

Using PowervROps cmdlets (part 3) – Adding metrics and properties to objects

Using PowervROps cmdlets (part 4) – Working with objects

Using PowervROps cmdlets (part 5) – Working with relationships

Using PowervROps cmdlets (part 6) – Working with custom groups

Using PowervROps cmdlets (part 7) – Working with supermetrics

Using PowervROps cmdlets (part 8) – Working with reports

Using PowervROps cmdlets (part 9) – Working with alerts

 

 

PowervROPs – Powershell cmdlets for the vROps API

What started out as the functions that were written for a customer I was working with has become something of an obsession that has resulted in a full-scale PowerShell module that exposes various parts of the vROps API.

The module should not be seen as a replacement for the vROps cmdlets available within PowerCLI, more as a complementary set that were born out of the specific requirements of a customer, but have since evolved as additional functions have been written.

The module is available on GitHub at the following URL:

https://github.com/andydvmware/PowervROps

There are currently 41 functions within the module, and for the most part they accept all parameters as defined by the API.

Screen Shot 2017-08-21 at 14.32.07

Over the coming days/weeks I’m going to write a series of posts detailed some of the ways in which the module has been used, however some of the highlights of the current release include:

  • Ability to generate and then download reports
  • Ability to add metrics and properties to objects
  • Add, set and delete relationships
  • Create new resources (for example custom datacenter objects)
  • Creation and deletion of custom groups
  • Ability to start/stop monitoring of resources
  • Ability to mark/unmark resources as being maintained