Azure App Service Deploy task

Azure Pipelines

Use this task to deploy to a range of App Services on Azure. The task works on cross-platform agents running Windows, Linux, or Mac and uses several different underlying deployment technologies.

The task works for ASP.NET, ASP.NET Core, PHP, Java, Python, Go, and Node.js based web applications.

The task can be used to deploy to a range of Azure App Services such as:

Prerequisites for the task

The following prerequisites must be set up in the target machine(s) for the task to work correctly.

  • App Service instance. The task is used to deploy a Web App project or Azure Function project to an existing Azure App Service instance, which must exist before the task runs. The App Service instance can be created from the Azure portal and configured there. Alternatively, the Azure PowerShell task can be used to run AzureRM PowerShell scripts to provision and configure the Web App.

  • Azure Subscription. To deploy to Azure, an Azure subscription must be linked to the pipeline. The task does not work with the Azure Classic service connection, and it will not list these connections in the settings of the task.

ParametersDescription
ConnectionType
(Connection type)
(Required) Select the service connection type to use to deploy the Web App.
Default value: AzureRM
Connected
ServiceName

(Azure subscription)
(Required if ConnectionType = AzureRM) Select the Azure Resource Manager subscription for the deployment.
Argument aliases: azureSubscription
PublishProfilePath
(Publish profile path)
(Required if ConnectionType = PublishProfile) The path to the file containing the publishing information.
Default value:$(System.DefaultWorkingDirectory)/**/*.pubxml
PublishProfilePassword
(Publish profile password)
(Required if ConnectionType = PublishProfile) The password for the profile file. Consider storing the password in a secret variable and using that variable here. Example: $(Password)
WebAppKind
(App Service type)
(Required if ConnectionType = AzureRM) Choose from Web App On Windows, Web App On Linux, Web App for Containers, Function App, Function App on Linux, Function App for Containers and Mobile App
Default value: webApp
Argument aliases: appType
WebAppName
(App Service name)
(Required if ConnectionType = AzureRM) Enter or select the name of an existing Azure App Service. Only App Services based on the selected app type will be listed.
DeployTo
SlotOrASEFlag

(Deploy to Slot or App Service Environment)
(Optional) Select the option to deploy to an existing deployment slot or Azure App Service environment. For both the targets, the task requires a Resource Group name.
If the deployment target is a slot, by default the deployment is to the production slot. Any other existing slot name can be provided.
If the deployment target is an Azure App Service environment, leave the slot name as production and specify just the Resource Group name.
Default value: false
Argument aliases: deployToSlotOrASE
ResourceGroupName
(Resource group)
(Required if DeployToSlotOrASEFlag = true) The Resource Group name is required when the deployment target is either a deployment slot or an App Service environment. Enter or select the Azure Resource Group that contains the Azure App Service specified above.
SlotName
(Slot)
(Required, if DeployToSlotOrASEFlag = true) Enter or select an existing slot other than the production slot.
Default value: production
DockerNamespace
(Registry or Namespace)
(Required if WebAppKind = webAppContainer
or WebAppkind = functionAppContainer) A globally unique top-level domain name for your specific registry or namespace. Note: the fully-qualified image name will be of the format: {registry or namespace}/{repository}:{tag}. For example, myregistry.azurecr.io/nginx:latest
DockerRepository
(Image)
(Required if WebAppKind = webAppContainer
or WebAppkind = functionAppContainer) Name of the repository where the container images are stored. Note: the fully-qualified image name will be of the format: {registry or namespace}/{repository}:{tag}. For example, myregistry.azurecr.io/nginx:latest
DockerImageTag
(Tag)
(Optional) Tags are optional, but are the mechanism that registries use to apply version information to Docker images. Note: the fully-qualified image name will be of the format: {registry or namespace}/{repository}:{tag}. For example, myregistry.azurecr.io/nginx:latest
VirtualApplication
(Virtual application)
(Optional) Specify the name of the Virtual Application that has been configured in the Azure portal. This option is not required for deployments to the website root. The Virtual Application must have been configured before deployment of the web project.
Package
(Package or folder)
(Required if ConnectionType = PublishProfile or WebAppKind = webApp, apiApp, functionApp, mobileApp, webAppLinux, or functionAppLinux) File path to the package, or to a folder containing App Service contents generated by MSBuild, or to a compressed zip or war file.
Build variables or release variables) and wildcards are supported. For example, $(System.DefaultWorkingDirectory)/**/*.zip or $(System.DefaultWorkingDirectory)/**/*.war
Default value: $(System.DefaultWorkingDirectory)/**/*.zip
Argument aliases: packageForLinux
RuntimeStack
(Runtime Stack)
(Optional) Select the framework and version. This is for WebApp for Linux.
RuntimeStackFunction
(Runtime Stack)
(Optional) Select the framework and version. This is for Function App on Linux.
StartupCommand
(Startup command)
(Optional) Enter the start up command.
ScriptType
(Deployment script type)
(Optional) Customize the deployment by providing a script that runs on the Azure App Service after successful deployment. Choose inline deployment script or the path and name of a script file. Learn more.
InlineScript
(Inline Script)
(Required if ScriptType == Inline Script) The script to execute. You can provide your deployment commands here, one command per line. See this example.
ScriptPath
(Deployment script path)
(Required if ScriptType == File Path) The path and name of the script to execute.
Web
ConfigParameters

