Search Results for: horizon

[HorizonAPI]Finding VDI or RDS machines based on wrong/old Golden Image

One of the first thing I did years ago when I first learned of the Horizon API’s was to start working on the vCheck for Horizon as I at that point was managing a Horizon 6.2* environment with lots of pools and lots of issues. With the vCheck I didn’t need to log into all pod’s anymore and nor did I need to check each and every pool after a recompose if all desktops had the correct image. Last week Guy Leech asked me if there was a script that could do this for RDS farms as he was working on a script that has to do with App Volumes & RDS hosts. I was like hell yeah we have that but when I looked at the vCheck and had to admit that it was a actually a hell no.

So after creating a new RDS image that could be used with Instant Clones this week it was time to create that vCheck. This morning and I even splashed a bug in the VDI wrong snapshot check when a Desktop Pool doesn’t have any machines in it. This led to this tweet that you might have seen:

SO what is actually the magic behind these checks? To be honest it is rather simple as the names of both the VM and the Snapshot in use are embedded in object both on pool/farm level and in the machine objects themselves.

First I connect to the connection server so we’ll use a credentials file and I also define 2 variables that we will use later

$hvconserver="pod2cbr1.loft.lab"
$credsfile="D:\homelab\creds.xml"

$creds=Import-Clixml $credsfile

$hvserver=connect-hvserver -Server $hvconserver -Credential $creds
$hvservice=$hvserver.ExtensionData
$wrongsnapdesktops=@()
$wrongsnaphosts=@()

After this I use 2 query’s to gather Pool and Farm information. The summaryviews don’t contain the needed information so I have to use farm.farm_get with the id to get what we need.

# --- Get Desktop pools
$poolqueryservice=new-object vmware.hv.queryserviceservice
$pooldefn = New-Object VMware.Hv.QueryDefinition
$pooldefn.queryentitytype='DesktopSummaryView'
$poolqueryResults = $poolqueryService.QueryService_Create($hvservice, $pooldefn)
$pools = foreach ($poolresult in $poolqueryResults.results){$hvservice.desktop.desktop_get($poolresult.id)}
$poolqueryservice.QueryService_DeleteAll($hvservice)
# --- Get RDS Farms

$Farmqueryservice=new-object vmware.hv.queryserviceservice
$Farmdefn = New-Object VMware.Hv.QueryDefinition
$Farmdefn.queryentitytype='FarmSummaryView'
$FarmqueryResults = $FarmqueryService.QueryService_Create($hvservice, $Farmdefn)
$farms = foreach ($farmresult in $farmqueryResults.results){$hvservice.farm.farm_get($farmresult.id)}
$Farmqueryservice.QueryService_DeleteAll($hvservice)

So how does this look?

and inside the automateddesktopdata and automatedfarmdata we find a property called virtualcenternamesdata that has what we need

Next I will create object for both the first farm and the first pool to show what where we need to look for in the vdi/machine objects

$queryservice=new-object vmware.hv.queryserviceservice
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryentitytype='MachineSummaryView'
$defn.filter = New-Object VMware.Hv.QueryFilterEquals -Property @{ 'memberName' = 'base.desktop'; 'value' = $pool.id }
$queryResults = $queryService.QueryService_Create($hvservice, $defn)
$poolmachines=$hvservice.machine.machine_getinfos($queryResults.results.id)


$queryservice=new-object vmware.hv.queryserviceservice
$defn = New-Object VMware.Hv.QueryDefinition
$defn.queryentitytype='RDSServerInfo'
$defn.filter = New-Object VMware.Hv.QueryFilterEquals -Property @{ 'memberName' = 'base.farm'; 'value' = $farm.ID }
$queryResults = $queryService.QueryService_Create($hvservice, $defn)
$farmmachines=$queryresults.results

As you can see I take an extra step for the desktops as the information that we need is not visible in the MachineSummaryView and the MachineDetailsView is a mess to run query’s for. The VDI machines have the GI and snapshot data stored in $machines.managedachinedata.viewcomposerdata (yes also for Instant Clones) while the rds hosts have it stored in RdsServerMaintenanceData.

After this it’s a matter of combining that information into a nice script that will grab it all for you.

$hvconserver="pod2cbr1.loft.lab"
$credsfile="D:\homelab\creds.xml"

$creds=Import-Clixml $credsfile

$hvserver=connect-hvserver -Server $hvconserver -Credential $creds
$hvservice=$hvserver.ExtensionData
$wrongsnapdesktops=@()
$wrongsnaphosts=@()

# --- Get Desktop pools
$poolqueryservice=new-object vmware.hv.queryserviceservice
$pooldefn = New-Object VMware.Hv.QueryDefinition
$pooldefn.queryentitytype='DesktopSummaryView'
$poolqueryResults = $poolqueryService.QueryService_Create($hvservice, $pooldefn)
$pools = foreach ($poolresult in $poolqueryResults.results){$hvservice.desktop.desktop_get($poolresult.id)}
$poolqueryservice.QueryService_DeleteAll($hvservice)
# --- Get RDS Farms

$Farmqueryservice=new-object vmware.hv.queryserviceservice
$Farmdefn = New-Object VMware.Hv.QueryDefinition
$Farmdefn.queryentitytype='FarmSummaryView'
$FarmqueryResults = $FarmqueryService.QueryService_Create($hvservice, $Farmdefn)
$farms = foreach ($farmresult in $farmqueryResults.results){$hvservice.farm.farm_get($farmresult.id)}
$Farmqueryservice.QueryService_DeleteAll($hvservice)




