Search code examples
azure-managed-identityazure-ai

How to use Managed Identity for a Python application which uses an Azure AI service?


I am following this tutorial which explains how to access an Azure text analytics service from a Python application using service principal. In the end, a password is used. The approach works for dev/test but for prod, the recommended way is to use managed identities.

The service principal has get, list access to the key vault.

The process gives me some parameters of service principal which I use in the Python code:

{
  "appId": "...",
  "displayName": "api://ai-app-mc",
  "password": "...",
  "tenant": "..."
}

How do I go about using managed identities such that I can access an Azure AI service from Python code without having to store any password or key in the code or .env file?

The code in the tutorial runs from Visual Studio. If I want to use managed identities, can I still use Visual Studio do I need to deploy the application in a VM and then assign managed identity to the VM and then give the managed identify access to the AzureAI` service? The tasks I have done so far:

  • went to Azure AI service and enabled managed identify. I suppose this decides who can access the service.
  • I created a Cognitive services user for the resource group

I suppose I have to assign roles but shall I do it at subscription level, resource group level?

Where does the Python code I want to run come in?


Solution

  • Follow below steps.

    1. Enable managed identities in your host that is in a VM. Follow this documentation for more about managed identities in VM.
    2. Next, give access to this managed identity to your language service. You need to assign the Cognitive Services Language Reader role to your managed identity.

    enter image description here

    1. Use the code below.
    import os
    from azure.core.credentials import AzureKeyCredential
    from azure.ai.textanalytics import TextAnalyticsClient
    from azure.identity import ManagedIdentityCredential, DefaultAzureCredential
    
    endpoint = "https://<resource_name>.cognitiveservices.azure.com/"
    
    sys_iden = ManagedIdentityCredential(client_id="ad7xxxxxxxfec")
    text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=sys_iden)
    
    documents = [
        """I had the best day of my life. I decided to go sky-diving and it made me appreciate my whole life so much more.
        I developed a deep-connection with my instructor as well, and I feel as if I've made a life-long friend in her.""",
        """This was a waste of my time. All of the views on this drop are extremely boring, all I saw was grass. 0/10 would
        not recommend to any divers, even first-timers.""",
        """This was pretty good! The sights were ok, and I had fun with my instructors! Can't complain too much about my experience""",
        """I only have one word for my experience: WOW!!! I can't believe I have had such a wonderful skydiving company right
        in my backyard this whole time! I will definitely be a repeat customer, and I want to take my grandmother skydiving too,
        I know she'll love it!"""
    ]
    
    result = text_analytics_client.analyze_sentiment(documents, show_opinion_mining=True)
    docs = [doc for doc in result if not doc.is_error]
    
    print("Let's visualize the sentiment of each of these documents")
    for idx, doc in enumerate(docs):
        print(f"Document text: {documents[idx]}")
        print(f"Overall sentiment: {doc.sentiment}")
    

    Here, I used ManagedIdentityCredential, which by default uses system-assigned identity, and by providing the client id, you can use user-assigned identity.

    Output:

    enter image description here