Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This example shows how to use the Azure SDK management libraries in a Python script to create and deploy a web app to Azure App Service, with the app code pulled from a GitHub repository.
The Azure SDK for Python includes management libraries (namespaces beginning with azure-mgmt
) that let you automate resource configuration and deployment — similar to what you can do with the Azure portal, Azure CLI, or ARM templates. For examples, see Quickstart: Deploy a Python (Django or Flask) web app to Azure App Service.
1: Set up your local development environment
If you haven't already, set up an environment where you can run this code. Here are some options:
Configure a Python virtual environment using
venv
or your tool of choice. You can create the virtual environment locally or in Azure Cloud Shell and run the code there. Be sure to activate the virtual environment to start using it. To install python, see Install Python.python -m venv .venv source .venv/bin/activate # Linux or macOS .venv\Scripts\activate # Windows
Use a conda environment. To install Conda, see Install Miniconda.
Use a Dev Container in Visual Studio Code or GitHub Codespaces.
2: Install the required Azure library packages
Create a file named requirements.txt with the following contents:
azure-mgmt-resource
azure-mgmt-web
azure-identity
In your local development environment, install the requirements using the following code:
pip install -r requirements.txt
3: Fork the sample repository
Visit https://github.com/Azure-Samples/python-docs-hello-world and fork the repository into your own GitHub account. Using a fork ensures that you have the necessary permissions to deploy the app to Azure.
Next, create an environment variable named
REPO_URL
and set it to the URL of your forked repository. This variable is required by the example code in the next section.
export REPO_URL=<url_of_your_fork>
export AZURE_SUBSCRIPTION_ID=<subscription_id>
4: Write code to create and deploy a web app
Create a Python file named provision_deploy_web_app.py and add the following code. The in-line comments explain what each part of the script does. The REPO_URL
and AZURE_SUBSCRIPTION_ID
environment variables should already be set in the previous step.
import random, os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.web import WebSiteManagementClient
# Acquire a credential object using CLI-based authentication.
credential = AzureCliCredential()
# Retrieve subscription ID from environment variable
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
# Constants we need in multiple places: the resource group name and the region
# in which we provision resources. You can change these values however you want.
RESOURCE_GROUP_NAME = 'PythonAzureExample-WebApp-rg'
LOCATION = "centralus"
# Step 1: Provision the resource group.
resource_client = ResourceManagementClient(credential, subscription_id)
rg_result = resource_client.resource_groups.create_or_update(RESOURCE_GROUP_NAME,
{ "location": LOCATION })
print(f"Provisioned resource group {rg_result.name}")
# For details on the previous code, see Example: Provision a resource group
# at https://docs.microsoft.com/azure/developer/python/azure-sdk-example-resource-group
#Step 2: Provision the App Service plan, which defines the underlying VM for the web app.
# Names for the App Service plan and App Service. We use a random number with the
# latter to create a reasonably unique name. If you've already provisioned a
# web app and need to re-run the script, set the WEB_APP_NAME environment
# variable to that name instead.
SERVICE_PLAN_NAME = 'PythonAzureExample-WebApp-plan'
WEB_APP_NAME = os.environ.get("WEB_APP_NAME", f"PythonAzureExample-WebApp-{random.randint(1,100000):05}")
# Obtain the client object
app_service_client = WebSiteManagementClient(credential, subscription_id)
# Provision the plan; Linux is the default
poller = app_service_client.app_service_plans.begin_create_or_update(RESOURCE_GROUP_NAME,
SERVICE_PLAN_NAME,
{
"location": LOCATION,
"reserved": True,
"sku" : {"name" : "B1"}
}
)
plan_result = poller.result()
print(f"Provisioned App Service plan {plan_result.name}")
# Step 3: With the plan in place, provision the web app itself, which is the process that can host
# whatever code we want to deploy to it.
poller = app_service_client.web_apps.begin_create_or_update(RESOURCE_GROUP_NAME,
WEB_APP_NAME,
{
"location": LOCATION,
"server_farm_id": plan_result.id,
"site_config": {
"linux_fx_version": "python|3.8"
}
}
)
web_app_result = poller.result()
print(f"Provisioned web app {web_app_result.name} at {web_app_result.default_host_name}")
# Step 4: deploy code from a GitHub repository. For Python code, App Service on Linux runs
# the code inside a container that makes certain assumptions about the structure of the code.
# For more information, see How to configure Python apps,
# https://docs.microsoft.com/azure/app-service/containers/how-to-configure-python.
#
# The create_or_update_source_control method doesn't provision a web app. It only sets the
# source control configuration for the app. In this case we're simply pointing to
# a GitHub repository.
#
# You can call this method again to change the repo.
REPO_URL = os.environ["REPO_URL"]
poller = app_service_client.web_apps.begin_create_or_update_source_control(RESOURCE_GROUP_NAME,
WEB_APP_NAME,
{
"location": "GitHub",
"repo_url": REPO_URL,
"branch": "master",
"is_manual_integration": True
}
)
sc_result = poller.result()
print(f"Set source control on web app to {sc_result.branch} branch of {sc_result.repo_url}")
# Step 5: Deploy the code using the repository and branch configured in the previous step.
#
# If you push subsequent code changes to the repo and branch, you must call this method again
# or use another Azure tool like the Azure CLI or Azure portal to redeploy.
# Note: By default, the method returns None.
app_service_client.web_apps.sync_repository(RESOURCE_GROUP_NAME, WEB_APP_NAME)
print(f"Deploy code")
This code uses CLI-based authentication (using AzureCliCredential
) because it demonstrates actions that you might otherwise do with the Azure CLI directly. In both cases, you're using the same identity for authentication. Depending on your environment, you might need to run az login
first to authenticate.
To use such code in a production script (for example, to automate VM management), use DefaultAzureCredential
(recommended) with a service principal based method as described in How to authenticate Python apps with Azure services.
Reference links for classes used in the code
- AzureCliCredential (azure.identity)
- ResourceManagementClient (azure.mgmt.resource)
- WebSiteManagementClient (azure.mgmt.web import)
5: Run the script
python provision_deploy_web_app.py
6: Verify the web app deployment
To view the deployed website, run the following command:
az webapp browse --name <PythonAzureExample-WebApp-12345> --resource-group PythonAzureExample-WebApp-rg
Replace the web app name (--name
) with the value generated by the script.
You don’t need to change the resource group name (--resource-group
) unless you changed it in the script. When you open the site, you should see “Hello, World!” in your browser.
Tip
If you don't see the expected output, wait a few minutes and try again.
If you're still not seeing the expected output:
- Go to the Azure portal.
- Navigate to Resource groups, and locate the resource group you created.
- Select the resource group to view its resources. Make sure it includes both an App Service Plan and an App Service.
- Select the App Service, and then go to Deployment Center.
- Open the logs tab to check the deployment logs for any errors or status updates.
7: Redeploy the web app code (optional)
The script provisions all the necessary resources to host your web app and configures the deployment source to use your forked repository using manual integration. With manual integration, you need to manually trigger the web app to pull updates from the specified repository and branch.
The script uses the WebSiteManagementClient.web_apps.sync_repository method to trigger the web app to pull code from your repository. If you make further changes to your code, you can redeploy by calling this API again, or by using other Azure tools such as the Azure CLI or the Azure portal.
You can redeploy your code using the Azure CLI by running the az webapp deployment source sync command:
az webapp deployment source sync --name <PythonAzureExample-WebApp-12345> --resource-group PythonAzureExample-WebApp-rg
You don’t need to change the resource group name (--resource-group
) unless you changed it in the script.
To deploy your code from Azure portal:
- Go to the Azure portal.
- Navigate to Resource groups, and locate the resource group you created.
- Select the resource group name to view its resources. Make sure it includes both an App Service Plan and an App Service.
- Select the App Service, and then go to Deployment Center.
- On the top menu, select Sync to trigger the deployment of your code.
8: Clean up resources
az group delete --name PythonAzureExample-WebApp-rg --no-wait
You do not need to change resource group name (--resource-group
option) unless you changed it in the script.
If you no longer need the resource group created in this example, you can delete it by running the az group delete command. While resource groups don’t incur ongoing charges, it’s a good practice to clean up any unused resources. Use the --no-wait
argument to immediately return control to the command line without waiting for the deletion to complete.
You can also delete a resource group programmatically using the ResourceManagementClient.resource_groups.begin_delete
method.
See also
- Example: Create a resource group
- Example: List resource groups in a subscription
- Example: Create Azure Storage
- Example: Use Azure Storage
- Example: Create and query a MySQL database
- Example: Create a virtual machine
- Use Azure Managed Disks with virtual machines
- Complete a short survey about the Azure SDK for Python