Wednesday, July 10, 2019

Azure App Service : Automate Start/Stop/Restart web app


Azure App Service : Automate Start/Stop/Restart web app



Start/Stop/Restart web app through code/program 


Issue:
·       I want to stop/start/Restart my web app through code.
·       I want to restart my web app everyday at some certain time.
·       How can I automate it?

Solution:
A common ask from may app services users is, Is there any way to stop/start or restart web app programmatically. Once we have logic and program then we can simply automate that also.

Good news is you can write code to perform this operation. I am explaining this using PowerShell, but same approach can be used with other languages like C#.

Points to remember,
·       When we Stop, Start or Restart the web app from Portal, we internally call the REST API.
·       If we can call those REST API or http endpoint programmatically then our purposed can be fulfilled.

But the challenge is, you can’t simply call those REST API. You must pass authentication information also with the request. This authentication information can be username/password or Bearer token.
It is not the good practice to hardcode username/password in the code hence we should generate BEARER token at run time and will pass that.

We can use the concept of “Service Principal” to generate bearer token.
Please refer below URL to create service principal,

Once we have Application ID and Client secret then we can use following Power Shell command to automate this process.


$Auth = Invoke-RestMethod -Uri "https://login.microsoftonline.com/<Your Tenant ID>/oauth2/token?api-version=1.0" -Method Post -Body @{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "<Your Application ID>"; "client_secret" = "<Your Client Secret ID>”}

$HeaderValue = "Bearer " + $Auth.access_token

#Stop
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/<your subscription id>/resourceGroups/<your resource group name>/providers/Microsoft.Web/sites/<your web app name>/stop?api-version=2018-02-01" -Method Post -Headers @{Authorization = $HeaderValue}  

#Start
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/<your subscription id>/resourceGroups/<your resource group name>/providers/Microsoft.Web/sites/<your web app name>/start?api-version=2018-02-01" -Method Post -Headers @{Authorization = $HeaderValue}  



Please replace values according to your web app and configuration. (highlighted in yellow). Please modify this script according to your requirement.

You can get the list of other REST API in resource explorer feature of your web app.
Ref: 

You can use this script in your web job or function app or anywhere else to automate this process.

Hope this helps. Please share your feedback.

No comments:

Post a Comment