(Generate web.config parameters for Python, Node.js, Go and Java apps)
(Optional) A standard web.config will be generated and deployed to Azure App Service if the application does not have one. The values in web.config can be edited and will vary based on the application framework. For example for Node.js applications, web.config will have startup file and iis_node module values. This edit feature is only for the generated web.config file. Learn more.
AppSettings
(App settings)
(Optional) Edit web app Application settings using the syntax -key value. Values containing spaces must be enclosed in double quotes. Examples: -Port 5000 -RequestTimeout 5000 and -WEBSITE_TIME_ZONE "Eastern Standard Time".
ConfigurationSettings
(Configuration settings)
(Optional) Edit web app configuration settings using the syntax -key value. Values containing spaces must be enclosed in double quotes. Example: -phpVersion 5.6 -linuxFxVersion: node|6.11
UseWebDeploy
(Select deployment method)
(Optional) If unchecked, the task auto-detects the best deployment method based on the app type, package format, and other parameters. Select the option to view the supported deployment methods, and choose one for deploying your app.
Argument aliases: enableCustomDeployment
DeploymentType
(Deployment method)
(Required if UseWebDeploy == true) Choose the deployment method for the app.
Default value: webDeploy
TakeAppOfflineFlag
(Take App Offline)
(Optional) Select this option to take the Azure App Service offline by placing an app_offline.htm file in the root directory before the synchronization operation begins. The file will be removed after the synchronization completes successfully.
Default value: true
SetParametersFile
(SetParameters file)
(Optional) location of the SetParameters.xml file to be used.
RemoveAdditional
FilesFlag

(Remove additional files at destination)
(Optional) Select the option to delete files on the Azure App Service that have no matching files in the App Service package or folder.
Note: This will also remove all files related to any extensions installed on this Azure App Service. To prevent this, set the Exclude files from App_Data folder checkbox.
Default value: false
ExcludeFiles
FromAppDataFlag

(Exclude files from the App_Data folder)
(Optional) Select the option to prevent files in the App_Data folder from being deployed to or deleted from the Azure App Service.
Default value: true
AdditionalArguments
(Additional arguments)
(Optional) Additional Web Deploy arguments following the syntax -key:value. These will be applied when deploying the Azure App Service. Example: -disableLink:AppPoolExtension -disableLink:ContentExtension. More examples.
Default value: -retryAttempts:6 -retryInterval:10000
RenameFilesFlag
(Rename locked files)
(Optional) Select this option to enable the MSDeploy flag MSDEPLOY_RENAME_LOCKED_FILES=1 in the Azure App Service application settings. When set, it enables MSDeploy to rename files that are locked during app deployment.
Default value: true
XmlTransformation
(XML transformation)
(Optional) The configuration transformations will be run for .Release.config and .{EnvironmentName}.config on the *.config files. Configuration transformations run before variable substitution. XML transformations are supported only for the Windows platform. Learn more.
Default value: false
Argument aliases: enableXmlTransform
XmlVariable
Substitution

