The Azure Python SDK is a set of libraries and packages that allow developers to interact with Microsoft Azure services using the Python programming language. It simplifies the process of integrating Python applications with Azure services by providing a set of high-level abstractions and APIs. With the SDK, developers can programmatically manage and interact with Azure resources, such as virtual machines, storage accounts, databases, and other cloud services.
To use the Azure Python SDK, developers typically install the required Python packages using a package manager like pip. They can then import the relevant modules into their Python code and use the classes provided and methods to interact with Azure services.
If we talk about Azure Container Apps, Microsoft provides comprehensive documentation and samples to help developers get started with the Azure Python SDK.
In this blog, we will be looking at how to create Container Apps using Azure Python SDK.
Getting Started
Prerequisites
It is assumed here that you already have an existing Azure Subscription, Resource Group, Container App Environment and a Container Registry available. Also, we will be using a Windows machine here to run the file which has Python version > 3.7 installed.
Here as an example, we will be creating an Azure Container App via the Azure Python SDK. To run the file, we would be using Azure CLI. This has been tested with the AZ CLI version 2.56. Also, make sure you have logged in with az login before running any az command else you could get an error stating EnvironmentCredential authentication unavailable. Environment variables are not fully configured.
Package Installation
Install the packages that will be used for managing the resources. The Azure Identity Package is needed almost every time. We would be using the Azure Container App package along with it.
pip install azure-identity
pip install azure-mgmt-appcontainers
Authentication
There are two options that can be used for authenticating. Authentication via Subscription ID and Authentication via Service Principal. In this example, we will be using Subscription ID for authenticating to Azure. We will look at the Authentication with MSI/Service Principal in the next part of this blog.
You can specify the Subscription ID as an Environment Variable or use it directly in the code. Both the examples are provided below.
from azure.identity import DefaultAzureCredential
from azure.mgmt.appcontainers import ContainerAppsAPIClient
import os
sub_id = os.getenv("AZURE_SUBSCRIPTION_ID")
client = ContainerAppsAPIClient(credential=DefaultAzureCredential(), subscription_id=sub_id)
from azure.identity import DefaultAzureCredential
from azure.mgmt.appcontainers import ContainerAppsAPIClient
client = ContainerAppsAPIClient(credential=DefaultAzureCredential(),subscription_id="<YOUR_SUBSCRIPTION_ID>")
Python File
We will be using the following file for our management tasks specified above. I am naming this file as containerapp.py
from azure.identity import DefaultAzureCredential
from azure.mgmt.appcontainers import ContainerAppsAPIClient
def main():
client = ContainerAppsAPIClient(
credential=DefaultAzureCredential(),
subscription_id="<YOUR_SUBSCRIPTION_ID>"
)
response = client.container_apps.begin_create_or_update(
resource_group_name="defaultrg",
container_app_name="containerapp-test",
container_app_envelope={
"location": "East US 2",
"properties": {
"configuration": {
"ingress": {
"external": True,
"targetPort": 80,
"transport": "http",
"stickySessions": {
"affinity": "none"
}
}
},
"environmentId": "/subscriptions/<YOUR_SUBSCRIPTION_ID>/resourceGroups/defaultrg/providers/Microsoft.App/managedEnvironments/defaultcaenv",
"template": {
"containers": [
{
"image": "docker.io/nginx:latest",
"name": "testapp4",
"resources": {
"cpu": 0.25,
"memory": ".5Gi"
}
}
]
},
},
},
).result()
print(response)
if __name__ == "__main__":
main()
In the above file, we are using a Public Repository (DockerHub) as our image source. If you want to use your private Azure Container Registry as an image source, the template section must include the auth configuration.
"template": {
"containers": [
{
"image": "nginx:latest",
"name": "containerapp-test",
"resources": {
"cpu": 0.25,
"memory": ".5Gi"
},
"registries": {
"server": "https://<YOUR_ACR_NAME>.azurecr.io",
"username": "<YOUR_ACR_USERNAME>",
"passwordSecretRef": "acr-password"
}
}
],
"secrets": [
{
"name": "acr-password",
"value": "<YOUR_ACR_PASSWORD>"
},
],
}
The above configuration assumes that there is an image called "nginx" with the tag "latest" in your ACR. Also, the ACR has admin credentials enabled. (Ref..)
After editing the python management file, we can run it simply by using the command.
python containerapp.py
On successful run, the result will be printed in json format on the cli.
Troubleshooting
In some cases, during an error, restarting the Azure CLI can help. I am listing some common scenarios that we usually see while working with the SDK.
InvalidAuthenticationTokenTenant
The error message suggests that the access token is from the wrong issuer, and it must match one of the tenants associated with this subscription. It is usually seen when the Subscription ID on the file does not match the account you've logged in. Re-logging with the correct account may help. (az logout & az login)
InvalidParameterValueInContainerTemplate
The error message noted two issues. Possible invalid or missing image or an issue with authentication. Please check any typo on the 'registryPassword'. Apart from that, if you are using any external public registry like DockerHub, please make sure that the full repository URL is mentioned in the 'image' parameter. Also, while using ACR with anonymous pull disabled (Ref..), make sure that only the image and the tag is mentioned in its value.
Using Azure Python SDK to manage Azure Container Apps - Part 2
Updated Feb 22, 2024
Version 13.0ractando
Microsoft
Joined September 30, 2022
Apps on Azure Blog
Follow this blog board to get notified when there's new activity