Azure App Service Archives - RuslanY Blog Azure App Service Features and Best Practices Fri, 31 Jan 2020 19:31:21 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.16 https://ruslany.net/wp-content/uploads/2019/05/cropped-web-32x32.png Azure App Service Archives - RuslanY Blog 32 32 How to monitor Azure App Service content changes and publishing activity https://ruslany.net/2020/01/how-to-monitor-azure-app-service-content-changes-and-publishing-activity/ https://ruslany.net/2020/01/how-to-monitor-azure-app-service-content-changes-and-publishing-activity/#respond Mon, 13 Jan 2020 23:08:58 +0000 https://ruslany.net/?p=424476 There are various ways to deploy an Azure App Service content: FTP, GitHub actions, deploy from Zip and many others. With Azure Role-Based Access Control it is possible to have many different users with contributor access who can deploy new content or modify existing files. In those situations it may be important to track who … Continue reading "How to monitor Azure App Service content changes and publishing activity"

The post How to monitor Azure App Service content changes and publishing activity appeared first on RuslanY Blog.

]]>
There are various ways to deploy an Azure App Service content: FTP, GitHub actions, deploy from Zip and many others. With Azure Role-Based Access Control it is possible to have many different users with contributor access who can deploy new content or modify existing files. In those situations it may be important to track who made the content changes and when. Some companies or businesses may need this capability for various compliance requirements. This blog post explains how to enable the monitoring of app service content publishing activity and content file changes.

Azure App Service is integrated with Azure Monitor which makes many app service logs available in Azure Monitor and Azure Log Analytics. The publishing activity and file change logs are also pushed to Azure Monitor and can be exported to third party services or can be used to create rule-based alerts.

Here are the configuration steps necessary to enable publishing activity and file change logging.

Create a new Log Analytics workspace

Note that this step can be omitted if you do not plan to use Log Analytics to query the logs and instead just want to make the logs available to third party log processing services.

Make sure that the workspace is created in the same region where you app service is located.

Create new Log Analytics workspace

Configure Azure Monitor diagnostic settings

In the Azure Portal select the App Service and then select the diagnostic settings:

App Service diagnostic settings

Select +Add diagnostic setting:

Add diagnostic setting

On next page you can specify what logs you need and where you need those logs to be sent to. Select the following logs:

  • AppServiceFileAuditLogs – this will generate logs for app service content files changes;
  • AppServiceAuditLogs – this will generate logs for publishing access, for example when somebody logs on via FTP.

Then select where you need those logs to be sent to. For example you can send them to a storage account of your choice and to a Log Analytics workspace that you created in a previous step. Note that the storage account has to be in the same region as the app service.

Configure logs for Azure Monitor

Scale the App Service Plan to PremiumV2 or Premium

The file change audit logs (AppServiceFileAuditLogs) are only available for app services in Premium, PremiumV2 and Isolated App Service Plans. You will need to scale up the app service plan in order to get those logs.

The publishing audit logs (AppServiceAuditLogs) are available for all App Service Plan pricing tiers.

Enable File Change Audit for the App Service

The last step is to switch on the File Change Audit configuration setting for the web app. At the time of writing this article there is no Portal support or client libraries for this setting yet so the easiest way to do this is via Azure Resource Explorer:

Enable file change audit in Azure Resource Explorer

How to access the logs

If you enabled sending of the logs to a storage account then you should see the insights-logs-appserviceauditlogs and insights-logs-appservicefileauditlogs containers in that storage account:

Log containers in the storage account

If you enabled sending of the logs to the Log Analytics workspace then open that workspace and go to the Logs page. That will open the query window where you can write the queries against the AppServiceFileChangeAuditLogs:

Querying file changes in the past 7 days

and AppServiceAuditLogs:

Querying the publishing access in the past 7 days

The log analytics allows you to create complex queries against these logs and also use those queries to create rule-based alerts. For example you can create an alert that will send you an email whenever a files with extension .config and *.dll are modified.

How to exclude specific files or directories from audit

If an application generates many temporary files or if it constantly writes something to a log file then this may result in very noisy audit log. To prevent this from happening you can exclude certain directories from auditing by using the audit log filter file.

Create a file named _auditLog.filter at the root directory of your site content (D:\Home) and add the directory and file paths to be excluded there:

# this is an example of an audit filter file
# it can contain file and directory paths
# it can have comments
# it can have up to 50 exclude paths
# each path can be up to 256 chars long
/LogFiles
/site/locks
/site/deployments
/site/wwwroot/applogs/phperrors.log

Known issues

  • The file change audit and publishing access audit are currently in a public preview. The functionality may have some bugs and the logs schema may change
  • The file change audit is only available for app services that run on Windows App Service plans. The Linux App Service Plans are not supported at the time of writing this article.

The post How to monitor Azure App Service content changes and publishing activity appeared first on RuslanY Blog.

]]>
https://ruslany.net/2020/01/how-to-monitor-azure-app-service-content-changes-and-publishing-activity/feed/ 0
Using ARM template to swap App Service deployment slots https://ruslany.net/2019/10/using-arm-template-to-swap-app-service-deployment-slots/ https://ruslany.net/2019/10/using-arm-template-to-swap-app-service-deployment-slots/#respond Tue, 01 Oct 2019 18:43:06 +0000 https://ruslany.net/?p=424454 Azure Resource Manager (ARM) templates are used to automate deployment and configuration of Azure resources. With the templates you can define the infrastructure to be deployed via a JSON file and then use that file to repeatedly deploy new resources or update existing ones. ARM templates are widely used to release new versions of the … Continue reading "Using ARM template to swap App Service deployment slots"

