In the post Using Python with Google Colab for Azure Projects, we wrote a small program that connects Python running in Colab to Azure using Device Code authentication. Unlike the earlier example where we relied on an existing CLI login, here we use a device code flow — perfect for environments like Colab where you don’t have a local Azure CLI session to authenticate against.
Let’s walk through the program step by step, looking at it from both the Python and the Azure perspective.
Recap: The Program
from azure.identity import DeviceCodeCredential
from azure.mgmt.resource import ResourceManagementClient
# Replace with your subscription ID and tenant ID
subscription_id = "YOUR_SUBSCRIPTION_ID"
tenant_id = "YOUR_TENANT_ID"
def show_message(verification_uri, user_code, expires_on):
print(f"To authenticate, visit: {verification_uri}")
print(f"Enter the code: {user_code}")
print(f"(Code expires on: {expires_on})")
# Authenticate with tenant-specific credentials
credential = DeviceCodeCredential(
tenant_id=tenant_id,
prompt_callback=show_message
)
# Example: create a client
client = ResourceManagementClient(credential, subscription_id)
# Creating a resource group (this first SDK call will trigger login)
for rg in client.resource_groups.list():
print(rg.name)
# Creating a resource group - Run from a different cell later
resource_group_params = {"location": "eastus"}
client.resource_groups.create_or_update("myColabResourceGroup", resource_group_params)
print("Resource Group created successfully!")
Breaking It Down
1. Imports
from azure.identity import DeviceCodeCredential
from azure.mgmt.resource import ResourceManagementClient
Python perspective:
We’re importing two classes from external modules. DeviceCodeCredential handles authentication, while ResourceManagementClient provides access to Azure Resource Manager (ARM) for managing resources. Without these imports, Python wouldn’t recognize these names.
Azure perspective:
These are your Azure SDK entry points. One manages sign-in (via device code flow), and the other communicates with Azure Resource Manager, which is the central control plane for all Azure resources.
2. Setting Variables
subscription_id = "YOUR_SUBSCRIPTION_ID"
tenant_id = "YOUR_TENANT_ID"
Python perspective:
Here we create variables to hold strings. Variables make code reusable by avoiding repetition.
Azure perspective:
The subscription_id identifies which subscription to target. The tenant_id ensures the authentication process happens against the right Azure Active Directory tenant (important when you belong to multiple directories).
3. Defining a Callback Function
def show_message(verification_uri, user_code, expires_on):
print(f"To authenticate, visit: {verification_uri}")
print(f"Enter the code: {user_code}")
print(f"(Code expires on: {expires_on})")
Python perspective:
Here we define a function named show_message. Functions in Python are reusable blocks of code. What’s special is that this one is used as a callback function: instead of you calling it directly, you pass it to another piece of code (the Azure SDK). Later, when Azure generates login details, the SDK will call back this function automatically with the right arguments (verification_uri, user_code, expires_on).
It’s important to note that there is no special syntax for defining a callback function in Python. A callback is defined the same way as any other function using def. The difference lies in how it’s used:
- With a regular function, you call it yourself (e.g.,
greet("Heartin")). - With a callback function, you hand it over to another piece of code, and that code decides when to execute it.
This shows two important Python ideas:
- First-class functions — In Python, functions can be treated like variables: you can pass them around, store them, or give them to other functions.
- Event-style programming — By giving the SDK your function, you let it decide when to execute it. Your function becomes a hook that runs at the right time.
Azure perspective:
At this step, no Azure communication has happened yet. What you’re doing is preparing a hook for Azure’s Device Code Flow.
When the authentication process starts, Azure will send three values into your callback:
verification_uri→ The special login URL (oftenhttps://microsoft.com/devicelogin) where the user must go to sign in.user_code→ A unique one-time code the user must enter on that page, which ties their login back to your script.expires_on→ The exact time when the code expires (typically within 15 minutes). After that, a new code must be requested.
Your function simply decides how to present these values to the user — in this example, they’re printed to the Colab console.
4. Creating Credentials
credential = DeviceCodeCredential(
tenant_id=tenant_id,
prompt_callback=show_message
)
Python perspective
Now we are creating an object called credential using the DeviceCodeCredential class.
- In Python, this is just like creating an instance of any other class (e.g.,
person = Person(name, age)). - You pass two arguments:
tenant_id→ a string variable we defined earlier that identifies your Azure tenant.prompt_callback=show_message→ this links the callback function you defined earlier.
The result is a credential object that can be reused wherever authentication is needed. It holds the logic for how login will work, but it doesn’t log in yet — it’s just prepared and ready.
Azure perspective
Here’s where Azure truly enters the picture:
DeviceCodeCredentialtells the Azure SDK: “Authenticate me using the Device Code flow.”- By providing
tenant_id, you scope the login process to the correct Azure Active Directory tenant. - By providing
prompt_callback, you give Azure’s SDK the hook it needs to display the login instructions (that URL, user code, and expiry).
When authentication is triggered later (e.g., when you call a client method), Azure will generate the device code, pass it to your show_message function, and then complete the login once the user signs in on the given URL with the code.
👉 Key takeaway: In this step you are not logging in yet. You are setting up the authentication mechanism — telling Azure how you want to log in (device code) and where the login instructions should be shown (via your callback).
5. Building the Client
client = ResourceManagementClient(credential, subscription_id)
Python perspective:
Here we create a ResourceManagementClient object, passing in our credential and subscription ID. Like before, a constructor (__init__) sets up the object for immediate use.
Azure perspective:
The ResourceManagementClient acts as a gateway to ARM. With both authentication (credential) and scope (subscription ID) provided, it can securely send API requests to manage Azure resources.
5. Creating the Client
client = ResourceManagementClient(credential, subscription_id)
Python perspective
We instantiate a ResourceManagementClient using the credential and subscription ID. This client object is now our gateway to Azure Resource Manager.
Azure perspective
The client is bound to your subscription and will use the device code credential for every API call. The actual login will be triggered the first time the client makes a call that requires authentication.
6. Listing Resource Groups
for rg in client.resource_groups.list():
print(rg.name)
Python perspective
This is a simple for loop. The method client.resource_groups.list() returns an iterable of resource group objects, and for each object (rg) we print its .name property. From Python’s side, it’s just looping through a list of objects.
Azure perspective
Here’s where Azure truly comes into play. The call client.resource_groups.list() does two things:
- Triggers Authentication: This is the first time your script contacts Azure. Since the client needs to prove your identity, the SDK calls your callback function, showing the login URL and code. Once you complete login in your browser, the code continues.
- Retrieves Data: After authentication, the SDK calls Azure Resource Manager (ARM) to fetch all resource groups in your subscription. Each result object contains details such as
name,location, andtags. We’re only printing the names here for simplicity.
Let us also explore some Azure concepts discussed here:
- A resource group is a logical container for Azure resources such as VMs, storage, and databases.
- Note: When we create a resource group, if a resource group with the same name already exists, Azure simply updates its properties rather than throwing an error.
7. Cleaning Up (Optional)
This cleanup step was not part of the original Colab code example, but it’s included here as a good practice.
client.resource_groups.begin_delete("myColabResourceGroup").result()
print("Resource Group deleted successfully!")
Python perspective
begin_delete()starts an asynchronous deletion of the resource group.- Adding
.result()makes the script wait until the deletion is finished. - The
printmessage confirms success once Azure reports the deletion is complete.
Azure perspective
- Deleting a resource group also deletes all the resources inside it — so it’s a powerful but destructive operation.
- This is especially useful in demos or training sessions, where you don’t want to leave unused resources consuming costs.
- Depending on what’s inside, deletion may take a few seconds to several minutes.
Why Device Code Flow?
- Perfect for Colab and remote environments
In places like Google Colab, JupyterHub, or remote servers, you don’t have a local Azure CLI or browser session. Device Code Flow lets you authenticate out-of-band through any browser, which makes it ideal. - No secrets hardcoded in code
Unlike client secret–based auth, you don’t need to embed usernames, passwords, or app secrets in your notebook. This keeps code secure and safe to share. - Secure and multi-platform
Authentication can be completed on any device with a browser — your laptop, phone, or even a tablet. That flexibility makes it more secure and more user-friendly. - Great for demos and teaching
Students or colleagues can follow along by simply visiting a URL and pasting a one-time code. No CLI setup, no environment variables required.
Alternatives to Device Code Flow
- Azure CLI Credential (
AzureCliCredential)
Uses your already-signed-in Azure CLI session. Great for local development, but not available in Colab or other headless environments. - Interactive Browser Credential (
InteractiveBrowserCredential)
Opens a local browser window for login. Works well on your own laptop, but not in cloud-hosted notebooks where no GUI browser exists. - Managed Identity Credential (
ManagedIdentityCredential)
Best in production when your code is running inside Azure (e.g., on a VM, App Service, or Function). The environment provides the identity automatically. - Client Secret / Certificate Credential (
ClientSecretCredential,CertificateCredential)
Requires registering an app in Azure AD and securely storing secrets or certificates. Good for automated services, but less beginner-friendly for learning scenarios.
👉 Summary: Device Code Flow is the most convenient and secure option for Colab and remote environments, while other flows are better suited to local development (CLI, browser) or production deployments (managed identities, service principals).
Conclusion
In this walkthrough, we explored how to authenticate to Azure from Python in Google Colab using the Device Code Flow. Step by step, we looked at:
- From the Python perspective — how to structure imports, variables, functions, and objects, and how callbacks let external libraries “call back” into your code.
- From the Azure perspective — how Device Code login connects Colab to Azure Active Directory, enabling secure access to Azure Resource Manager without embedding secrets or relying on the Azure CLI.
With this approach, you can authenticate cleanly in environments where the CLI or a browser session isn’t available. Once authenticated, the same credential object works across Azure SDK clients — letting you list resource groups, create new ones, manage resources, and expand into other Azure services.
👉 Next steps: Try extending the sample to work with other SDKs like Storage, Compute, or Key Vault, and see how the same authentication pattern powers all your cloud interactions.