foreach ($pool in $pools){
  $poolname=$pool.base.name

  if ($pool.type -like "*automated*"){
    $queryservice=new-object vmware.hv.queryserviceservice
    $defn = New-Object VMware.Hv.QueryDefinition
    $defn.queryentitytype='MachineSummaryView'

    $defn.filter = New-Object VMware.Hv.QueryFilterEquals -Property @{ 'memberName' = 'base.desktop'; 'value' = $pool.id }

        $queryResults = $queryService.QueryService_Create($hvservice, $defn)

    if ($queryResults.results.count -ge 1){
      $poolmachines=$hvservice.machine.machine_getinfos($queryResults.results.id)
      $wrongsnaps=$poolmachines | where {$_.managedmachinedata.viewcomposerdata.baseimagesnapshotpath -notlike  $pool.automateddesktopdata.VirtualCenternamesdata.snapshotpath -OR $_.managedmachinedata.viewcomposerdata.baseimagepath -notlike $pool.automateddesktopdata.VirtualCenternamesdata.parentvmpath}
      if ($wrongsnaps){
        foreach ($wrongsnap in $wrongsnaps){
          $wrongsnapdesktops+= New-Object PSObject -Property @{
            "VM Name" = $wrongsnap.base.name;
            "VM Snapshot" = $wrongsnap.managedmachinedata.viewcomposerdata.baseimagesnapshotpath;
            "VM GI" = $wrongsnap.managedmachinedata.viewcomposerdata.baseimagepath;
            "Pool Snapshot" = $pool.automateddesktopdata.VirtualCenternamesdata.snapshotpath;
            "Pool GI" = $pool.automateddesktopdata.VirtualCenternamesdata.parentvmpath;
          }
        }
      }
    }
    $hvservice.QueryService.QueryService_DeleteAll()
  }
}

foreach ($farm in $farms){
  $farmname=$farm.data.name

  if ($farm.type -like "*automated*"){
    $queryservice=new-object vmware.hv.queryserviceservice
    $defn = New-Object VMware.Hv.QueryDefinition
    $defn.queryentitytype='RDSServerInfo'

    $defn.filter = New-Object VMware.Hv.QueryFilterEquals -Property @{ 'memberName' = 'base.farm'; 'value' = $farm.ID }

    $queryResults = $queryService.QueryService_Create($hvservice, $defn)
    $farmmachines=$queryResults.Results
    if ($farmmachines.count -ge 1){
      $wrongsnaps=$farmmachines | where {$_.rdsservermaintenancedata.baseimagesnapshotpath -notlike  $farm.automatedfarmdata.VirtualCenternamesdata.snapshotpath -OR $_.rdsservermaintenancedata.baseimagepath -notlike $farm.automatedfarmdata.VirtualCenternamesdata.parentvmpath}
      if ($wrongsnaps){
        foreach ($wrongsnap in $wrongsnaps){
          $wrongsnaphosts+= New-Object PSObject -Property @{
            "RDS Name" = $wrongsnap.base.name;
            "VM Snapshot" = $wrongsnap.rdsservermaintenancedata.baseimagesnapshotpath;
            "VM GI" = $wrongsnap.rdsservermaintenancedata.baseimagepath;
            "Farm Snapshot" = $farm.automatedfarmdata.VirtualCenternamesdata.snapshotpath;
            "Farm GI" = $farm.automatedfarmdata.VirtualCenternamesdata.parentvmpath;
          }
        }
      
      }
      $hvservice.QueryService.QueryService_DeleteAll()
    }
  }
}
$wrongsnaphosts
$wrongsnapdesktops

Yes this is the same idea as what I use in the vCheck and what I will be using in the ControlUp Script Based Action that I will be creating soon.

 

Using the Horizon 8 swagger page

A couple weeks back when Horizon 8 was released they also made us happy with the Swagger page to browse the rest api methods. One thing it lacks though is a way to easily authenticate to actually try them. There is an Authenticate button but I couldn’t find any information on what it actually needs. While creating my previous blog post I was messing around with things and actually found a way to authenticate. First I tried to authenticate using the actual api method for that but trying any call afterwards still showed me as not being authenticated. You could copy/paste the access token though and you’ll see in the script how that might work, or check the 3rd screenshot.

the swagger can be found like this: https://loftcbr01.loft.lab/rest/swagger-ui.html

Let’s have a look at the script.

$url = read-host "url for connectionserver"

$username=read-host "Username"
$domain=Read-host "Domain"
$password=read-host "Password" -AsSecureString

$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)
}
try{
$accessToken = Open-HRConnection -username $username -password $UnsecurePassword -domain $Domain -url $url
Set-Clipboard (Get-HRHeader -accessToken $accessToken).Authorization
}
catch{
    write-host "Error while authenticating"
}

To make it directly usable I have chosen to ask for web address of the server, username, domain and password and in the end I copy the token you need to the clipboard for you. Let’s have a look at it

No further output but I can paste what I have in the clipboard now in the Authenticate field at the swagger page, hit authorize and close.

And now I can try api calls, pulling machines from the inventory for example.

SO that’s how we can actually use the Swagger page to try api calls.

[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)