The post Using ARM template to swap App Service deployment slots appeared first on RuslanY Blog.

]]>
Azure Resource Manager (ARM) templates are used to automate deployment and configuration of Azure resources. With the templates you can define the infrastructure to be deployed via a JSON file and then use that file to repeatedly deploy new resources or update existing ones. ARM templates are widely used to release new versions of the Azure web apps and function apps. During a release the new version of an app is deployed to a staging slot and then it is swapped into production. This blog post explains how to automate the App Service deployment slot swap operation with an ARM template.

Let’s assume you have a web app with production and staging deployment slots. When you release a new version of that web app you first would deploy it to the staging slot and then swap it into production slot. To define the swap operation via ARM template you’ll need to use two properties on the “Microsoft.Web/sites” and “Microsoft.Web/sites/slots” resources:

  • buildVersion – this is a string property which can be set to any arbitrary value that would represent the current version of the app deployed in the slot. For example: “v1“, “1.0.0.1“, “2019-09-20T11:53:25.2887393-07:00“.
  • targetBuildVersion – this is a string property that is used to specify what version of the app the current slot should have. If the targetBuildVersion is different from the buildVersion then this will trigger the swap operation by finding a slot that has the expected build version and then swapping the site from that slot into the current slot.

With that the process of deploying a new version of an app can be done as follows:

  1. Deploy a new version of an app into a staging slot
  2. Execute ARM template to update the buildVersion of the app in staging slot
  3. Execute ARM template to set the targetBuildVersion on the production slot

Here is an example ARM template that demonstrates how to perform steps #2 and #3:

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "sites_SwapAPIDemo_name": {
            "defaultValue": "SwapAPIDemo",
            "type": "String"
        },
        "sites_buildVersion": {
            "defaultValue": "v1",
            "type": "String"
        }
    },
    "resources": [
        {
            "type": "Microsoft.Web/sites/slots",
            "apiVersion": "2018-02-01",
            "name": "[concat(parameters('sites_SwapAPIDemo_name'), '/staging')]",
            "location": "East US",
            "kind": "app",
            "properties": {
                "buildVersion": "[parameters('sites_buildVersion')]"
            }
        },
        {
            "type": "Microsoft.Web/sites",
            "apiVersion": "2018-02-01",
            "name": "[parameters('sites_SwapAPIDemo_name')]",
            "location": "East US",
            "kind": "app",
            "dependsOn": [
                "[resourceId('Microsoft.Web/sites/slots', parameters('sites_SwapAPIDemo_name'), 'staging')]"
            ],
            "properties": {
                "targetBuildVersion": "[parameters('sites_buildVersion')]"
            }
        }        
    ]
}

This ARM template is idempotent, meaning that it can be executed repeatedly and produce the same state of the slots. In other words if you re-run the same template with the same parameters after the swap has been performed and targetBuildVersion on production slot matches the buildVersion then it will not trigger another swap.

The post Using ARM template to swap App Service deployment slots appeared first on RuslanY Blog.

]]>
https://ruslany.net/2019/10/using-arm-template-to-swap-app-service-deployment-slots/feed/ 0
How to restore a deleted Azure Web App https://ruslany.net/2019/06/how-to-restore-a-deleted-azure-web-app/ https://ruslany.net/2019/06/how-to-restore-a-deleted-azure-web-app/#comments Wed, 05 Jun 2019 18:51:51 +0000 https://ruslany.net/?p=424425 If you happened to accidentally delete your web app in Azure App Service then up until recently you had to open a support case in order to get it restored. But now you can restore it yourself by using the commands from the Az PowerShell module. This blog post explains how to do that. Assume … Continue reading "How to restore a deleted Azure Web App"

The post How to restore a deleted Azure Web App appeared first on RuslanY Blog.

]]>
If you happened to accidentally delete your web app in Azure App Service then up until recently you had to open a support case in order to get it restored. But now you can restore it yourself by using the commands from the Az PowerShell module. This blog post explains how to do that.

Assume you used to have a site named “undeletesiteexample” and you have deleted it accidentally. The first step to recover it is to get the details of the deleted app:

Get-AzDeletedWebApp -Name undeletesiteexample
Get-AzDeletedWebApp output

This command will return the information about the deleted app such as when it was deleted and what is its DeletedSiteId. The DeletedSiteId is used to uniquely identify the deleted app in case there have been several apps with the same name deleted.

The next step is to restore the deleted app by using Restore-AzDeletedWebApp command:

Restore-AzDeletedWebApp -ResourceGroupName SwapTestRG -Name undeletesiteexample -TargetAppServicePlanName SwapTestASP
Restore-AzDeletedWebApp output

Or alternatively you can pipe the output of the Get-AzDeletedWebApp command:

$deletedSiteInfo = Get-AzDeletedWebApp -Name undeletesiteexample
$deletedSiteInfo | Restore-AzDeletedWebApp -ResourceGroupName SwapTestRG -Name undeletesiteexample -TargetAppServicePlanName SwapTestASP