(XML variable substitution)
(Optional) Variables defined in the build or release pipeline will be matched against the key or name entries in the appSettings, applicationSettings, and connectionStrings sections of any configuration file and parameters.xml file. Variable substitution runs after configuration transformations.
Note: if the same variables are defined in the release pipeline and in the stage, the stage variables will supersede the release pipeline variables. Learn more
Default value: false
Argument aliases: enableXmlVariableSubstitution
JSONFiles
(JSON variable substitution)
(Optional) Provide a newline-separated list of JSON files to substitute the variable values. Filenames must be relative to the root folder. To substitute JSON variables that are nested or hierarchical, specify them using JSONPath expressions. For example, to replace the value of ConnectionString in the sample below, define a variable named Data.DefaultConnection.ConnectionString in the build or release pipeline (or release pipelines stage).

{
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\SQLEXPRESS;Database=MyDB;Trusted_Connection=True"
    }
  }
}

Variable substitution runs after configuration transformations. Note: build and release pipeline variables are excluded from substitution. Learn more.

This YAML example deploys to an Azure Web App container (Linux).

pool:
  vmImage: Ubuntu-16.04

variables:
  azureSubscriptionEndpoint: Contoso
  DockerNamespace: contoso.azurecr.io
  DockerRepository: aspnetcore
  WebAppName: containersdemoapp

steps:

- task: AzureRMWebAppDeployment@4
  displayName: Azure App Service Deploy
  inputs:
    appType: webAppContainer
    ConnectedServiceName: $(azureSubscriptionEndpoint)
    WebAppName: $(WebAppName)
    DockerNamespace: $(DockerNamespace)
    DockerRepository: $(DockerRepository)
    DockerImageTag: $(Build.BuildId)
  • To deploy to a specific app type, set appType to any of the following accepted values: webApp (Web App on Windows), webAppLinux (Web App on Linux), webAppContainer (Web App for Containers - Linux), functionApp (Function App on Windows), functionAppLinux (Function App on Linux), functionAppContainer (Function App for Containers - Linux), apiApp (API App), mobileApp (Mobile App). If not mentioned, webApp is taken as the default value.

  • To enable any advance deployment options, add the parameter enableCustomDeployment: true and include the below parameters as needed.

        # deploymentMethod: 'runFromPackage' # supports zipDeploy as well
        # appOffline: boolean    # Not applicable for 'runFromPackage'
        # setParametersFile: string
        # removeAdditionalFilesFlag: boolean
        # additionalArguments: string
    

Output Variables

  • Web App Hosted URL: Provide a name, such as FabrikamWebAppURL, for the variable populated with the Azure App Service Hosted URL. The variable can be used as $(variableName.AppServiceApplicationUrl), for example $(FabrikamWebAppURL.AppServiceApplicationUrl), to refer to the hosted URL of the Azure App Service in subsequent tasks.

Usage notes

  • The task works with the Azure Resource Manager APIs only.
  • To ignore SSL errors, define a variable named VSTS_ARM_REST_IGNORE_SSL_ERRORS with value true in the release pipeline.
  • For .NET apps targeting Web App on Windows, avoid deployment failure with the error ERROR_FILE_IN_USE by ensuring that Rename locked files and Take App Offline settings are enabled. For zero downtime deployment, use the slot swap option.
  • When deploying to an App Service that has Application Insights configured, and you have enabled Remove additional files at destination, ensure you also enable Exclude files from the App_Data folder in order to maintain the Application insights extension in a safe state. This is required because the Application Insights continuous web job is installed into the App_Data folder.

Sample Post deployment script

The task provides an option to customize the deployment by providing a script that will run on the Azure App Service after the app's artifacts have been successfully copied to the App Service. You can choose to provide either an inline deployment script or the path and name of a script file in your artifact folder.

This is very useful when you want to restore your application dependencies directly on the App Service. Restoring packages for Node, PHP, and Python apps helps to avoid timeouts when the application dependency results in a large artifact being copied over from the agent to the Azure App Service.

An example of a deployment script is:

