skip to Main Content

I’m looking for a way to programmatically log in to Azure without needing to install the Azure CLI. Currently, I use the following commands:

az login --service-principal -u <user_credentials> -p <password> --tenant <tenant_id>
az account set -s <subscription_id>

However, these require the Azure CLI to be pre-installed. Is there an alternative method to authenticate with the same credentials (service principal, tenant, subscription ID) in Python without relying on the Azure CLI? Any suggestions or guidance would be greatly appreciated. Thanks!

3

Answers


  1. For programmatically logging in and acquiring tokens in Python, the package you would want to use is azure-identity.

    Since you are using a Service Principal for logging in, you would want to use ClientSecretCredential to create a credential object which you would use later on with other Azure SDKs to authorize requests.

    Here’s some sample code:

    from azure.identity import ClientSecretCredential
    
    
       credential = ClientSecretCredential(
           tenant_id="<tenant_id>",
           client_id="<client_id>",
           client_secret="<client_secret>",
       )
    
    from azure.storage.queue import QueueServiceClient
    queue_service = QueueServiceClient(account_url="https://account.queue.core.windows.net", credential= credential)
    # Do some operations on queues now
    
    Login or Signup to reply.
  2. I would suggest that you check the following libraries and their documentation:

    They also come with code samples for different tasks.

    Login or Signup to reply.
  3. You can use clientId, clientSecret to get access_token, then request azure rest api with the access_token, which case azure cli installation is not required. Even many azure-related modules do not need to be installed, using the primitive method

    import requests
    import json
    
    clientId = ''
    clientSecret = ''
    tenantId = ''
    subscriptionId = ''
    
    token_url = f'https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token'
    graph_url = 'https://graph.microsoft.com/v1.0/'
    
    def get_access_token():
        data = {
            'grant_type': 'client_credentials',
            'client_id': clientId,
            'client_secret': clientSecret,
            'scope': 'https://management.azure.com/.default'
        }
        response = requests.post(token_url, data=data)
        response.raise_for_status()
        return response.json()['access_token']
    
    def get_azure_resource(url: str):
        access_token = get_access_token()
        headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json'
        }
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.json()
    
    try:
        resource_url = f'https://management.azure.com/subscriptions/{subscriptionId}?api-version=2022-12-01'
    
        resource_info = get_azure_resource(resource_url)
    
        print(json.dumps(resource_info, indent=4))
    except requests.exceptions.HTTPError as e:
        print(f'HTTP Error: {e}')
    except requests.exceptions.RequestException as e:
        print(f'Request Exception: {e}')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search