The Restore-AzDeletedWebApp can be used to restore a site using the same or different name. Also you can chose where to restore it to, e.g. which resource group, app service plan or deployment slot. In addition you can also chose to restore just the content ([-RestoreContentOnly]) or the content and the site’s configuration settings.

Note that if the app was hosted on and then deleted from an App Service Environment then it can be restored only if the corresponding App Service Environment still exist.

The post How to restore a deleted Azure Web App appeared first on RuslanY Blog.

]]>
https://ruslany.net/2019/06/how-to-restore-a-deleted-azure-web-app/feed/ 11
Azure App Service Deployment Slots Tips and Tricks https://ruslany.net/2019/06/azure-app-service-deployment-slots-tips-and-tricks/ https://ruslany.net/2019/06/azure-app-service-deployment-slots-tips-and-tricks/#comments Tue, 04 Jun 2019 19:21:32 +0000 https://ruslany.net/?p=424386 This post explains some of the not so well-known features and configurations settings of the Azure App Service deployment slots. These can be used to modify the swap logic as well as to improve the application availability during and after the swap. Here is what you can do with them: Swap slots only if the … Continue reading "Azure App Service Deployment Slots Tips and Tricks"

The post Azure App Service Deployment Slots Tips and Tricks appeared first on RuslanY Blog.

]]>
This post explains some of the not so well-known features and configurations settings of the Azure App Service deployment slots. These can be used to modify the swap logic as well as to improve the application availability during and after the swap. Here is what you can do with them:

Swap based on the status code

During the swap operation the site in the staging slot is warmed up by making an HTTP request to its root directory. More detailed explanation of that process is available at How to warm up Azure Web App during deployment slots swap. By default the swap will proceed as long as the site responds with any status code. However, if you prefer the swap to not proceed if the application fails to warm up then you can configure it by using these app settings:

  • WEBSITE_SWAP_WARMUP_PING_PATH: The path to make the warm up request to. Set this to a URL path that begins with a slash as the value. For example, “/warmup.php”. The default value is /.
  • WEBSITE_SWAP_WARMUP_PING_STATUSES:Expected HTTP response codes for the warm-up operation. Set this to a comma-separated list of HTTP status codes. For example: “200,202” . If the returned status code is not in the list, the swap operation will not complete. By default, all response codes are valid.

You can mark those two app setting as “Slot Settings” which would make them remain with the slot during the swap. Or you can have them as “non-sticky” settings meaning that they would move with the site as it gets swapped between slots.

Minimize random cold starts

In some cases after the swap the web app in the production slot may restart later without any action taken by the app owner. This usually happens when the underlying storage infrastructure of Azure App Service undergoes some changes. When that happens the application will restart on all VMs at the same time which may result in a cold start and a high latency of the HTTP requests. While you cannot control the underlying storage events you can minimize the effect they have on your app in the production slot. Set this app setting on every slot of the app:

  • WEBSITE_ADD_SITENAME_BINDINGS_IN_APPHOST_CONFIG: setting this to “1” will prevent web app’s worker process and app domain from recycling when the App Service’s storage infrastructure gets reconfigured.

The only side effect this setting has is that it may cause problems when used with some Windows Communication Foundation (WCF) application. If you app does not use WCF then there is no downside of using this setting.

Control SLOT-sticky configuration

Originally when deployment slots functionality was released it did not properly handle some of the common site configuration settings during swap. For example if you configured IP restrictions on the production slot but did not configure that on the staging slot and then performed the swap you would have had the production slot without any IP restrictions configuration, while the staging slot had the IP restrictions enabled. That did not make much sense so the product team has fixed that. Now the following settings always remain with the slot:

  • IP Restrictions
  • Always On
  • Protocol settings (Https Only, TLS version, client certificates)
  • Diagnostic Log settings
  • CORS

If however for any reason you need to revert to the old behavior of swapping these settings then you can add the app setting WEBSITE_OVERRIDE_PRESERVE_DEFAULT_STICKY_SLOT_SETTINGS to every slot of the app and set its value to “0” or “false”.

swap Diagnostics detector

If a swap operation did not complete successfully for any reason you can use the diagnostics detector to see what has happened during the swap operation and what caused it to fail. To get to it use the “Diagnose and solve problems” link in the portal:

How to find the Swap Diagnostics detector

From there click on “Check Swap Operations” which will open a page showing all the swaps performed on the webapp and their results. It will include possible root causes for the failures and recommendations on how to fix them.

Check Swap Operations page

The post Azure App Service Deployment Slots Tips and Tricks appeared first on RuslanY Blog.

]]>
https://ruslany.net/2019/06/azure-app-service-deployment-slots-tips-and-tricks/feed/ 30
Using Azure Activity Log to check the progress of deployment slots swap operation https://ruslany.net/2018/03/using-azure-activity-log-to-check-the-progress-of-deployment-slots-swap-operation/ https://ruslany.net/2018/03/using-azure-activity-log-to-check-the-progress-of-deployment-slots-swap-operation/#comments Thu, 08 Mar 2018 18:10:38 +0000 http://ruslany.net/?p=424244 If you use Azure Web App Deployment Slots then you may have noticed that sometimes the swap action may take a while to complete. This may happen when an application that is being swapped into production has a long warmup/initialization phase. It has to be warmed up on every VM in an App Service Plan … Continue reading "Using Azure Activity Log to check the progress of deployment slots swap operation"

