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

Using OMS and Azure Functions to restart Azure Web…

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

From time to time I have had problems with this blog and other sites running in Azure. Occasionally they throw HTTP 5XX errors and when it doesnt fix it self I will have to restart the web app. By using Operations Management Suite (OMS)  with the web app analytics solution added, I created an alert calling an Azure Function to restart the affected web app. It’s keeping the sites up until I can get to the bottom of the problem or change provider.. Anyway, this is how I set it up.

 

Before we create the actual function we will we have a few dependencies.

  • OMS Workspace with the Web App Analytics enabled (currently in public preview) –Not Covered
  • Azure Function account –Not Covered
  • Azure AD application used for authentication

Create an application for authentication

In order to access and manage Azure resources from Azure Functions we need to create an application in Azure Active Directory and assign it the proper permissions. I Used Powershell to do this, but it’s perfectly fine to use the online console.

The script below will create a new application and assign it “web site contributor” role. If you need other security rights chose a different role.  You can read more about the built-in roles here

Please edit the script to your needs. You will need the App Id, app password and TenantId to use as variables in our function.

Login-AzureRmAccount

#Add azure application to use for authenication from azure function
$application = New-AzureRmADApplication -DisplayName "AUTH: Azure Function" -HomePage "http://yourwebsites/functions" -IdentifierUris "https://adatum.no/AzureFunctions" -Password "***********************************"
#Grab the application ID
$appid = $application.ApplicationId.Guid 

#create a service principal for the AAD app
New-AzureRmADServicePrincipal -ApplicationId $appid

#add a role to the newly created principal.
#I have chosen Web Site Contributor, but if you want to use anything else. please see https://docs.microsoft.com/en-us/azure/active-directory/role-based-access-built-in-roles
New-AzureRmRoleAssignment -RoleDefinitionName 'Website Contributor' -ServicePrincipalName $appid

#Get the tenant ID
$TenantId = (Get-AzureRmSubscription -SubscriptionName "NAME").TenantId

Finished:

 

Setting up the Function app

First, create three environment variables in your function app containing your application ID, password and tenant id.

FunctionApp>settings>Manage Application Settings

 

I had appreciated examples of how to encrypt this password

Next, the actual code.

#Get input
$input = Get-Content $req -Raw | ConvertFrom-Json
$AppName = $input.appName
$ResourceGroup = $input.resourceGroupName

#Get user and password, create credential object
$User = $env:AzureFunctionAppID
$Pass = ConvertTo-SecureString -String $env:AzureFunctionAppPwd -AsPlainText -Force

$Credential = New-Object System.Management.Automation.PSCredential $user,$pass

#Login
Add-AzureRmAccount -Credential $Credential -TenantId $env:TennantId -ServicePrincipal

#Restart the web app and output state
Restart-AzureRmWebApp -name $AppName -ResourceGroupname $ResourceGroup
$Output = (Get-AzureRmWebApp -name $AppName).State
Out-File -Encoding Ascii -FilePath $res -inputObject $output

This Powershell function will use the environment variables/AAD application to login to your Azure environment and restart the WebApp provided in the input. I have set it up to require AppName and ResourceGroup (name) in the json post.

Send the following in the test pane to verify that the function works.

{
    "appName": "mywebApp",
    "resourceGroupName": "MyWebbAppResourceGroup"
}

There isn’t much response other than the (hopefully) “Running” status, but you can confirm everything in you activity log. The user initiated will be your application we created in the first step.

 

OMS Alert with Json payload

 

 

To automate the process, OMS need to trigger the function when too many 500-errors occur. Azure Web App Analytics (preview) in OMS already have views enabled for different error codes, response time etc, so you can use this for what ever you need. I wanted to restart a specific web app based on error 500’s. This is the search string I ended up with

Type:AzureMetrics ResourceId=*"/MICROSOFT.WEB/SITES/"* (MetricName=Requests OR MetricName=Http*) MetricName=Http5xx Resource=WEBAPPNAME

Based on that search result i created an alert sending a webhook with a custom Json payload

{ 
"appName": "mywebApp", 
"resourceGroupName": "MyWebbAppResourceGroup"
 }

 

OMS should now kick off your Azure Function and restart the website without your interaction. To verify you can use the acitivity log and OMS’ alert log.

 

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
Azure CDN Logo Azure

Azure CDN on WordPress

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

Content Delivery Network (CDN) let you distribute static content from your website or other web application from locations closest to the end-user. For a standard web site this include things like images, CSS files, Java script and so on.

 

Looking at the image below, you can see that visitors on this site is scattered around. enabling CDN will therefore improve performance by delivering the content from different locations rather than the site host which is in Europe.
Following this post you should be able to have CDN up and running in about 15 minutes 🙂

 

visitors location

 

 

 

 

PreReq’s

  • W3 Total Cache WordPress Plugin
  • Azure Subscription

 

Enable Azure CDN

The first thing you need to do is to create a new Azure CDN profile in the Azure portal. Search for CDN and create a new profile.

I chose to go with the standard Verizon version which at this point it cost $0.08 per GB up to 10TB usage. If you have other needs please check the features and pricing for Azure CDN here.

Next, create a new endpoint and configure the origin. If you run your site in Azure you can find it in the drop down. The endpoint will be the URL which all cached content is available. You can run multiple endpoints under one profile, i just ended up using a 1-1 resource group, profile and endpoint.

Azure CDN endpoint blade

According to Azure documentation, it can take up to 90 minutes before new endpoints are cached, so expect to see 404 errors after you have created it. Take a note of the endpoint hostname which is the address we are configuring in WordPress.

 

Configure WordPress CDN

Heading over to your wordpress admin page you will have to enable CDN under W3 Total Cache general settings. Tick enable and chose generic mirror as your CDN type. Azure CDN will mirror your data and using “pull” functionality.

Enable CDN using wordpress

 

 

After this is enabled click CDN under performance on your left menu. If you do not remember your endpoint name, go back and copy it from the Azure portal.

 

Scroll down to the configuration area and put in your endpoint name without HTTP(s). Check connectivity by clicking “test mirror”

 

This is all configuration needed to do basic CDN using Azure on your WordPress web site, but a lot of customization can be done both in Azure and in WP. After caching is enabled and time has done it things. You should be able to confirm that mirroring is working. Here is a screenshot of Chrome developer tools where you see the image URL is my CDN endpoint in Azure.

 

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

Posts pagination

1 … 15 16 17 18 19

Popular blog posts

  • SCOM Alerts to Microsoft Teams and Mattermost
  • How to move Azure blobs up the path
  • Windows Admin Center with SquaredUp/SCOM
  • SCOM Task to restart Agent - am i complicating it?
  • 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