[HorizonRestAPI] Trying some of those new funky Horizon 8 REST api’s

In my last post I promised to provide some examples of those new REST api’s in Horizon 8. A couple of things that I will show:

I have changed how I run my scripts a bit in that I decided to go even lazier and store my credentials in an xml file:

$credential = Get-Credential
$credential | Export-CliXml -Path 'C:\My\Path\cred.xml'

and in my script I retrieve them

$url = "https://pod1cbr1.loft.lab"

$credentials=Import-Clixml .\creds.xml
$username=($credentials.username).split("\")[1]
$domain=($credentials.username).split("\")[0]
$password=$credentials.password

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) 
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)


function Get-HRHeader(){
    param($accessToken)
    return @{
        'Authorization' = 'Bearer ' + $($accessToken.access_token)
        'Content-Type' = "application/json"
    }
}
function Open-HRConnection(){
    param(
        [string] $username,
        [string] $password,
        [string] $domain,
        [string] $url
    )

    $Credentials = New-Object psobject -Property @{
        username = $username
        password = $password
        domain = $domain
    }

    return invoke-restmethod -Method Post -uri "$url/rest/login" -ContentType "application/json" -Body ($Credentials | ConvertTo-Json)
}

function Close-HRConnection(){
    param(
        $accessToken,
        $url
    )
    return Invoke-RestMethod -Method post -uri "$url/rest/logout" -ContentType "application/json" -Body ($accessToken | ConvertTo-Json)
}

$accessToken = Open-HRConnection -username $username -password $UnsecurePassword -domain $Domain -url $url

Invoke-RestMethod -Method Get -uri "$url/rest/config/v1/ic-domain-accounts" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

[sta_anchor id=”sessions” unsan=”Sessions” /]

Sessions

The first call I will show is immediately one of the more important ones: session information. Currently only local sessions seem to be available so we’ll have to wait for global session information. This is the call I will use:

$sessions=Invoke-RestMethod -Method Get -uri "$url/rest/inventory/v1/sessions" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

with this result

So s lot of data but less directly readable results than the soap api’s but we do see all of it including deeper levels. For applications we do see something new though.

Yes that’s actually the local application that the user launched. In this case it was through a Global Entitlement named Global_Notepad so it’s not showing that. According to the soap api’s this should also be shown there but they never do as far as I know.

[sta_anchor id=”messages” /]

Messages

One of the other things that we can do is send messages. For this we need to create an variable with the following information:

{
  "message": "Sample Info Message",
  "message_type": "INFO",
  "session_ids": [
    "7cdd624f-37d1-46c1-ab96-695a5d13956f"
  ]
}

To make it more fun I will send a message to all my desktop sessions I put those first into an variable

$desktopsessions=$sessions | where {$_.session_type -eq "DESKTOP"}

and I will create the json like this

$json=@{
  "message"="Wouter is sending a message";
  "message_type"="WARNING";
  "session_ids"=$desktopsessions.id -as [string[]]
}

this I will convert to a json and use the Put method

$json=@{
  "message"="Wouter is sending a message";
  "message_type"="WARNING";
  "session_ids"=$desktopsessions.id -as [string[]]
}
$body = $json | ConvertTo-Json
Invoke-RestMethod -Method Post -uri "$url/rest/inventory/v1/sessions/action/send-message" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -body $body

As you see I get all status codes 200 back so I know it was a success and we do see that on the desktops as well.

[sta_anchor id=”machines” unsan=”Machines” /]

Machines

So getting all machines is as easy as 1,2,3 with /inventory/v1/machines.

$machines=Invoke-RestMethod -Method Get -uri "$url/rest/inventory/v1/machines" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

Not a lot of new data, just less things we don’t need.

[sta_anchor id=”reset” unsan=”Reset” /]

Reset

If you look good you’ll see that the machine I was showing is in the already used state. In my lab this happens because often I power down the lab while I still have some sessions running. Let’s reset this machine. What do we need for this first the api method and that’s /inventory/v1/machines/action/reset for requires:

Since I am far from fluent in REST api’s and json this took me a while to find out but I did it like this

$body=((Invoke-RestMethod -Method Get -uri "$url/rest/inventory/v1/machines" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)) | where {$_.state -eq "ALREADY_USED"}).id -as [string[]] | convertto-json
Invoke-RestMethod -Method Post -uri "$url/rest/inventory/v1/machines/action/reset" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -body $body

so I use the method to pull the machines, filter on the state being “ALREADY_USED”, take the id of this as a string and convert that to json. When select the body I need to add the quotes and straight brackets because if it is a single string the json won’t be usable json. I will show it later with multiple systems that it’s not needed with multiples.