The post Using Azure Activity Log to check the progress of deployment slots swap operation appeared first on RuslanY Blog.

]]>
If you use Azure Web App Deployment Slots then you may have noticed that sometimes the swap action may take a while to complete. This may happen when an application that is being swapped into production has a long warmup/initialization phase. It has to be warmed up on every VM in an App Service Plan and that sometimes takes minutes (more detailed description of what happens during the swap can be found in Most common deployment slot swap failures and how to fix them). This blog post explains how to see the progress and the result of the swap operation in the Azure Activity Log.

To see the swap operation events use the Activity log view in the Azure Portal:

Activity Log

Here is an example of how the swap events look like:

Swap events example
  1. ApplySlotConfig – this is logged when slot settings from production slot have been applied to a webapp in the staging slot
  2. StartSlotWarmup – this is logged when starting to initialize the webapp in the staging slot
  3. EndSlotWarmup – this indicates that the webapp initialization has completed
  4. SlotSwap – this is logged when the webapp from the staging slot has been swapped into production slot.

If there was a failure while swapping the slots then the events will look like below. The event description will have explanation of why the failure occurred.

Failed swap event in activity log

If you use PowerShell then you can get the swap related events by using this command:

Get-AzureRmLog -ResourceGroup slotswaptest -StartTime 2018-03-07 -Caller SlotSwapJobProcessor

This will produce an output as below:

Activity Log in PowerShell

(For more information on how to get Activity Log events via Powershell refer to View activity logs to audit actions on resources)

If you prefer to call the Azure API’s directly (or by using ARMClient tool) then you make a request like below:

ArmClient.exe GET "//providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&$filter=eventTimestamp ge '2018-03-07T00:00:00Z' and eventTimestamp le '2018-03-08T23:00:00Z' and resourceGroupName eq 'slotswaptest'"

In the response look for events that have Caller property set to “SlotSwapJobProcessor“.

The post Using Azure Activity Log to check the progress of deployment slots swap operation appeared first on RuslanY Blog.

]]>
https://ruslany.net/2018/03/using-azure-activity-log-to-check-the-progress-of-deployment-slots-swap-operation/feed/ 7
Most common deployment slot swap failures and how to fix them https://ruslany.net/2017/11/most-common-deployment-slot-swap-failures-and-how-to-fix-them/ https://ruslany.net/2017/11/most-common-deployment-slot-swap-failures-and-how-to-fix-them/#comments Thu, 02 Nov 2017 21:30:01 +0000 http://ruslany.net/?p=419544 Azure Web App Deployment Slots are used to deploy new versions of an application code into production with no interruption to the production traffic. In order to achieve this the swap process involves multiple steps that are performed to prepare the new version of the code to successfully handle the load once it is in … Continue reading "Most common deployment slot swap failures and how to fix them"

The post Most common deployment slot swap failures and how to fix them appeared first on RuslanY Blog.

]]>
Azure Web App Deployment Slots are used to deploy new versions of an application code into production with no interruption to the production traffic. In order to achieve this the swap process involves multiple steps that are performed to prepare the new version of the code to successfully handle the load once it is in production slot. Some of these steps may go wrong, especially when the new version of the code does not cooperate well. This in turn either causes the swap to fail or it results in swapping new code in production while it is still not ready to handle the production load. This post describes the most common reasons why this may happen and how to correct them.

In order to better understand the reasons for the swap failures it is first necessary to explain how the application code in the staging slot is initialized / warmed up prior to the swap to production. Failures during these steps are the most common reasons for the overall failure of the swap operation.

The swap operation is done by an internal process that runs within a scale unit where web app is hosted. Here are the steps that it performs to ensure the application is initialized prior to the swap. Note that the same sequence of actions happens during Auto-Swap and Swap with Preview.

  • Apply the production configuration settings to all web app’s instances in the staging slot. This happens when web app has appsettings or connection strings marked as “Slot settings” or if Continuous Deployment is enabled for the site or if Site Authentication is enabled. This will trigger all instances in the staging slot to restart. (For Swap with Preview this the first phase of the swap after which the swap process is paused and you can validate that the application works correctly with production settings)
  • Wait for every instance to complete its restart. If some instance failed to restart then the swap process will revert any configuration changes to the app in staging slot and will not proceed further. If that happens the first place to look into is the D:\home\LogFiles\eventlog.xml file of the application specific error log (such as php_errors.log for PHP apps) where you may find more clues what prevents application from starting.
  • If Local Cache is enabled then swap process will trigger Local Cache initialization by making an HTTP request to the root directory URL path (“/”) of the web app on every web worker. Local Cache Initialization consists of copying the site’s content files from network share to the local disk of the worker and then re-pointing the web app to use local disk for its content. This causes another restart of the web app. The swap process will wait until the Local Cache is completely initialized and restarted on every instance before proceeding further. A common reason why Local Cache Initialization may fail is when site content size exceeds the local disk quota specified for the Local Cache. If that is the case the the quota can be increased by following instructions from Local Cache Documentation.
  • If Application Initialization (AppInit) is enabled then swap process will make another HTTP request to the root URL path on every web worker. The AppInit is a module that runs within the web app request processing pipeline and it gets executed when web app starts. The only thing the swap process does with its first HTTP request to the web app is it triggers the AppInit module to do its work. After that it just waits until AppInit reports that it has completed the warmup. AppInit module uses the list of URL paths specified inside web.config file and makes internal HTTP requests to each of those. All these requests are within the web app process. It does not call any external URL’s and its requests are not going through the scale unit’s front ends. Also, neither the initial HTTP request nor AppInit internal requests follow HTTP redirects. That causes the most common problem that users run into with this module. If web app has such rewrite rules as “Enforce Domain” or “Enforce HTTPs” then none of the warmup requests will actually reach the application code. All the requests will be shortcut by the rewrite rules. In order to prevent that the rewrite rules need to be modified like below:
