Skip to content
adatum
  • Home
  •  About adatum
  •  Learn Azure Bicep
  •  SCOM Web API
vSphere logo Automation

First look at the vSphere 6.5 REST API

  • 04/03/201707/01/2025
  • by Martin Ehrnst

 

 

The other day I stumbled across  a blog series by William Lee who delves deep in to how you use the latest vmware vSphere REST API using PowerCLI. Using the language I know best, Powershell I thought I should give this API I try. I have some experience with API use from before as I often use this to do information exchange between systems, but this is my first experince with vCenter.

This post will cover the very basics on how we authenticate and get a list of all VM’s connected to our vCenter server.

You can explore and test all endpoints by this URL https://vcenter/rest/apiexplorer

To get started I declare two variables for the urls / endpoints we going to use. One for vm’s and one for the session endpoint

$VCBaseUri = "https://host/rest/vcenter/vm"
$SessionUri = "https://host/rest/com/vmware/cis/session"

Based on the credential input from the user we will create a base64 encoded string and create a header for the session endpoint.

#Getting cred and creating auth key
$Cred = Get-Credential
$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Cred.UserName+':'+$Cred.GetNetworkCredential().Password))
$head = @{
  'Authorization' = "Basic $auth"
}

The $head variable now contains a table with your encoded username and password. We will use this authorization header to create a new session. At first i assumed we could authenticate using basic authentication only but after a little investigation I figured we needed to create a session. vmware has documented the endpoint here

Using our authorization header we connect to the session endpoint and recieves a token that we use in our session header. From now on. All authentication is with this session token.

the key for our token is ‘vmware-api-session-id’

#Creating a Session

$token = (Invoke-RestMethod -Method Post -Headers $head -Uri $SessionUri).Value
$session = @{'vmware-api-session-id' = $token}

Finally you can call the VM endpoint and retrieve all your vms by running the following.

#Calling VM endpoint authenticated with the session

$vms = (Invoke-RestMethod -Uri $VCBaseUri -Headers $session -ContentType 'Application/json').Value

To get a single vm by name, you can filter by appending the uri.

/vm?filter.names=web-w2k12"

Hopefully you will have this output showing all vm’s as objects

vcenter api powershell vm output

 

My complete script now looks like this.

$VCBaseUri = "https://host/rest/vcenter/vm?filter.names=argaste-web-w2k12"
$SessionUri = "https://host/rest/com/vmware/cis/session"

#Getting cred and creating auth key
$Cred = Get-Credential
$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Cred.UserName+':'+$Cred.GetNetworkCredential().Password))
$head = @{
  'Authorization' = "Basic $auth"
}

#Creating a Session

$token = (Invoke-RestMethod -Method Post -Headers $head -Uri $SessionUri).Value
$session = @{'vmware-api-session-id' = $token}

#Calling VM endpoint authenticated with the session

$vms = (Invoke-RestMethod -Uri $VCBaseUri -Headers $session -ContentType 'Application/json').Value

 

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit
Automation

Playing with cognitive services

  • 16/01/201707/01/2025
  • by Martin Ehrnst

If you know what your users do or talk about you will likely have advantages over your competitors, or if you have support desk, you want to dispatch the ticket to the correct department as quickly as possible. To gain some insights you can use different AI/Machine learning tools to help you and ‘automatically’ perform actions.

Microsoft cognitive services is a set of APIs which let you do things like text analytics. I have played around a bit and found that I could pretty easy do a sentiment test (how ‘happy’ is the author) and a key phrase analysis (what is the text about). To do an analysis I needed to send the text in English. By living in Norway I am fortunate i many ways, but one of them is that Norwegian translate very good programmatically in to English

Since Microsoft (or Google and AWS) let’s us translate text through their translation API, you can in theory run text analysis on any language. I played around a bit and i managed to send some text through translation and in the end output a sentiment analysis and the key phrases. I set up the script in Azure Functions as well and it works pretty good.
To use it you will have to sign up for two Cognitive Services accounts in Azure, One for the Text Analytics API and one for the Translator API. In your Azure function you will have to set up the two API keys as variables.

The script is available on Github and it is totally a proof of concept without any error handling other than the APIs itself. Feel free to contribute to the code. Version when writing 0.5b

 

Here is an example on a text i found on a French news site.

Donald Trump a réaffirmé, lundi, ses positions critiques vis-à-vis de l’Otan, de l’UE, et de la politique d’accueil des migrants lors d’entretiens accordés à des médias européens. Une vision toujours proche de celle de Vladimir Poutine.

Une erreur catastrophique de Merkel sur l’accueil des migrants, l’Otan obsolète, le succès du Brexit qui marque le début de la fin de l’Union européenne. Si le fond ressemble à du Vladimir Poutine, la forme, elle, est clairement signée Donald Trump.

Lundi 16 janvier, à cinq jours de son investiture, le magnat de l’immobilier n’a pas mâché ses mots pour exposer ses vues sur les sujets d’actualité les plus brûlants sur le Vieux Continent, auprès des journaux britannique Times et allemand Bild.