$body=((Invoke-RestMethod -Method Get -uri "$url/rest/inventory/v1/machines" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken))  | where {$_.state -eq "AVAILABLE"}).id -as [string[]] | convertto-json
Invoke-RestMethod -Method Post -uri "$url/rest/inventory/v1/machines/action/reset" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -body $body

Horizon 8 released: Moar api’s!!

So yesterday every VMware EUC person was going wild because Horizon 8 was released. I won’t go into all the stuf that’s new because plenty of other folks have already done that (love the parentless instant clones though!). So what exactly are the new things looking from the API perspective? From the good old soap api’s I didn’t expect any changes and couldn’t find any either but a new api explorer page was published anyway. From the REST side a lot as changed. First of all here also a new api explorer page was published. Besides that an explanation of the API’s was actually posted on Techzone over here. On this page some excellent things can be found like there’s a swagger page now on your connection server: https://connectionserverfqdn/rest/swagger-ui.html as of now I haven’t found a way on the page itself to authenticate as you need an api key for the authorize button but that’s something I had requested anyway to make available.

But also a set of postman collections if that’s your preferred method to test api’s it has collections for all the Horizon releases that contained public rest api’s.

In the swagger ui it’s possible to browse all the api calls we can do and I’ll use that in later blog posts to actually do new things because I have seen a shitload of new possibilities!

 

[Horizon]Creating applications using PowerCLI

Something I didn’t handle previously was the creating of applications in Horizon. Since they are always hard wired to a farm or desktop it might happen that you need to re-create these so automation is preferred.

When looking at the api call for creating an application I find that we need to create an objetc of the type VMware.hv.ApplicationSpec

After defining this spec we’ll see that two objects are needed: Data and ExecutionData. This is also visible in the API Explorer.

Let’s define both of these and see what the options are.

Looking at the API explorer for Data only the name is actually required while for Executiondata only the Executablepath and the desktop or farm id is required

(going lazy here and using vmware.hv.helper to get the farmid)

And now I can create the application itself

[HorizonRestAPI] Handling Instant Clone Administrator accounts

One of the options already available using the Horizon REST API‘s is working with Instant Clone Administrators. In total there are 5 API calls available and I will give an explanation for al 5 on how to use them. As you can see you’ll run all of them against /rest/config/v1/ic-domain-accounts.

GET : for all Instant Clone Domain accounts

POST : to create a new Instant Clone Domain accounts

GET : To retreive a specific Instant Clone Domain account with it’s ID

PUT : to update an Instant Clone Domain account.

DELETE : To delete an Instant Clone Domain account

Getting Started

To start showing these I am starting with the same base that I used in my first blog post about the Horizon REST api’s:

$url = read-host -prompt "Connection server url" 
$username = read-host -prompt "Username" 
$password = read-host -prompt "Password" -AsSecureString 
$Domain = read-host -Prompt "Domain" 
$url = "https://pod1cbr1.loft.lab"


$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) 
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)


function Get-HRHeader(){
    param($accessToken)
    return @{
        'Authorization' = 'Bearer ' + $($accessToken.access_token)
        'Content-Type' = "application/json"
    }
}
function Open-HRConnection(){
    param(
        [string] $username,
        [string] $password,
        [string] $domain,
        [string] $url
    )

    $Credentials = New-Object psobject -Property @{
        username = $username
        password = $password
        domain = $domain
    }

    return invoke-restmethod -Method Post -uri "$url/rest/login" -ContentType "application/json" -Body ($Credentials | ConvertTo-Json)
}

function Close-HRConnection(){
    param(
        $accessToken,
        $url
    )
    return Invoke-RestMethod -Method post -uri "$url/rest/logout" -ContentType "application/json" -Body ($accessToken | ConvertTo-Json)
}

$accessToken = Open-HRConnection -username $username -password $UnsecurePassword -domain $Domain -url $url

Invoke-RestMethod -Method Get -uri "$url/rest/config/v1/ic-domain-accounts" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

[sta_anchor id=”get” unsan=”GET” /]

GET

The regular get is really straight forward, just invoke a get and you get the results.

Invoke-RestMethod -Method Get -uri "$url/rest/config/v1/ic-domain-accounts" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

As you can see I currently have 2 accounts configured.

[sta_anchor id=”post” unsan=”POST” /]

POST

With post we can configure a new Instant Clone Domain account. Let’s see what we need. According to the API explorer it looks like we need to supply a domain ID, password and account.

To get the domain ID we’ll actually need to do a GET against another url:

$domains=Invoke-RestMethod -Method Get -uri "$url/rest/external/v1/ad-domains" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

Now I will create the json that we’ll need to configure the account. The $data variable is just a regular powershell array that  afterwards convert to the actual json