<rule name="Canonical Host Name" stopProcessing="true">
  <match url="(.*)" />
  <conditions>
    <add input="{WARMUP_REQUEST}" pattern="1" negate="true" />
    <add input="{REMOTE_ADDR}" pattern="^100?\." negate="true" />
    <add input="{HTTP_HOST}" negate="true" pattern="^ruslany\.net$" />
  </conditions>
  <action type="Redirect" url="http://ruslany.net/{R:1}" redirectType="Permanent" />
</rule>
<rule name="Redirect to HTTPS" stopProcessing="true">
  <match url="(.*)" />
  <conditions>
    <add input="{WARMUP_REQUEST}" pattern="1" negate="true" />
    <add input="{REMOTE_ADDR}" pattern="^100?\." negate="true" />
    <add input="{HTTPS}" pattern="^OFF$" />
  </conditions>
  <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>

The {WARMUP_REQUEST} is a server variable that is set by AppInit module for each of its internal requests. That is a reliable way to distinguish whether the request is external or is made by AppInit module. The {REMOTE_ADDR} is a server variable that contains the IP address of HTTP client. The IP address ranges starting with “10.” or “100.” are internal to the scale unit and no outside HTTP client can use them.

  • If AppInit is not enabled then swap process just makes an HTTP request to the root path of the webapp on each web worker and as long as it receives some HTTP response it considers the warmup complete. Again the rewrite rules in the web app can cause the site to return HTTP redirect response and the actual application code will not be executed at all. Since the AppInit is not involved here the only way to prevent the rewrite rules is to use the {REMOTE_ADDR} server variable in the rule’s conditions as shown below.
<conditions>
  <add input="{REMOTE_ADDR}" pattern="^100?\." negate="true" />
</conditions>
  • After all the above steps are completed successfully the actual swap is performed by switching the routing rules on the scale unit’s front ends. More details on what happens during the swap can be found in other blog post “How to warm up Azure Web App during deployment slots swap”

Some other common problems that cause the swap to fail:

  • An HTTP request to the root URL path times out. The swap process waits for 90 seconds for the request to return. In case of timeout the request will be retried for up to 5 times. If after that the request still times out then the swap operation will be aborted. If that happens then check the eventlog.xml or application specific error log to see if there are any indications of what causes the timeout.
  • An HTTP request to the root URL path is aborted. This may happen if web app has a rewrite rule to abort some requests. If that is the case then the rule can be modified by adding the {REMOTE_ADDR} check as shown in previous examples.
  • Web App has IP restriction rules that prevent the swap process from connecting to it. In that case you’ll need to allow the internal IP address range used by the swap process:

The post Most common deployment slot swap failures and how to fix them appeared first on RuslanY Blog.

]]>
https://ruslany.net/2017/11/most-common-deployment-slot-swap-failures-and-how-to-fix-them/feed/ 17
Using Powershell to manage Azure Web App Deployment Slots https://ruslany.net/2016/10/using-powershell-to-manage-azure-web-app-deployment-slots/ https://ruslany.net/2016/10/using-powershell-to-manage-azure-web-app-deployment-slots/#comments Fri, 28 Oct 2016 00:41:20 +0000 http://ruslany.net/?p=402841 This blog post has been updated from its original version in order to use the correct names of the PowerShell cmdlets. This blog post explains how to perform common management tasks for Azure Web App deployment slots by using Powershell cmdlets. To learn more about deployment slots refer to the Azure documentation and my previous … Continue reading "Using Powershell to manage Azure Web App Deployment Slots"

The post Using Powershell to manage Azure Web App Deployment Slots appeared first on RuslanY Blog.

]]>

This blog post has been updated from its original version in order to use the correct names of the PowerShell cmdlets.

This blog post explains how to perform common management tasks for Azure Web App deployment slots by using Powershell cmdlets. To learn more about deployment slots refer to the Azure documentation and my previous blog posts: Azure Web App Deployment Slot Swap with Preview and How to warm up Azure Web App during deployment slots swap.

Create a new deployment slot for an existing web app

$rg = "SomeResourceGroupName"
$site = "SomeSiteName"
New-AzWebAppSlot -ResourceGroupName $rg -name $site -slot staging

List deployment slots for a web app

Get-AzWebAppSlot -ResourceGroupName $rg -name $site

Delete a deployment slot

Remove-AzWebAppSlot -ResourceGroupName $rg -name $site -Slot staging

Specify slot app settings and connection strings

Set-AzWebAppSlotConfigName -ResourceGroupName $rg -name $site -AppSettingNames "SlotName","Environment" -ConnectionStringNames "PrimaryDB","SecondaryDB"

This cmdlet specifies the names of app settings and connection strings that will be treated as slot settings, meaning that they will remain with the slot during swap.

Set the app setting values on web app and on its slots