@echo off
if NOT exist requirements.txt (
 echo No Requirements.txt found.
 EXIT /b 0
)
if NOT exist "$(PYTHON_EXT)/python.exe" (
 echo Python extension not available >&2
 EXIT /b 1
)
echo Installing dependencies
call "$(PYTHON_EXT)/python.exe" -m pip install -U setuptools
if %errorlevel% NEQ 0 (
 echo Failed to install setuptools >&2
 EXIT /b 1
)
call "$(PYTHON_EXT)/python.exe" -m pip install -r requirements.txt
if %errorlevel% NEQ 0 (
 echo Failed to install dependencies>&2
 EXIT /b 1
)

Deployment methods

Several deployment methods are available in this task. Web Deploy (msdeploy.exe) is the default. To change the deployment option, expand Additional Deployment Options and enable Select deployment method to choose from additional package-based deployment options.

Based on the type of Azure App Service and agent, the task chooses a suitable deployment technology. The different deployment technologies used by the task are:

By default, the task tries to select the appropriate deployment technology based on the input package type, App Service type, and agent operating system.

Auto Detect Logic

For windows based agents.

App Service typePackage typeDeployment Method
WebApp on Linux or Function App on LinuxFolder/Zip/jar
War
Zip Deploy
War Deploy
WebApp for Containers (Linux) or Function App for Containers (Linux)Update the App settingsNA
WebApp on Windows, Function App on Windows, API App, or Mobile AppWar
Jar
MsBuild package type or deploy to virtual application


Folder/Zip
War Deploy
Zip Deploy
Web Deploy

if postDeploymentScript == true, Zip Deploy
else, Run From Package

On non-Windows agents (for any App Service type), the task relies on Kudu REST APIs to deploy the app.

Web Deploy

Web Deploy (msdeploy.exe) can be used to deploy a Web App on Windows or a Function App to the Azure App Service using a Windows agent. Web Deploy is feature-rich and offers options such as:

  • Rename locked files: Rename any file that is still in use by the web server by enabling the msdeploy flag MSDEPLOY_RENAME_LOCKED_FILES=1 in the Azure App Service settings. This option, if set, enables msdeploy to rename files that are locked during app deployment.

  • Remove additional files at destination: Deletes files in the Azure App Service that have no matching files in the App Service artifact package or folder being deployed.

  • Exclude files from the App_Data folder: Prevent files in the App_Data folder (in the artifact package/folder being deployed) being deployed to the Azure App Service

  • Additional Web Deploy arguments: Arguments that will be applied when deploying the Azure App Service. Example: -disableLink:AppPoolExtension -disableLink:ContentExtension. For more examples of Web Deploy operation settings, see Web Deploy Operation Settings.

Install Web Deploy on the agent using the Microsoft Web Platform Installer. Web Deploy 3.5 must be installed without the bundled SQL support. There is no need to choose any custom settings when installing Web Deploy. Web Deploy is installed at C:\Program Files (x86)\IIS\Microsoft Web Deploy V3.

Kudu REST APIs

Kudu REST APIs work on both Windows and Linux automation agents when the target is a Web App on Windows, Web App on Linux (built-in source), or Function App. The task uses Kudu to copy files to the Azure App service.

Container Registry

Works on both Windows and Linux automation agents when the target is a Web App for Containers. The task updates the app by setting the appropriate container registry, repository, image name, and tag information. You can also use the task to pass a startup command for the container image.

Zip Deploy

Expects a .zip deployment package and deploys the file contents to the wwwroot folder of the App Service or Function App in Azure. This option overwrites all existing contents in the wwwroot folder. For more information, see Zip deployment for Azure Functions.

Run From Package

Expects the same deployment package as Zip Deploy. However, instead of deploying files to the wwwroot folder, the entire package is mounted by the Functions runtime and files in the wwwroot folder become read-only. For more information, see Run your Azure Functions from a package file.

War Deploy

Expects a .war deployment package and deploys the file content to the wwwroot folder or webapps folder of the App Service in Azure.

Troubleshooting

Error: Could not fetch access token for Azure. Verify if the Service Principal used is valid and not expired.

The task uses the service principal in the service connection to authenticate with Azure. If the service principal has expired or does not have permissions to the App Service, the task fails with the specified error. Verify validity of the service principal used and that it is present in the app registration. For more details, see Use Role-Based Access Control to manage access to your Azure subscription resources. This blog post also contains more information about using service principal authentication.

SSL error