$domainid=$domains |select-object -expandproperty id -first 1

$data=@{
ad_domain_id= $domainid;
password= "password";
username= "username"
}

$body= $data | ConvertTo-Json

Now let’s use the Post method to apply this

Oops, too slow let’s authenticate and try again

Invoke-RestMethod -Method Post -uri "$url/rest/config/v1/ic-domain-accounts" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -body $body

There are a few remarks about this: no propper error is returned when a wrong username and password is used. Wen you try to create an account that already exists it will return a 409 conflict.

[sta_anchor id=”post” unsan=”GETID” /]

GET with ID

This is straightforward again, just extend the url for the get with the ID of the account you want to get. I grabbed this from the regular pul request and filtered on the user account I just created

$icaccounts= Invoke-RestMethod -Method Get -uri "$url/rest/config/v1/ic-domain-accounts" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) 
$accountid=($icaccounts | where {$_.username -eq "username"}).id 
Invoke-RestMethod -Method Get -uri "$url/rest/config/v1/ic-domain-accounts/$accountid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

[sta_anchor id=”post” unsan=”PUT” /]

PUT

Put can be used to change a users password. It’s requires a combination of the url with the ID from the get with id and a body like in the Post.

$data=@{password="Demo-02"}
$body = $data | ConvertTo-Json
Invoke-RestMethod -Method Put -uri "$url/rest/config/v1/ic-domain-accounts/$accountid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -Body $body

[sta_anchor id=”post” unsan=”DELETE” /]

DELETE

To delete an account simply use the url with the id in it with the DELETE method

Invoke-RestMethod -Method Delete -uri "$url/rest/config/v1/ic-domain-accounts/$accountid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

 

[HorizonAPI] Getting started with the Horizon REST api

Until now all of my blogging about the Horizon api’s was about consuming the SOAP api using PowerCLI. Since a couple of releases Horizon also has a REST api and since 7.12 we are also able to change some settings using that. So now it’s time for me to dive into the Horizon REST api’s. I will consume them using Powershell since I am the most comfortable using that but you can use whatever method you prefer..

The REST api is just like the soap api documented at the VMware{CODE} api explorer.

First of all we need to create an accesstoken, we can do this by using some code that I simply stole from Andrew Morgan because why would I re-invent the wheel? From his git repository I grabbed three basic functions: get-HRHeader, Open-HRConnection and close-hrconnection. there’s also a refresh-hrconnection but I won’t need that for now.

function Get-HRHeader(){
    param($accessToken)
    return @{
        'Authorization' = 'Bearer ' + $($accessToken.access_token)
        'Content-Type' = "application/json"
    }
}

function Open-HRConnection(){
    param(
        [string] $username,
        [string] $password,
        [string] $domain,
        [string] $url
    )

    $Credentials = New-Object psobject -Property @{
        username = $username
        password = $password
        domain = $domain
    }

    return invoke-restmethod -Method Post -uri "$url/rest/login" -ContentType "application/json" -Body ($Credentials | ConvertTo-Json)
}

function Close-HRConnection(){
    param(
        $accessToken,
        $url
    )
    return Invoke-RestMethod -Method post -uri "$url/rest/logout" -ContentType "application/json" -Body ($accessToken | ConvertTo-Json)
}
$accessToken = Open-HRConnection -username $username -password $password -domain $Domain -url $url

But we can’t do anything with only these functions, somehow we also need to supply username and password

$url = read-host -prompt "Connection server url"
$username = read-host -prompt "Username"
$password = read-host -prompt "Password" -AsSecureString
$Domain = read-host -Prompt "Domain"

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

(I am grabbing it from the command line here but when I run the scripts I have my creds hardcoded to make my life for the duration of this blog post a bit easier)

Next up is actually getting some data. The first thing that I wil do is show the connection servers. This can be done with the following API call. The part after -uri “$url/rest/ is what you can find int he api explorer. The method is the method also shown in the api explorer.

Invoke-RestMethod -Method Get -uri "$url/rest/monitor/connection-servers" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

and the result:

Since one of the few things that you can already change using the rest api’s are the general settings I will take those as the next example

Invoke-RestMethod -Method Get -uri "$url/rest/config/v1/settings" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

This works but I can’t say that it’s really usable. Now this is not the first time I do something with REST api’s (haven’t done it a lot though to be honest) so I know this can easily be converted to json to make it visible. What I will do is that I put it in a variable first.

$settings=Invoke-RestMethod -Method Get -uri "$url/rest/config/v1/settings" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$settings | ConvertTo-Json

Now this DOES look usable! Let’s take a look what is under general_settings

$settings.general_settings