Set-AzWebApp -ResourceGroupName $rg -Name $site -AppSettings @{"SlotName" = "Production"; "Environment" = "Production"}
Set-AzWebAppSlot -ResourceGroupName $rg -Name $site -Slot staging -AppSettings @{"SlotName" = "Staging"; "Environment" = "Staging"}

Perform a regular slot swap

Switch-AzWebAppSlot -ResourceGroupName $rg -Name $site -SourceSlotName staging -DestinationSlotName production

Perform swap with preview

First check that the staging slot’s app setting have staging values:

$stagingSite = Get-AzWebAppSlot -ResourceGroupName $rg -Name $site -Slot staging
$stagingSite.SiteConfig.AppSettings

Name Value
---- -----
SlotName Staging
Environment Staging

Next perform the first step of the swap, which is to apply target slot’s setting values to the current staging slot:

Switch-AzWebAppSlot -ResourceGroupName $rg -Name $site -SourceSlotName staging -DestinationSlotName production -SwapWithPreviewAction ApplySlotConfig

Now confirm that the app setting values have changed:

$stagingSite = Get-AzWebAppSlot -ResourceGroupName $rg -Name $site -Slot staging
$stagingSite.SiteConfig.AppSettings

Name Value
---- -----
SlotName Production
Environment Production

At this point you would want to verify that the web app in the staging slot works as expected. You can make multiple requests to it to warm it up and fill up its caches, etc.

Once you are sure the app works as expected call this cmdlet to finish the swap:

Switch-AzWebAppSlot -ResourceGroupName $rg -Name $site -SourceSlotName staging -DestinationSlotName production -SwapWithPreviewAction CompleteSlotSwap

If for any reason you do not want to proceed with the swap you can reset the configuration on the staging slot back to its original state:

Switch-AzWebAppSlot -ResourceGroupName $rg -Name $site -SourceSlotName staging -DestinationSlotName production -SwapWithPreviewAction ResetSlotSwap

The post Using Powershell to manage Azure Web App Deployment Slots appeared first on RuslanY Blog.

]]>
https://ruslany.net/2016/10/using-powershell-to-manage-azure-web-app-deployment-slots/feed/ 6
How to buy a certificate for an Azure Web App https://ruslany.net/2016/04/how-to-buy-a-certificate-for-an-azure-web-app/ https://ruslany.net/2016/04/how-to-buy-a-certificate-for-an-azure-web-app/#comments Tue, 05 Apr 2016 18:55:25 +0000 http://ruslany.net/?p=397342 If you have tried to enable SSL for your Azure Web App you know that the steps to do that are: Purchase certificate and export it into a PFX file Upload PFX file to a resource group that contains your web app Bind the web app’s hostnames to the certificate Out of those steps the … Continue reading "How to buy a certificate for an Azure Web App"

The post How to buy a certificate for an Azure Web App appeared first on RuslanY Blog.

]]>
If you have tried to enable SSL for your Azure Web App you know that the steps to do that are:

  1. Purchase certificate and export it into a PFX file
  2. Upload PFX file to a resource group that contains your web app
  3. Bind the web app’s hostnames to the certificate

Out of those steps the step #1 is the most non-obvious. Just by looking through the instructions in this article you can see that the process is complex and error prone.

Recently the Azure team has released an improved support for buying certificates for Azure Web Apps. Now it is possible to purchase a certificate without ever leaving the Azure Portal UI experience. In this blog post I’ll show how easy it is to buy a certificate and enable SSL for a Web App. As an example I will walk through the process of buying a certificate and enabling SSL for my web site http://ruslany.net/

To start the process of buying a cert in Azure Portal click on Browse > and select “App Service Certificates“.

Then click Add and specify the certificate properties, most importantly the Naked Domain Host Name (e.g. ruslany.net in my case):

The certificate purchase process starts and at some point you will be asked to configure a Key Vault service which will store the purchased cert.

If you do not have a Key Vault configured then add a new Key Vault Repository and once it is provisioned click on the “Store” button:

After the Key Vault has been linked to your certificate then next step is to verify the domain ownership. Azure Portal makes this verification very simple. If you already have a Web App that uses the same domain name as in the certificate then you can chose “App Service Verification” method and the corresponding App will be listed below. Just click on “Verify” button and give it 5 to 10 minutes for verification process to complete.

Assuming the verification was successful the certificate will be issued and will be stored in the Key Vault repository from where it can be used by other App Services within your subscription:

To use the certificate in the Web App, select the Web App in the portal, then select “Custom domains and SSL” and then click on “Import Certificate”

This will ask you to pick the certificate from the Key Vault repository:

After that the certificate information should show up in the “Custom Domains and SSL” page where you can configure SSL bindings to use that certificate:

How to rekey a certificate

One nice feature that is included in the certificate management functionality is the ability to rekey a certificate. If for any reason you believe your certificate got compromised or if you need to rotate the certificate for security compliance reasons you can easily rekey it. This will result in a new certificate with a different thumbprint issued for your domain.

In addition, once the rekey’ed certificate has been issued you can click on “Sync” button and all the web apps that use the old certificate will be updated to use the rekey’ed certificate. Note that you can rekey these certificates as many times as you need as long as they are not expired.