To use a certificate in App Service, the certificate must be signed by a trusted certificate authority. If your web app gives you certificate validation errors, you're probably using a self-signed certificate. Set a variable named VSTS_ARM_REST_IGNORE_SSL_ERRORS to the value true in the build or release pipeline to resolve the error.

A release hangs for long time and then fails

This may be because there is insufficient capacity on your App Service Plan. To resolve this, you can scale up the App Service instance to increase available CPU, RAM, and disk space or try with a different App Service plan.

5xx Error Codes

If you are seeing a 5xx error, then check the status of your Azure service.

Error: No package found with specified pattern

Check if the package mentioned in the task is published as an artifact in the build or a previous stage and downloaded in the current job.

Error: Publish using zip deploy option is not supported for msBuild package type

Web packages created using MSBuild task (with default arguments) have a nested folder structure that can only be deployed correctly by Web Deploy. Publish to zip deploy option can not be used to deploy those packages. To convert the packaging structure, follow the below steps.

  • In Build Solution task, change the MSBuild Arguments to /p:DeployOnBuild=true /p:DeployDefaultTarget=WebPublish /p:WebPublishMethod=FileSystem /p:DeleteExistingFiles=True /p:publishUrl="$(System.DefaultWorkingDirectory)\WebAppContent"

  • Add Archive Task and change the inputs as follows:

    • Change Root folder or file to archive to $(System.DefaultWorkingDirectory)\WebAppContent Root folder or file to archive

    • Disable Prepend root folder name to archive paths option Prepend root folder name to archive paths

Web app deployment on Windows is successful but the app is not working

This may be because web.config is not present in your app. You can either add a web.config file to your source or auto-generate one using the File Transforms and Variable Substitution Options of the task.

  • Click on the task and go to Generate web.config parameters for Python, Node.js, Go and Java apps.

    Generate web.config parameters Dialog

  • Click on the more button Generate web.config parameters for Python, Node.js, Go and Java apps to edit the parameters.

    Drop Down Dialog

  • Select your application type from the drop down.

  • Click on OK. This will populate web.config parameters required to generate web.config.

ERROR_FILE_IN_USE

When deploying .NET apps to Web App on Windows, deployment may fail with error code ERROR_FILE_IN_USE. To resolve the error, ensure Rename locked files and Take App Offline options are enabled in the task. For zero downtime deployments, use slot swap.

You can also use Run From Package deployment method to avoid resource locking.

Web Deploy Error

If you are using web deploy to deploy your app, in some error scenarios Web Deploy will show an error code in the log. To troubleshoot a web deploy error see this.

Web app deployment on App Service Environment (ASE) is not working

  • Ensure that the Azure DevOps build agent is on the same VNET (subnet can be different) as the Internal Load Balancer (ILB) of ASE. This will enable the agent to pull code from Azure DevOps and deploy to ASE.
  • If you are using Azure DevOps, the agent neednt be accessible from internet but needs only outbound access to connect to Azure DevOps Service.
  • If you are using TFS/Azure DevOps Server deployed in a Virtual Network, the agent can be completely isolated.
  • Build agent must be configured with the DNS configuration of the Web App it needs to deploy to. Since the private resources in the Virtual Network don't have entries in Azure DNS, this needs to be added to the hosts file on the agent machine.
  • If a self-signed certificate is used for the ASE configuration, "-allowUntrusted" option needs to be set in the deploy task for MSDeploy.It is also recommended to set the variable VSTS_ARM_REST_IGNORE_SSL_ERRORS to true. If a certificate from a certificate authority is used for ASE configuration, this should not be necessary.

FAQs

How should I configure my service connection?

This task requires an Azure Resource Manager service connection.

How should I configure Web Job Deployment with Azure Application Insights?

When deploying to an App Service with Application Insights configured and you have enabled “Remove additional files at destination”, then you also need to enable “Exclude files from the App_Data folder” in order to keep the app insights extension in a safe state. This is required because App Insights continuous web job gets installed into the App_Data folder.

How should I configure my agent if it is behind a proxy while deploying to App Service?

When your self-hosted agent requires a web proxy, you can inform the agent about the proxy during configuration. This allows your agent to connect to Azure Pipelines or TFS through the proxy. Learn more about running a self-hosted agent behind a web proxy

Open source

This task is open source on GitHub. Feedback and contributions are welcome.