Let’s say I want to change the forced logoff message

$settings.general_settings.forced_logoff_message="Get lost, the Bastard Operator From Hell is here."

Now my variable has the change but I need to send this to the server. This can be done using a put method and the settings variable has to be added as json. The second line is to pull the new settings from my connection server showing it directly in a json format.

 

Invoke-RestMethod -Method Put -uri "$url/rest/config/v1/settings" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -body ($settings | ConvertTo-Json)
Invoke-RestMethod -Method Get -uri "$url/rest/config/v1/settings" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) | ConvertTo-Json

and in the admin interface:

That’s it for my 1ste blog post about the horizon REST api’s hopefully it’s useful! Below is an example of the script that I used.

$url = read-host -prompt "Connection server url" 
$username = read-host -prompt "Username" 
$password = read-host -prompt "Password" -AsSecureString 
$Domain = read-host -Prompt "Domain" 

#$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) 
#$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

function Get-HRHeader(){
    param($accessToken)
    return @{
        'Authorization' = 'Bearer ' + $($accessToken.access_token)
        'Content-Type' = "application/json"
    }
}
function Open-HRConnection(){
    param(
        [string] $username,
        [string] $password,
        [string] $domain,
        [string] $url
    )

    $Credentials = New-Object psobject -Property @{
        username = $username
        password = $password
        domain = $domain
    }

    return invoke-restmethod -Method Post -uri "$url/rest/login" -ContentType "application/json" -Body ($Credentials | ConvertTo-Json)
}

function Close-HRConnection(){
    param(
        $accessToken,
        $url
    )
    return Invoke-RestMethod -Method post -uri "$url/rest/logout" -ContentType "application/json" -Body ($accessToken | ConvertTo-Json)
}

$accessToken = Open-HRConnection -username $username -password $password -domain $Domain -url $url

Invoke-RestMethod -Method Get -uri "$url/rest/monitor/connection-servers" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)

[HorizonAPI] Registering a Composer Domain Administrator using the api’s

A while ago I blogged about adding an Instant Clone administrator using the api’s. I never looked at creating a linked clone domain administrator though so let’s do that.

When checking the services near the bottom we see a service called ViewComposerDomainAdministrator

Now let’s check the available methods

The difference between ViewComposerDomainAdministrator_Create and ViewComposerDomainAdministrator_CreateByServerDefinition is that for the first you’ll need the virtualcenterid and for the lather the ServerDefinition for the configured vCenter.I will go with the easier first one.

Let’s see what’s required

so we need a spec of the type VMware.Hv.ViewComposerDomainAdministratorSpec this is what the api explorer says about it:

So for the base we actually need another object of the type vmware.hv.ViewComposerDomainAdministratorBase, let’s create both

$spec=new-object  vmware.hv.viewcomposerdomainadministratorspec
$spec.base=new-object VMware.Hv.viewcomposerDomainAdministratorBase

The virtualCenterID is only available by doing a virtualcenter.virtualcenter_list() with a where on the results

$vcenter="pod2vcr1.loft.lab"
$vcenters = $services.virtualcenter.virtualcenter_list()
$vcenterid = ($vcenters.where{$_.serverSpec.serverName -eq $vcenter}).id
$spec.VirtualCenter = $vcenterid

see how I do the where? For this one it doesn’t really matter but doing it this way is muchos faster than using where-object

In the base the username and domain are strings so those are easy. For the password we need to have it encrypted in a certain way. Luckily I already used it in the vCenter adding post that I gave an update last week.

$spec.base.Username = "m_wouter"
$spec.Base.Domain = "loft.lab"
$cmpdomainadminpassword=read-host "Composer domain administrator password?" -assecurestring
$temppw = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($cmpdomainadminpassword)
$PlaincmpdomainadminPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($temppw)
$cmpdomainadminencPassword = New-Object VMware.Hv.SecureString
$enc = [system.Text.Encoding]::UTF8
$cmpdomainadminencPassword.Utf8String = $enc.GetBytes($PlaincmpdomainadminPassword)
$spec.base.password=$cmpdomainadminencPassword

And we bring all of this together by creating the administrator

$services.ViewComposerDomainAdministrator.ViewComposerDomainAdministrator_Create($spec)

To match the post adding vCenter servers I have put all of this together in a nice script, you just need to connect to the connection server first

$hvServer = $global:DefaultHVServers[0]
$services=  $hvServer.ExtensionData

# Create required objects