The post How to buy a certificate for an Azure Web App appeared first on RuslanY Blog.

]]>
https://ruslany.net/2016/04/how-to-buy-a-certificate-for-an-azure-web-app/feed/ 5
Azure Web App Deployment Slot Swap with Preview https://ruslany.net/2015/10/azure-web-app-deployment-slot-swap-with-preview/ https://ruslany.net/2015/10/azure-web-app-deployment-slot-swap-with-preview/#comments Fri, 30 Oct 2015 16:56:12 +0000 http://ruslany.net/?p=392581 Some time ago I had a blog post describing how to warm up an Azure Web App during deployment slots swap. In that post I explained the sequence of actions that happens during the swap. One important point in that explanation is that if a site has any app settings or connection strings that are … Continue reading "Azure Web App Deployment Slot Swap with Preview"

The post Azure Web App Deployment Slot Swap with Preview appeared first on RuslanY Blog.

]]>
Some time ago I had a blog post describing how to warm up an Azure Web App during deployment slots swap. In that post I explained the sequence of actions that happens during the swap. One important point in that explanation is that if a site has any app settings or connection strings that are marked as “Slot” then during slot swap those settings are read from target (e.g. Production) slot and applied to the site in the staging slot. That causes the restart of the site’s worker process so that those changes take effect and become visible as process environment variable.

The restart of the worker process is OK for the majority of the swaps. But sometimes it would be useful to pause right after the production settings were applied on the staging slot and before the actual swap of host names happens. Recently Azure Web Apps team has released a “Swap with Preview” feature that supports that use case. That feature will give you a chance to verify that the web site in the staging slot works fine with production settings. Also this will allow you to warm up/initialize the site in any way you want. For example you can generate some load on that site so that its cache is completely pre-populated. After you are satisfied with how the site works in staging slot you can complete the swap so that the site is moved to production slot and starts taking on production traffic. The site’s worker process will not be restarted during that step, which means that the worker process in production slot is exactly what you have tested in staging slot.

To demonstrate how Swap with Preview works I’ve created a site and added a “Slot” setting to it with name “SlotName” and value “Production“. Also I added a “Slot” connection string with value “ProductionConnectionString“.

Then I’ve created a staging deployment slot for this site and added a “Slot” setting to it with name “SlotName” and value “Staging“. Also I added a “Slot” connection string with value “StagingConnectionString“.

Then I have deployed the following ASP.NET code to both sites in production and staging slots. The code reads the environment variables where the app setting values are stored. Also it reads the current process id which changes every time the site gets restarted.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Swap with Preview test</title>
<h1>Swap with Preview Test Page</h1>
<table>
<tbody>
<tr>
<th>Server Variable</th>
<th>Value</th>
</tr>
<tr>
<td>Process ID:</td>
<td><%= System.Diagnostics.Process.GetCurrentProcess().Id %></td>
</tr>
<tr>
<td>SlotName:</td>
<td><%= Environment.GetEnvironmentVariable("SlotName") %></td>
</tr>
<tr>
<td>ConnectionString:</td>
<td><%= Environment.GetEnvironmentVariable("SQLAZURECONNSTR_ConnectionString") %></td>
</tr>
</tbody>
</table>

If I browse to the production and staging slots I can see the process ID, app settings and connection strings:

Production slot:

Staging slot:

Now let’s assume that I have deployed a new version of an app into a staging slot and want to swap it into production. I use the “Swap” action which gives me a choice of doing a normal Swap or “Swap with Preview”. I chose “Swap with Preview” and click OK.

After the operation completes let’s browse to the staging slot:

Notice that the Process ID has changed, meaning that the worker process has restarted. Also the SlotName and ConnectionString now contain the values from the production slot. Basically the site now has all the settings that it would have in production slot except that it is still in the staging slot and does not receive any production traffic. This gives me an opportunity to verify how the new version of my app behaves with production settings. Also it lets me hit all the important URL paths on my app to make sure they are properly warmed up.

IMPORTANT: While the site is in this “swap pending” state it is not possible to make any changes to connection strings and app settings of both slots involved in the swap.

From here I have two options. If I am happy with how my new app version works with production settings I can complete the swap by using “Complete Swap” action and then choosing “Complete Swap” from the drop down list:

if I browse to the production slot after the swap completes I can see that it now has the new version of my app and the Process ID is the same, meaning that the worker process has not restarted.

If however I find that the new version of my app in staging slot does not work very well with production settings I can chose “Cancel Swap” action, which will reset the settings on my staging slot.

This example demonstrates how to perform deployment slot swap while pausing after target slot settings have been applied to the current slot and before the swap completes. During that paused state you can prepare application for taking on production traffic so that when you complete the swap you have exact same application in production slot without any restarts.

With the addition of the “Swap with preview” capability there are now three options for how to perform deployment slot swaps. They range from fully manual to fully automated and you can choose any of them depending on how confident you feel about new bits you deploy:

  1. Swap with preview – this is the option which gives you most control over the swap process. It allows you to fully verify the new version of your app before it is swapped into production and it helps to avoid restarts during the swap.
  2. Regular swap – this is the most common swap option, where the application get automatically warmed up prior to the swap. Application in the staging slot may get restarted prior to the swap.
  3. Auto-swap – this is the fully automated option where swap operation is triggered as soon as the new content is deployed to a staging slot.

