Azure Python SDK: 'ServicePrincipalCredentials' object has no attribute 'get_token'

The Azure libraries for Python are currently being updated to share common cloud patterns such as authentication protocols, logging, tracing, transport protocols, buffered responses, and retries.

This would change the Authentication mechanism a bit as well. In the older version, ServicePrincipalCredentials in azure.common was used for authenticating to Azure and creating a service client.

In the newer version, the authentication mechanism has been re-designed and replaced by azure-identity library in order to provide unified authentication based on Azure Identity for all Azure SDKs. Run pip install azure-identity to get the package.

In terms of code, what then was:

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient

credentials = ServicePrincipalCredentials(
    client_id='xxxxx',
    secret='xxxxx',
    tenant='xxxxx'
)

compute_client = ComputeManagementClient(
    credentials=credentials,
    subscription_id=SUBSCRIPTION_ID
)

is now:

from azure.identity import ClientSecretCredential
from azure.mgmt.compute import ComputeManagementClient

credential = ClientSecretCredential(
    tenant_id='xxxxx',
    client_id='xxxxx',
    client_secret='xxxxx'
)

compute_client = ComputeManagementClient(
    credential=credential,
    subscription_id=SUBSCRIPTION_ID
)

You can then use the list_all method with compute_client to list all VMs as usual:

# List all Virtual Machines in the specified subscription
def list_virtual_machines():
    for vm in compute_client.virtual_machines.list_all():
        print(vm.name)

list_virtual_machines()

References:

  • Azure SDK for Python on GitHub
  • Migration Guide - Resource Management
  • How to authenticate and authorize Python apps on Azure
  • Example: Use the Azure libraries to provision a virtual machine