Azure Account Authentication Using Python3

07 / Jul / 2022 by Ritika TTN 0 comments

Need for Authentication:

To communicate with Azure Resources we need to do authentication, suppose you have an application that monitors Azure resources. To fetch azure resources data from the azure account, we need a connection string or secrets to do Azure Authentication. Ather that, these all secrets are shared with the application developer who integrates secrets into the code itself. As we all know, Python is one of the most popular programming language because of its simplified syntax and it also provides great support for writing scripts to interact with cloud resources. 

Azure SDK is an Azure Software Development Kit for Python3, which allows Python developers to write software that makes use of Azure services.

The Azure Authentication process requires:

Step 1. Create Azure account

Step 2. Get Subscription and Tenant Id.

Step 3. Registered Your Application

Step 4. Create New Client Secret in Registered Application and Save Value Id.

Step 5. Grant Reader permission to Registered App.

Step 6. Now use Client Secret value, subscription, tenant, and Client(Application) Id in Azure SDK script to fetch Azure Resource data. (Here we are fetching a list of Azure VM using these keys).

Workflow Diagram to authenticate your azure account to interact with Azure Resources using Azure Python SDK

Step1: Create an Azure account 

Link: https://www.acronis.com/en-sg/articles/create-microsoft-azure-account/

Step2: Get a Subscription and Tenant Id

To get your Azure Subscription and Tenant Id of your Azure account, use your local terminal or use the azure cloud shell terminal in the Azure Portal.

Open your Azure portal → Go to Subscription → Copy and save your subscription id → then go to Azure Active Directory → Copy and save your tenant id for later use.

                                                                                             OR

Open your Azure Cloud Shell Terminal and use the below command to get your Account Subscription and Tenant Id.

> az account show

Step 3:  Registered Your Application

you must have sufficient permission to register your application in your Azure AD. If you have a user role, you must make sure that non-administrators can register applications. You can ask for an Application Developer Role.

You can also check your access by going into SubscriptionIAMview my access.

 To register your app in Azure Portal:

  1. Sign in to your Azure portal and go to Azure Active Directory
    From Manage, Select App Registration
  2. Select App RegistrationAdd New Registration
  3. Enter a name for the Application. ( Azure-Integration)
  4. In the Add a Redirect UrlAdd a Platformselect Web and add your app URL (https://xyz.com) as the sign-on URL and Create the Application → Register
  1. From Overview of Registered App, copy the Application/Client Id and save it anywhere for later use

Step4: Create New Client Secret in Registered Application and Save Value Id

To create a client secret associated with your app:

  1. In Azure, under the application, you have just created, select Certificates & Secrets
  2. Under these Certificates & SecretsAdd new Client Secret -> Give DescriptionSelect
    expiration time → Copy Value somewhere else because it hides sometimes 

Step5: Grant Reader permission to Registered App

      Grant Reader permission to your Application:

  1. Go to Subscriptions → and open the Subscription that you want Your app ( Monitoring Webapp ) to monitor.

  2. Click on Subscription → Select Access control (IAM)Add role AssignmentAdd Member Select your app and add and save

Step6: Fetch the number of VM’s data in our Azure Account using Azure SDK with Keys

resources.py :

from azure.mgmt.compute import ComputeManagementClient
from azure.common.credentials import ServicePrincipalCredentials
import os
Subscription_Id = os.environ[“subscription_id”]
Tenant_Id = os.environ[“tenant_id”]
Client_Id = os.environ[“client_id”]
Secret = os.environ[“secret”]

credential = ServicePrincipalCredentials(
        client_id=Client_Id,
        secret=Secret,
        tenant=Tenant_Id
        )

compute_client = ComputeManagementClient(credential, Subscription_Id)

vm_list = compute_client.virtual_machines.list('azure-poc')
# vm_list = compute_client.virtual_machines.list('resource_groupname')
i= 0
for vm in vm_list:
    array = vm.id.split("/")
    resource_group = array[4]
    vm_name = array[-1]
    statuses = compute_client.virtual_machines.instance_view(resource_group, vm_name).statuses
    status = len(statuses) >= 2 and statuses[1]

    if status and status.code == 'PowerState/running':
        print(vm_name)

Output

Rotate Client Secrets Credentials:

It will be required to update the application’s authentication credentials using the Azure Portal, once the client secret expires (the maximum expiration date available in Azure is 2 years). Go to App Registration → Select Your App → Go into Client Secret —>Edit the Client Secret field with the new value and confirm with Save Changes.

Use Case Of Managed Identity:

Using a managed identity, you can authenticate to any service that supports Azure AD authentication without exposing credentials.

Azure Managed Identity 

  • User Assigned Managed Identities 
  • System Assigned Managed Identities 

But as we can see, the system assigned managed not to work for us where you have to monitor thousands of services because we need to create thousands of managed identities for each azure resource to communicate with them.

Same, In the case of User assigned managed identity, we need to grant permission every time whenever newly resource group is created in our Azure Infra. So it is also not good, as we need to add every time newly created resource group. It is clearly seen that there is no other way to do authentication Using Python SDK except App Registration.

Can we Use Azure Key Vault to store secrets, Instead of passing Direct Client Id and Client Secret Id in code:

As we know, Azure Vault is the most secure way to handle such a situation in today’s scenarios. But it is not free to use, you have to pay $0.03 for a 10k transaction in the standard pricing tier. So It is not beneficial in that scenario where you have to fetch the secret key from the vault to communicate with azure resources more frequently.

No, We can’t fetch the ClientId and Client SecretId directly from Key Vault because Key Vault Url is not a Global URL, before accessing it we need to authenticate Key Vault and for authentication, we are using the app Registration Secret.

Conclusion

If you want to communicate with more than one service using the same credential in the entire subscription, then go with Azure App Registration Authentication. If your code runs in any Azure service, go with Azure Managed Identities Approach. If you want to store those credentials in Keyvault, then you need to authenticate the key vault first and then use their credentials in code but when your client’s secret expires you need to create a new Key vault again and provide the reader permission again to it.

 

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *