Skip to content
adatum
  • Home
  •  About adatum
  •  Learn Azure Bicep
  •  SCOM Web API
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

SCOM Alerts to Microsoft Teams and Mattermost

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

…or slack?

For a SCOM 2016 implementation I have worked around different methods to consume alerts. Keeping emails to an absolute minimum and add more smartness to alerts and incidents is one of the main goals.

On a daily basis we use custom dashboards created with SquaredUp and integrated this with our ticketing and CMDB systems, allowing us to create alert tickets directly from SCOM on the connected to the correct server/person/customer etc. (Sounds like a great blog post down the road)

On the concept side of things, it shouldnt matter what system you use to handle alerts as long as someone takes action on it. So in this blog post I will show how you can ‘interact’ or at least notify on alerts with two collaboration tools. Microsoft Teams and Mattermost.

This example uses SCOM as the alert source, but it could easially be another monitoring system, Solarwinds, OMS, Datadog etc.

The main technique involves Webhooks which i used when sending alerts to Azure Automation, and is somewhat the same thing we are doing here.

On a high level, this is what we are going through.

  • Creating Channels in MSFT Teams and Mattermost
  • enabling them to receive incoming webhooks
  • Create a new SCOM command channelAdd the PS script to send alerts

In teams, create a new channel by clicking the three bullets.( If you want to use an existing channel feel free).

After naming your channel, create a webhook for it by adding a new connector, and configure it.

Set a name and maybe an image, and remember to copy your URL.

 

In SCOM create a new command channel

You will ned the full path to powershell as the command file, which is:

C:\Windows\System32\WindowsPowershell\v1.0\Powershell.exe

And the startup folder

C:\Windows\System32\WindowsPowershell\v1.0\

The command line parameters are basicly a powershell script writtes as a ‘one-liner’ after the command parameter.

I will break it down for you here.

-executionpolicy Unrestricted -Command " &{Invoke-RestMethod -Method Post -Uri 'https://outlook.office365.com/webhook/************'

We are setting the execution policy and starting powershell with a command. The first “section” is a post to your webhook url.

Second, as the body i create a hash-table which holds our data and convert it to Json. For readability I have stripped down the code a little. We will insert data from SCOM here in the end.

-Body (ConvertTo-Json -InputObject @{'Title'='The title';'Text'='[View alert in SCOM Web console](https://scom)'}) -ErrorAction Stop}"

After you have created the command channel. Continue to add a new subscriber and a new subscription. When an alert matching your criteria is triggered you will se the following in your teams channel.

Success!

Mattermost: Using integrations from the menu. Create a new webhook assigned to the channel you want. Copy the webhook URL to use in your script, which for mattermost looks like this (should be somewhat equal to Slack). Not much changed from Teams.

 -Body (ConvertTo-Json -InputObject @{'text'='alertname [View alert in SCOM](https://yoururl)';'username'='SCOM Alerts'}) -ContentType application/json  -ErrorAction Stop}"

Please note that everything goes under ‘text’ and I have added a content type in our request as well an override for the poster username.

If all went well you should see a result like this:

Here are the two commands for each channel with SCOM data

Teams:

-executionpolicy Unrestricted -Command " &{Invoke-RestMethod -Method Post -Uri 'https://outlook.office365.com/*****' -Body (ConvertTo-Json -InputObject @{'Title'='$Data[Default='Not Present']/Context/DataItem/ManagedEntityPath$\$Data[Default='Not Present']/Context/DataItem/ManagedEntityDisplayName$ : $Data[Default='Not Present']/Context/DataItem/AlertName

Mattermost:

-executionpolicy Unrestricted -Command " &{Invoke-RestMethod -Method Post -Uri 'https://mattermost/hooks/*******' -Body (ConvertTo-Json -InputObject @{'text'='$Data[Default='Not Present']/Context/DataItem/AlertName$ : $Data[Default='Not Present']/Context/DataItem/ManagedEntityPath$\$Data[Default='Not Present']/Context/DataItem/ManagedEntityDisplayName$ [View alert in SCOM](https://URLid=$Data/Context/DataItem/AlertId$)';'username'='SCOM Alerts'}) -ContentType application/json  -ErrorAction Stop}"

Notes:

As you see I have put the scripts which handles the logic in a powershell onliner, inside a SCOM channel.

The next thin I want to do is to add more logic to the messages posted in Teams/Slack/Mattermost like taking actions etc.

To do this i will move the code out of scom and probably trigger an external script that does the logic. It could run serverless in azure functions, AWS Lambda, in azure automation, SMA or what ever you chose. I am looking to accomplish something like this and will of course let you know when its done.

from Slack documentation

References

https://msdn.microsoft.com/en-us/microsoft-teams/connectors

https://docs.mattermost.com/developer/webhooks-incoming.html

;'Text'='[View alert in SCOM Web console](https://URL/$Data/Context/DataItem/AlertId$)'}) -ErrorAction Stop}"

Mattermost:


Notes:

As you see I have put the scripts which handles the logic in a powershell onliner, inside a SCOM channel.

The next thin I want to do is to add more logic to the messages posted in Teams/Slack/Mattermost like taking actions etc.

To do this i will move the code out of scom and probably trigger an external script that does the logic. It could run serverless in azure functions, AWS Lambda, in azure automation, SMA or what ever you chose. I am looking to accomplish something like this and will of course let you know when its done.

from Slack documentation

References

https://msdn.microsoft.com/en-us/microsoft-teams/connectors

https://docs.mattermost.com/developer/webhooks-incoming.html

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

Popular blog posts

  • SCOM Alerts to Microsoft Teams and Mattermost
  • How to move Azure blobs up the path
  • Creating Azure AD Application using Powershell
  • SCOM and OMS: The agents
  • Azure Application registrations, Enterprise Apps, and managed identities

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