Sorting bits into bytes...

VM latency sensitivity setting in vROps

So I was approached by one of my fellow vROps buddies @ ITQ. His customer is in need to get some advanced VM settings in vROps. So Kim asked me if I had any experience with that. Not with that particularly, but I’ve some experience in getting 3rd party data into vROps. With that I should be able to help out my fellow buddy.

So after some trial and error, here is a working (hehe) Powershell script that will lookup a VMs latency sensitivity setting and will send that to vROps as a nice custom property. For the Powershell script to work a internet connection is needed to download a module or you need to install the module manually. Here is a link to the module needed:

https://github.com/fgrehl/Virten.net.VimAutomation

Also don’t forget to check this blog:

https://vmusketeers.com/

There you will find cool content not only from Kim but also from other VMware rockstars!

 

<#

Author: Kabir Ali - info@kablog.nl
Scriptname: VM Latency Sensitivity (VMLS)
Version: 1.0 (Tested)
Date: Feb 2 2021
Why: Kim Bottu asked for it
Remark: Test setup
        vROPs Version: 8.2.0 (16949153)
        vCenter 6.7 U3

Example: .\VMLS.ps1 -vCenter "vCenter.local.domain" -vCenterUser "vCenterUser" -vCenterPass "vCenterPass" -vROPsServer "vROps.local.domain" -vROPsUser "vROPsUsername" -vROPsPass "vROPsPass"

#>

Param (
    
    [Parameter(Mandatory = $true)][string]$vCenter,
    [Parameter(Mandatory = $true)][string]$vCenterUser,
    [Parameter(Mandatory = $true)][string]$vCenterPass,
    [Parameter(Mandatory = $true)][string]$vROPsServer,
    [Parameter(Mandatory = $true)][string]$vROPsUser,
    [Parameter(Mandatory = $true)][string]$vROPsPass
)

# Functions are required
function ConvertTo-UnixTimestamp {
    $epoch = Get-Date -Year 1970 -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0	
 	$input | % {		
        $milliSeconds = [math]::truncate($_.ToUniversalTime().Subtract($epoch).TotalMilliSeconds)
        Write-Output $milliSeconds
    }	
}
function Get-TimeStamp {
    return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
}

### Define Defaults ###
# See Parameters

### vCenter Connection ###

# Lets connect to the vCenter
try {
  Connect-VIServer -Server $vCenter -User $vCenterUser -Password $vCenterPass
}
Catch {
  Write-Output "Failed to connect to the vCenter: $vCenter ... Exiting..."
  Exit
}


### vROPs API Connection ###

#Building vROPS API string & invoking REST API
$vROPsURL = "https://" + $vROPsServer + "/suite-api/api/"
$vROPsAuthURL = "https://" + $vROPsServer + "/suite-api/api/auth/token/acquire"
$Type = "application/json"
# Creating JSON for Auth Body
$AuthJSON =
"{
  ""username"": ""$vROPSUser"",
  ""password"": ""$vROPsPass""
}"
# Authenticating with API
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Try {
    $vROPSSessionResponse = Invoke-RestMethod -Method POST -Uri $vROPsAuthURL -Body $AuthJSON -ContentType $Type
}
Catch {
    $_.Exception.ToString()
    $error[0] | Format-List -Force
    Write-Output "Failed connecting to vROPs: $vROPsServer ... Exiting..."
    Exit
}
# Extracting the session ID from the response
$vROPSSessionHeader = @{"Authorization"="vRealizeOpsToken "+$vROPSSessionResponse.'auth-token'.token
"Accept"="application/json"}

# Install custom module
Try {
Install-Module -Name Virten.net.VimAutomation
}
Catch {
    $_.Exception.ToString()
    $error[0] | Format-List -Force
    Write-Output "Failed to install Virten module ... Exiting..."
    #Exit
}

### Generic Code ###

# Get VMs from vCenter
$vCenterVMs = Get-VM
# Generate output
write-host "Found a total of " $vCenterVMs.count "in vCenter: " $vCenter -ForegroundColor Green
# For every VM found in vCenter look up the data in vROps
foreach ($vCenterVM in $vCenterVMs) {
    # Just to be sure templates are excluded from the results or any other VMs that might misreport the latency setting
    $LatencySensitivity = $null
    # Get the latency settings from the VM
    $LatencySensitivity = (get-vm -name $vCenterVM.name | Get-VMLatencySensitivity).LatencySensitivity
        # If the latency setting is found, continue
        if ($LatencySensitivity -ne $null) {
            # Generate output
            write-host "VM:" $vCenterVM "has the following latency setting:" $LatencySensitivity -ForegroundColor Green
            # Build vROps URL based on VM name from vCenter
            $ResourcesURL = $vROpsURL+"resources?resourceKind=virtualmachine&name=" +$vCenterVM
            # Get data from vROps
            $vROpsVM = (Invoke-RestMethod -Method GET -Uri $ResourcesURL -Headers $vROpsSessionHeader -ContentType $Type).resourceList
            # Get timestamp to update vROps with
            $EpochTimeNow = (Get-Date | ConvertTo-UnixTimestamp)
            # Create the JSON reply to update vROps
            $JSONData='{
                "property-content" : [ {
                "statKey" : "Custom Properties|VM Latency Sensitivity",
                "timestamps" : ['+$EpochTimeNow+'],
                "values" : ["'+$LatencySensitivity+'"],
                "others" : [ ],
                "otherAttributes" : { }
                } ]
            }'
            # Try to add/update the custom metric
            Try {
                $TagJSONResponse = Invoke-RestMethod -Method POST -Body $JSONData -Uri ($vROpsURL+'resources/'+$vROpsVM.identifier+'/properties') -TimeoutSec 100 -Headers $vROpsSessionHeader -ContentType $Type
                $TagDetailedInfo = $TagJSONResponse.value
                write-host "Update successful on" $vCenterVM -ForegroundColor Green
                write-host "--- --- --- ---" -ForegroundColor Yellow
            }
            Catch {
                $_.Exception.ToString()
                $error[0] | Format-List -Force
                write-host "Update unsuccessful on" $vCenterVM -ForegroundColor Red
            }
        }
}

# Close sessions and done
write-host "All done" -ForegroundColor Green
Invoke-RestMethod -Method POST -Uri https://$vROpsServer/suite-api/api/auth/token/release -Headers $vROpsSessionHeader -ContentType $Type
Disconnect-VIServer -Server * -Confirm:$false

 

Thanks for reading and I hope this helps!

Leave a Reply