The post Azure Web App Deployment Slot Swap with Preview appeared first on RuslanY Blog.

]]>
https://ruslany.net/2015/10/azure-web-app-deployment-slot-swap-with-preview/feed/ 3
How to warm up Azure Web App during deployment slots swap https://ruslany.net/2015/09/how-to-warm-up-azure-web-app-during-deployment-slots-swap/ https://ruslany.net/2015/09/how-to-warm-up-azure-web-app-during-deployment-slots-swap/#comments Wed, 30 Sep 2015 16:23:04 +0000 https://ruslanynet.azurewebsites.net/2015/09/30/how-to-warm-up-azure-web-app-during-deployment-slots-swap/ Azure Web App deployment slots are used to help roll out new versions of an app without downtime or cold start activation. New version is typically deployed to a staging slot, then after testing and final verification it gets swapped into a production slot. During the swap operation the Web App’s worker process may get … Continue reading "How to warm up Azure Web App during deployment slots swap"

The post How to warm up Azure Web App during deployment slots swap appeared first on RuslanY Blog.

]]>
Azure Web App deployment slots are used to help roll out new versions of an app without downtime or cold start activation. New version is typically deployed to a staging slot, then after testing and final verification it gets swapped into a production slot. During the swap operation the Web App’s worker process may get restarted in order for some settings to take effect. Even though the swap does not proceed until the restarted worker process comes back online on every VM instance, it may still not be enough for application to be completely ready to take on production traffic. This post explains how you can use the recently enabled Application Initialization Module to completely warm up your application prior to swapping it into production.

First of all it is necessary to explain the sequence of actions that happens when a staging slot is swapped into production. When the Swap button is clicked in Azure Portal or a corresponding management API is called:

  1. The App Settings and Connection Strings that are marked as “Slot” are read from the Production slot and applied to the site in the Staging slot. That causes the site’s worker process to be restarted for those changes to take effect and become visible as process environment variables;
  2. Then the site in the staging slot gets warmed up. To warm up the site an HTTP request is made to the root directory of the site to every VM instance where site is supposed to run. The warm up request has a User-Agent header set to “SiteWarmup”;
  3. After warm up has completed the host names for the sites in production and staging slots get swapped. Now the site that has been warmed up in the staging slot starts getting production traffic and the site that used to be in the production slot is now in the staging slot
  4. The site that is now in the staging slot gets updated with the App Settings and Connection Strings associated with the staging slot. That causes restart of that site, but it is not in production slot any more so restart is harmless.

Sometimes hitting the site’s root URL is not enough to completely warm up the application. For example it maybe necessary to hit all important routes in an ASP.NET MVC app or to pre-populate the in-memory cache. That is where the Application Initialization Module can help.

Let’s use a simple example to demonstrate how a Web App can be warmed up in the deployment slot during the swap operation. First let’s create a site and a staging deployment slot:

Next let’s set some slot settings on the App and its staging slot. These slot settings will cause the App’s worker process to restart during swap.

For the actual app code I used two simple PHP files: index.php and warmup-cache.php. The index.php is served when site’s root URL is requested. The warmup-cache.php is my “cache warmup” code that takes long time to run (emulated by sleep() command). In real application that can be the script that makes database queries to fill up the cache.

Finally I also have a web.config file which configures AppInit module:

<system.webServer>
  <applicationInitialization >
    <add initializationPage="/warmup-cache.php" hostName="appinit-warmup.azurewebsites.net"/>
  </applicationInitialization>
<system.webServer>

In the applicationInitialization section I can specify multiple URL paths that need to be requested in order to warm up my application. In my case I only need to hit one URL. Also notice that I can specify the host name to use for the warm up requests (this is optional and if not specified the “localhost” will be used as a host name).

The following steps are just for verification/debugging purposes. There is no need to perform them when using AppInit module. In fact enabling them for your production site may considerably slow it down.

To confirm that the warmup-cache.php is actually requested during the swap I will use Failed Request Tracing. It can be enabled from Azure Portal:

However, that will trace only failed requests. I need it to trace all requests. For that I add the following section to the web.config file:

<tracing>
  <traceFailedRequests>
    <clear/>
    <add path="*">
      <traceAreas>
      <add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,Rewrite,iisnode" verbosity="Verbose" />
      </traceAreas>
      <failureDefinitions statusCodes="200-600" />
    </add>
  </traceFailedRequests>
</tracing>

The important attribute here is statusCodes which specifies that requests with status codes between 200 and 600 should be logged.

Now let’s run the swap command.

During the swap operation the application is restarted and the first warm up request is made to the root directory of the web app. That starts the AppInit module which makes a request to warmup-cache.php URL and waits until it completes. Only after that request competes the swap operation proceeds to the next step and swaps the host names so that the warmed up site starts getting production traffic. Because of that the swap operation takes longer time to complete.

After the swap completed we can analyze the Request Tracing logs to confirm that the warmup-cache.php URL has been hit prior to the swap. Note that we need to get those log files from the site in the production slot now.

Looking through the logs we can see the following:

  • The first warm up request is made to the web site. Notice the user agent value set to “SiteWarmup”:
  • Another log file shows that the appInit module has started and made an HTTP request to the warmup-cache.php around the same time. That request has the host name I specified in the web.config file. Also the user-agent is different.

    As expected that request took around 30 seconds.

That simple example demonstrates how to use IIS Application Initialization Module with Azure Web App deployment slots to ensure that the application in the slot is completely warmed up.

The post How to warm up Azure Web App during deployment slots swap appeared first on RuslanY Blog.

]]>
https://ruslany.net/2015/09/how-to-warm-up-azure-web-app-during-deployment-slots-swap/feed/ 42