$spec=new-object  vmware.hv.viewcomposerdomainadministratorspec
$spec.base=new-object VMware.Hv.viewcomposerDomainAdministratorBase
$spec.base.Username = "m_wouter"
$spec.Base.Domain = "loft.lab"
$vcenter="pod2vcr1.loft.lab"
$vcenters = $services.virtualcenter.virtualcenter_list()
$vcenterid = ($vcenters.where{$_.serverSpec.serverName -eq $vcenter}).id
$spec.VirtualCenter = $vcenterid
$cmpdomainadminpassword=read-host "Composer domain administrator password?" -assecurestring
$temppw = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($cmpdomainadminpassword)
$PlaincmpdomainadminPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($temppw)
$cmpdomainadminencPassword = New-Object VMware.Hv.SecureString
$enc = [system.Text.Encoding]::UTF8
$cmpdomainadminencPassword.Utf8String = $enc.GetBytes($PlaincmpdomainadminPassword)
$spec.base.password=$cmpdomainadminencPassword




# This will create the View Composer Domain Admin
$services.ViewComposerDomainAdministrator.ViewComposerDomainAdministrator_Create($spec)

 

 

[Update 23-04-2020]Adding vCenter server to Horizon View using the api’s

Update

I don’t know since what version but somewhere this script stopped working because VMware change some things. In 7.8 there was a change about the thumbprint algorithm to DER_BASE64_PEM so it might have started there. Another change is that in the sslcertthumbprint field they stopped using the thumbprint but actually add the entire certificate.

What is needed to fix this?

Replace:

$spec.CertificateOverride=($services.Certificate.Certificate_Validate($spec.serverspec)).thumbprint

with

$spec.CertificateOverride.SslCertThumbprint=($services.Certificate.Certificate_Validate($spec.serverspec)).certificate
$spec.CertificateOverride.sslCertThumbprintAlgorithm = "DER_BASE64_PEM"

and you should be good. I have already updated the version of the script below.

A big thank you to Mark Brookfield for asking me about this

/update