Translated in to English

Donald Trump has r affirm, Monday, his criticism-screws – live NATO, the EU, and the migrant policy in interviews granted to European media. A vision still close to that of Vladimir Poutine.

A catastrophic error of Merkel on the reception of migrants, NATO MP4 you, the success of the Brexit brand the d to the end of the European Union. If the background looks like from Vladimir P
utin, the form, she is clearly sign e Donald Trump.

Monday, January 16, five days of his inauguration, the real estate mogul has no m ch her words to present its views on the topics of news the most br callers on the old Continent, aupr s of B
ritish newspapers Times and German Bild.

Not the best translation, but the analisys is quite OK

Sentiment Score : 87.73 %

Key phrases : Monday, Vladimir Putin, NATO MP4, Vladimir Poutine, criticism-screws - live NATO, aupr s of British newspapers Times, real estate mogul, end, European media, reception of migrants, m ch, old 
Continent, success, e Donald Trump, European Union, br callers, migrant policy, form, interviews, days, Brexit brand, inauguration, words, catastrophic error of Merkel, topics of news, German
Bild, background, January, vision

The tests done in Norwegian is pretty much spot on, and English analysis is just as you would expect.

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit
Automation

Sending SMS with Azure functions and Twilio

  • 23/12/201607/01/2025
  • by Martin Ehrnst

Update:

As pointed out by Tao Yang, storing the Twilio credentials in the script isnt exactly best practice.

pretty cool but the secret should at least be stored as application settings, not in clear text in the code. or even better – in Key Vault

— Tao Yang (@MrTaoYang) July 4, 2017

I have updated the script below to use Functions environment variables. You can create these from Settings>Manage Application settings 
[Fast publish]

Here the other day i “needed” to send a SMS when an alert was raised in Microsoft OMS. I already had a Twilio subscription so i developed a little script to send my self a text message. Later I put that script in a runbook in Azure Automation and called that from the alert. SMS received and it was all good.

Later the same evening i was trying out Azure Functions which let you run so called ‘server-less code’. Serverless or not, the code has to run on something, but you don’t need to maintain the infrastructure. I needed something to test Functions so i ported my Automation runbook in to a function.

The function accepts (in my environment) a webhook or sending a post with Json string.

And here is the code that does it. You will have to add your own Twilio config, but other than that it should work.

<#
    .DESCRIPTION
        Azure function sending SMS through Twilio.
        Depending on how you set up your function. This script will accept bot GET parameters through it's URL or a POST with JSON string sending phone and msg

        {
            "phone": "+4712345678",
            "msg": "www.adatum.no"
        }

        It will send the msg to the number you provide.

    .NOTES
        Requires an active twilio subscription and an azure functions container.
        Please add your Twilio sid, secret and phone number to the script

        Created by Martin Ehrnst
        www.adatum.no

    .CHANGELOG
        21.12.16: v1.0 initial release

#>

$requestBody = Get-Content $req -Raw | ConvertFrom-Json
$phone = $requestBody.phone
$msg = $requestBody.msg
$sid = $env:TwilioSID
$password = ConvertTo-SecureString -String $env:TwilioPASS -AsPlainText -Force
$uri = "https://api.twilio.com/2010-04-01/Accounts/$sid/Messages.json"
$from = $env:TwilioPhone

if ($req_query_phone) 
{
    $phone = $req_query_phone 
}

if ($req_query_msg) 
{
    $msg = $req_query_msg
}


$cred = New-Object System.Management.Automation.PsCredential($sid,$password)

$SMS = @{
    From=$from
    To=$phone
    Body=$Msg
}

$SMSEND = Invoke-RestMethod -Method Post -Uri $uri -Credential $Cred -Body $SMS
Out-File -Encoding Ascii -FilePath $res -inputObject "$smssend"

Here is a little example on how you configure your OMS alert to use it. The message contains a link to the alert search result.

Share this:

  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit

Posts pagination

1 … 3 4 5 6 7 … 9

Popular blog posts

  • Webinar: Multi-tenant resource management at scale with Azure Lighthouse
  • Azure Application registrations, Enterprise Apps, and managed identities
  • Azure Monitor Managed Prometheus
  • Azure token from a custom app registration
  • OpsMgr & External Services PT2

Categories

Automation Azure Azure Active Directory Azure Bicep Azure DevOps Azure Functions Azure Lighthouse Azure Logic Apps Azure Monitor Azure Policy Community Conferences CSP Monitoring DevOps GitHub Guest blogs Infrastructure As Code Kubernetes Microsoft CSP MPAuthoring OMS Operations Manager Podcast Powershell Uncategorised Windows Admin Center Windows Server

Follow Martin Ehrnst

  • X
  • LinkedIn

RSS feed RSS - Posts

RSS feed RSS - Comments

Microsoft Azure MVP

Martin Ehrnst Microsoft Azure MVP
Adatum.no use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it. Cookie Policy
Theme by Colorlib Powered by WordPress