Home Azure Cloud Explaining the Python Program That Connects to Azure via CLI Login

Explaining the Python Program That Connects to Azure via CLI Login

190
0

In the post Getting Started with Azure CLI on Your Local Machine, we installed Python and set up a virtual environment. In the follow-up post Setting Up Python with Azure CLI and SDKs, we added the Azure SDKs and ran a simple program that relied on the CLI login for authentication. In this post, we’ll go a step further and dig into that program — explaining how it works from both the Python perspective and the Azure perspective.

Recap: The Program

from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient

# 👇 Replace with your own Subscription ID
subscription_id = "00000000-0000-0000-0000-000000000000"

credential = DefaultAzureCredential()
client = ResourceManagementClient(credential, subscription_id)

print("Resource groups:")
for rg in client.resource_groups.list():
    print(f"- {rg.name}")

Breaking It Down

Now that we’ve seen the Python program in action, let’s break it down into clear sections — imports, setting variables, creating credentials, building the client, and looping through results — and explore what each step means from both the Python perspective and the Azure perspective.

1. Imports

from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
  • Python perspective:
    import makes code from external modules available. Here, two classes are imported so they can be used directly in the script. Without these imports, Python would not recognize the names DefaultAzureCredential or ResourceManagementClient.
  • Azure perspective:
    These imported classes are your entry points to Azure. One handles authentication (DefaultAzureCredential) and the other lets you manage resources (ResourceManagementClient).

2. Setting Variables

subscription_id = "00000000-0000-0000-0000-000000000000"
  • Python perspective:
    A variable named subscription_id is created and assigned a string value. Variables store data in memory that you can reuse later.
  • Azure perspective:
    The subscription ID value is used in further operations and tells Azure which subscription to operate on when making requests.

3. Creating Credentials

credential = DefaultAzureCredential()
  • Python perspective:
    This creates an object called credential from the DefaultAzureCredential class. Creating an object (also called instantiating a class) means you now have a variable with methods and properties you can use.
  • Azure perspective:
    The DefaultAzureCredential class is a built-in credential provider in the Azure SDK. Its job is to automatically pick the best available authentication method without you needing to hardcode usernames, passwords, or secrets. This means you can use the same line of code everywhere — your laptop, a server, or an Azure-hosted service — and DefaultAzureCredential figures out the right way to log you in.
    In our case, since we previously ran az login on the same machine, it took the credentials directly from the Azure CLI session and converted them into an access token for the SDK.

4. Building the Client

client = ResourceManagementClient(credential, subscription_id)
  • Python perspective:
    Another object, client, is created from the ResourceManagementClient class. The constructor is given two arguments: the credential object and the subscription_id variable. A constructor in Python is a special method (named __init__) that runs automatically when you create an object from a class. Its role is to set up the new object with any values you pass in, so the object is ready to use right away.
  • Azure perspective:
    The ResourceManagementClient is part of the Azure SDK. It acts as a gateway to the Azure Resource Manager (ARM), which is the central service that manages all Azure resources.
  • By passing the credential, the client knows who you are and can request access tokens when needed.
  • By passing the subscription_id, it knows which subscription to target for every request.
  • Once created, this client provides methods to list, create, update, or delete resource groups and other resource-related operations. Under the hood, each method sends a REST API call to Azure Resource Manager, but you don’t have to deal with raw HTTP — the SDK handles that for you.

5. Looping Through Results

print("Resource groups:")
for rg in client.resource_groups.list():
    print(f"- {rg.name}")
  • Python perspective:
    • for rg in ...: is a loop that iterates over items in a collection.
    • print(f"...") outputs text, with the f string allowing you to insert values (here, rg.name) into the printed text.
  • This is a for loop in Python. It goes through each item returned by client.resource_groups.list().
  • Each item is stored in the variable rg during one pass of the loop.
  • Inside the loop, we print the name property of each rg object.
    This shows how loops help repeat an action for every element in a collection without writing the same code multiple times.
  • Azure perspective:
  • The call client.resource_groups.list() tells the ResourceManagementClient to fetch all resource groups in the specified subscription.
  • Behind the scenes, the client sends a request to the Azure Resource Manager (ARM) REST API.
  • ARM checks your permissions (from the credential) and then returns a list of resource group objects.
  • The loop then prints out each group’s name, but those objects can also contain other details (like location, tags, and provisioning state).

Conclusion

In this walkthrough, we broke down the Python program line by line, looking at it from two angles:

  • The Python perspective, which showed how classes, constructors, variables, loops, and objects work in a basic programming sense.
  • The Azure perspective, which explained how the Azure SDK uses those pieces to authenticate with the Azure CLI login, connect to Azure Resource Manager, and fetch resource groups.

By combining these two views, you can see not just how the code runs, but also how it translates into real actions in the cloud. This approach helps beginners learn both Python fundamentals and Azure concepts at the same time.

The key takeaway is that this program securely uses your Azure CLI login (no hardcoded secrets) and leverages the SDK to make resource management simpler than dealing with raw REST API calls.

From here, you can build on this foundation — for example, by exploring the properties of each resource group, creating or deleting groups, or expanding to other Azure services using their respective SDK clients.

References

Previous articleSetting Up Python with Azure CLI and SDKs
Next articleUsing Python with Jupyter Notebooks for Azure Projects
Heartin Kanikathottu
As a seasoned Cloud and Security Architect, I’ve led transformative initiatives in key roles, including Vice President at Morgan Stanley, Principal Architect at Societe Generale, and Tech Lead & Cloud Security Architect at VMware, among others. I’m also an internationally published author with multiple books available on platforms like Amazon and O'Reilly. Notably, one of my books was recognized as the 8th best cloud computing book of all time in 2020, reflecting the impact of my contributions to the field. With over 15 professional certifications from providers such as Microsoft (Azure), Amazon (AWS), Oracle (Java), Pivotal (Spring), and IBM, I bring a wealth of expertise to my work. Academically, I hold dual Master’s degrees in Cloud Computing and Data Analytics. I’m passionate about sharing knowledge and mentoring others, which is why I actively speak at global technical forums such as Tech Opportunities Fest at Platform Calgary, Google's Kubernetes Meetup, Java User Group, Elasticsearch Meetup, and the Agile India Conference.

LEAVE A REPLY

Please enter your comment!
Please enter your name here