Yesterday Sean Massey (https://thevirtualhorizon.com/) asked me if it was possible to add a vCenter server + some other things to Horizon View using the api’s. With a quick look at the api explorer I confirmed this should be possible. The other things he asked I will put in a separate blogpost.

It looks like a simple matter of building the spec and I should be good. In the end it turned out to be a bit more work then expected. Some items are not required according to the api explorer but should at least be called in the spec (set them to something empty) while others can safely be left away. The automatic generated ssl certs in my lab also turned out to be a pita. First I copied them from a current spec and later I downloaded the certificate on the Connection server itself and read that cert. Andrew Morgan (http://andrewmorgan.ie/)from VMware helped me out with this by showing their internal script that they use. It turned out that except for the SSL certs I was on the right path. As usual I will add this functionality to the vmware.hv.helper but since that might take a while I decided to create a useful script

$hvServer = $global:DefaultHVServers[0]
$services=  $hvServer.ExtensionData

# Create required objects

$spec=new-object VMware.Hv.VirtualCenterSpec
$spec.serverspec=new-object vmware.hv.serverspec
$spec.viewComposerData=new-object VMware.Hv.virtualcenterViewComposerData

$spec.Certificateoverride=new-object vmware.hv.CertificateThumbprint
$spec.limits=new-object VMware.Hv.VirtualCenterConcurrentOperationLimits
$spec.storageAcceleratorData=new-object VMware.Hv.virtualcenterStorageAcceleratorData

# vCenter Server specs

$spec.ServerSpec.servername="pod2vcr1.loft.lab"        # Required, fqdn for the vCenter server
$spec.ServerSpec.port=443                                 # Required
$spec.ServerSpec.usessl=$true                             # Required
$spec.ServerSpec.username="administrator@vsphere.local"   # Required user@domain
$vcpassword=read-host "vCenter User password?" -assecurestring
$temppw = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($vcPassword)
$PlainvcPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($temppw)
$vcencPassword = New-Object VMware.Hv.SecureString
$enc = [system.Text.Encoding]::UTF8
$vcencPassword.Utf8String = $enc.GetBytes($PlainvcPassword)
$spec.ServerSpec.password=$vcencPassword
$spec.ServerSpec.servertype="VIRTUAL_CENTER"

# Description & Displayname, neither is required to be set

#$spec.description="description"              # Not Required
#$spec.displayname="virtualcenterdisplayname" # Not Required
$spec.CertificateOverride=($services.Certificate.Certificate_Validate($spec.serverspec)).thumbprint
$spec.CertificateOverride.SslCertThumbprint=($services.Certificate.Certificate_Validate($spec.serverspec)).certificate
$spec.CertificateOverride.sslCertThumbprintAlgorithm = "DER_BASE64_PEM"


# Limits
# Only change when you want to change the default values. It is required to set these in the spec

$spec.limits.vcProvisioningLimit=20
$spec.Limits.VcPowerOperationsLimit=50
$spec.limits.ViewComposerProvisioningLimit=12
$spec.Limits.ViewComposerMaintenanceLimit=20
$spec.Limits.InstantCloneEngineProvisioningLimit=20

# Storage Accelerator data

$spec.StorageAcceleratorData.enabled=$false
#$spec.StorageAcceleratorData.DefaultCacheSizeMB=1024   # Not Required

# Cmposer
# most can be left empty but they need to be set otherwise you'll get a xml error

$spec.ViewComposerData.viewcomposertype="STANDALONE"  # DISABLED for none, LOCAL_TO_VC for installed with the vcenter and STANDALONE for s standalone composer


if ($spec.ViewComposerData.viewcomposertype -ne "DISABLED"){
    $spec.ViewComposerData.ServerSpec=new-object vmware.hv.serverspec
    $spec.ViewComposerData.CertificateOverride=new-object VMware.Hv.CertificateThumbprint
    $cmppassword=read-host "Composer user password?" -assecurestring
    $temppw = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($cmpPassword)
    $PlaincmpPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($temppw)
    $cmpencPassword = New-Object VMware.Hv.SecureString
    $enc = [system.Text.Encoding]::UTF8
    $cmpencPassword.Utf8String = $enc.GetBytes($PlaincmpPassword)
    $spec.ViewComposerData.ServerSpec.password=$cmpencPassword
    $spec.ViewComposerData.ServerSpec.servername="pod2cmp1.loft.lab"
    $spec.ViewComposerData.ServerSpec.port=18443
    $spec.ViewComposerData.ServerSpec.usessl=$true
    $spec.ViewComposerData.ServerSpec.username="m_wouter@loft.lab"
    $spec.ViewComposerData.ServerSpec.servertype="VIEW_COMPOSER"

    $spec.ViewComposerData.CertificateOverride=($services.Certificate.Certificate_Validate($spec.ViewComposerData.ServerSpec)).thumbprint
    $spec.ViewComposerData.CertificateOverride.sslCertThumbprint = ($services.Certificate.Certificate_Validate($spec.ViewComposerData.ServerSpec)).certificate
    $spec.ViewComposerData.CertificateOverride.sslCertThumbprintAlgorithm = "DER_BASE64_PEM"
}


# Disk reclamation, this is required to be set to either $false or $true
$spec.SeSparseReclamationEnabled=$false 

# This will create the connection
$services.VirtualCenter.VirtualCenter_Create($spec)

 

Looking at the output it will only ask for the vCenter user’s password and if a Composer server is set for that user’s password.

 

[HorizonAPI] Creating Entitlements

So last week I created a blog about gathering Horizon entitlements using the api’s. At the end I promised that my next blog post would be about creating entitlements and guess what: that’s this post 🙂

First a short explanation about what UserEntitlements actually are in Horizon. When you pull the entitlement info the base property has the needed information.

So in short an entitlement is a link between the userorgroup object id and a resource object id. The resource object can be: Application, Desktop, Global Application Entitlement, Global Desktop Entitlement and URLRedirection.

Let’s first grab the id’s that we need, I use 2 queries for that bur first I put the names of the group and the desktop in variables:

$groupname = "example_group"
$poolname = "pod01_pool01"

Than I create two objects called $group and $pool using queries.

$queryService = New-Object VMware.Hv.QueryServiceService
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryEntityType = 'ADUserOrGroupSummaryView'
$defn.Filter = New-Object VMware.Hv.QueryFilterEquals -property @{'memberName'='base.name'; 'value' = "$groupname"}
$group= ($queryService.queryService_create($HVService, $defn)).results
$queryService.QueryService_DeleteAll($HVService)

$queryService = New-Object VMware.Hv.QueryServiceService
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryEntityType = 'DesktopSummaryView'
$defn.Filter = New-Object VMware.Hv.QueryFilterEquals -property @{'memberName'='desktopSummaryData.displayName'; 'value' = "$Poolname"}
$pool= ($queryService.queryService_create($HVService, $defn)).results
$queryService.QueryService_DeleteAll($HVService)

Next we create the object to link them together.

$userentitlement= new-object VMware.Hv.UserEntitlementBase
$userentitlement.UserOrGroup = $group.id
$userentitlement.Resource = $pool.id

And we create the actual entitlement, since the output we get from this is the id of the entitlement object I store this in a variable to show you the entitlement in the next step.

and to show the entitlement

($hvservice.UserEntitlement.UserEntitlement_Get($newentitlement)).base

If you want to create entitlements for other resource you’ll need to use the either of the following to build your query:

Name Data object property to filter on
Application ApplicationInfo data.displayName
Desktop DesktopSummaryView DesktopSummaryData.displayName
Global Application Entitlement GlobalApplicationEntitlementInfo base.displayName
Global Desktop Entitlement GlobalEntitlementInfo base.displayName

There is no query for the URLRedirection so you’ll need to use URLRedirection.URLRedirection_List() to get the entire list and select the right one from that.

This is a complete example script that you could use to create a desktop entitlement:

Import-Module VMware.VimAutomation.HorizonView
Import-Module VMware.VimAutomation.Core

$cs = 'pod1cbr1.loft.lab'
$groupname = "example_group"
$poolname = "pod01_pool01"

$hvServer = Connect-HVServer -Server $cs 

$HVService= $hvServer1.ExtensionData

$queryService = New-Object VMware.Hv.QueryServiceService
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryEntityType = 'ADUserOrGroupSummaryView'
$defn.Filter = New-Object VMware.Hv.QueryFilterEquals -property @{'memberName'='base.name'; 'value' = "$groupname"}
$group= ($queryService.queryService_create($HVService, $defn)).results
$queryService.QueryService_DeleteAll($HVService)

$queryService = New-Object VMware.Hv.QueryServiceService
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryEntityType = 'DesktopSummaryView'
$defn.Filter = New-Object VMware.Hv.QueryFilterEquals -property @{'memberName'='desktopSummaryData.displayName'; 'value' = "$Poolname"}
$pool= ($queryService.queryService_create($HVService, $defn)).results
$queryService.QueryService_DeleteAll($HVService)

$userentitlement= new-object VMware.Hv.UserEntitlementBase
$userentitlement.UserOrGroup = $group.id
$userentitlement.Resource = $pool.id
$hvservice.UserEntitlement.UserEntitlement_Create($userentitlement)

[HorizonAPI] Pulling entitlement information using the api’s

Somehow I have never really blogged about using the Horizon api’s to gather entitlement data. These are actually stored in entitlement objects and we can find them using a query against either the EntitledUserOrGroupLocalSummaryView or EntitledUserOrGroupGlobalSummaryView objects. Let’s start with the local variety.

$queryService = New-Object VMware.Hv.QueryServiceService
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryEntityType = 'EntitledUserOrGroupLocalSummaryView'
$queryResults= ($queryService.queryService_create($HVservice, $defn)).results
$queryService.QueryService_DeleteAll($HVservice)
$queryresults

So we have some property’s and the ID is the easiest one to use since it’s of the VMware.Hv.UserOrGroupId type that we can resolve using aduserorgroup.aduserorgroup_GetInfos(arrayofids)

$hvservice.ADUserOrGroup.ADUserOrGroup_GetInfos($queryResults.id)

and the name is visible using base.displayname

($hvservice.ADUserOrGroup.ADUserOrGroup_GetInfos($queryResults.id)).base.displayname

$

Yes that’s me making a typo, try to talk to me on Slack. I hardly type anything without typo’s. Back to the $queryresults because there’s an easier way to get the group or username because it’s listed under the base property.

$queryresults.base

or

So we now have the group or username now we need to find what they have been entitled to, this information is stored under localdata.

$queryresults.localdata

The Applications and Desktops properties contain the ids where the users have rights to so if we use Desktop.Desktop_GetSummaryViews or Application_GetSummaryViews we end up with the relevant data. I have opened the summarydata for both to make things more visible.

($hvservice.Desktop.Desktop_GetSummaryViews($queryResults.localdata.desktops)).desktopsummarydata
($hvservice.Application.Application_GetSummaryViews($queryResults.localdata.applications)).applicationsummarydata

To create a nice overview of this I have created a small script

$queryService = New-Object VMware.Hv.QueryServiceService
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryEntityType = 'EntitledUserOrGroupLocalSummaryView'
$queryResults= ($queryService.queryService_create($HVservice, $defn)).results
$queryService.QueryService_DeleteAll($HVservice)
$entitlements=@()
foreach ($queryresult in $queryresults){
    $userorgroupname = $queryresult.base.displayname
    $group = $queryresult.base.group
    $desktops=@()
    if ($queryresult.localdata.desktops){
        foreach ($desktop in $queryresult.localdata.desktops){
            $desktops+=($hvservice.desktop.desktop_get($desktop)).base.name
        }
    }
    $applications=@()
    if ($queryresult.localdata.applications){
        foreach ($application in $queryresult.localdata.applications){
            $applications+=($hvservice.application.application_get($application)).data.name
        }
    }
    $entitlements+=New-Object PSObject -Property @{
        "Name" = $userorgroupname;
        "group" = $group;
        "desktops" = $desktops;
        "applications" = $applications;
    }
}
$entitlements | select-object Name,group,desktops,applications

as you can see user1 is the lucky SoB that I test everything on.

The difference with global entitlements is that the localdata property is replaced bij globaldata.

$queryService = New-Object VMware.Hv.QueryServiceService
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryEntityType = 'EntitledUserOrGroupGlobalSummaryView'
$queryResults= ($queryService.queryService_create($HVservice, $defn)).results
$queryService.QueryService_DeleteAll($HVservice)
$queryresults

And the entitlements are named a bit different

$queryresults.globaldata

To rebuild the script for global entitlements it needed a bit of tinkering but here it is

$queryService = New-Object VMware.Hv.QueryServiceService
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryEntityType = 'EntitledUserOrGroupGlobalSummaryView'
$queryResults= ($queryService.queryService_create($HVservice, $defn)).results
$queryService.QueryService_DeleteAll($HVservice)
$entitlements=@()
foreach ($queryresult in $queryresults){
    $userorgroupname = $queryresult.base.displayname
    $group = $queryresult.base.group
    $desktops=@()
    if ($queryresult.globaldata.GlobalEntitlements){
        foreach ($desktop in $queryresult.globaldata.GlobalEntitlements){
            $desktops+=($hvservice.GlobalEntitlement.GlobalEntitlement_Get($desktop)).base.displayname
        }
    }
    $applications=@()
    if ($queryresult.globaldata.GlobalApplicationEntitlements){
        foreach ($application in $queryresult.globaldata.GlobalApplicationEntitlements){
            $applications+=($hvservice.GlobalApplicationEntitlement.GlobalApplicationEntitlement_Get($application)).base.displayname
        }
    }
    $entitlements+=New-Object PSObject -Property @{
        "Name" = $userorgroupname;
        "group" = $group;
        "desktops" = $desktops;
        "applications" = $applications;
    }
}
$entitlements | select-object Name,group,desktops,applications

So here you have the ways to retrieve information about entitlements, locally and globally. Next post will be about creating entitlements.

[HorizonAPI] Configuring the Horizon event database in code

Last week Mark Brookfield asked the question if it is possible to configure the event database in code. My answer was that I thought it should be possible until Stephen Jesse pointed me to the the vmware.hv.helper where there is the set-hveventdatabase cmdlet for this. When looking at the code I noticed something familiar:

.NOTES
Author                      : Wouter Kursten
Author email                : wouter@retouw.nl
Version                     : 1.0

===Tested Against Environment====
Horizon View Server Version : 7.4
PowerCLI Version            : PowerCLI 10
PowerShell Version          : 5.0

So that’s why I knew it was possible! A good reason to create a quick blogpost though. Mark made a nice script for himself with variables and all those fancy things but I just want to quickly show how you can do it.

$hvedbpw=read-host -AsSecureString
$temppw=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($hvedbpw)
$PlainevdbPassword=[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($temppw)
$dbupassword=New-Object VMware.Hv.SecureString
$enc=[system.Text.Encoding]::UTF8
$dbupassword.Utf8String=$enc.GetBytes($PlainevdbPassword)
$eventservice=new-object vmware.hv.eventdatabaseservice
$eventservicehelper=$eventservice.getEventDatabaseInfoHelper()
$eventsettings=new-object VMware.Hv.EventDatabaseEventSettings
$eventdatabase=new-object VMware.Hv.EventDatabaseSettings
$eventsettings.ShowEventsForTime="TWO_WEEKS"
$eventsettings.ClassifyEventsAsNewForDays=2
$eventdatabase.Server="labsql01.magneet.lab"
$eventdatabase.type="SQLSERVER"
$eventdatabase.port=1433
$eventdatabase.name="pod1_events"
$eventdatabase.username="sa_view"
$eventdatabase.password=$dbupassword
$eventservicehelper.setDatabase($eventdatabase)
$eventservicehelper.setsettings($eventsettings)
$eventservice.update($hvservice,$eventservicehelper)

The first three line make it possible to not use a plaintext password. If you don’t care about that you can remove those and declare something for $plainevdbpassword.

For the $eventsettings.ShowEventsForTime for time there are several options (same as in the gui) these are:

ONE_WEEK,TWO_WEEKS,THREE_WEEKS,ONE_MONTH,TWO_MONTHS,THREE_MONTHS,SIX_MONTHS
Yes, they are all in capitals!

To show how this works I will first clear the current database.

$hvservice.EventDatabase.EventDatabase_Clear()
$hvservice.EventDatabase.EventDatabase_Get()

Yes this is one of those exceptions where a service_get doesn’t need an id.

Now I run the script with a new _get to show the results.

If you are interested in the details: