Search code examples
pythonazurevisual-studio-codeazureservicebus

Python script to access Azure Service Bus with Managed identity


I want to send a message to a servicebus from Visual Studio Code, in a simple python script. I want to access the service bus using a managed identity (in this case my own user). From visual studio it would be fairly simple using the authentication part in options.

As I understand it in Visual Studio Code you can use the Azure Account extension. So I installed the extension, logged in with success and can see all azure ressources.

However when i run my python script I get following error: enter image description here

Its like VS Code does not pickup my credentials. Beside logging into the extention is other configurations needed?


Solution

  • Python script to access Azure Service Bus with Managed identity

    It worked for me using below steps:

    Firstly I logged in to azure using Azure CLI command:

    az login
    

    enter image description here

    Then, I had set the subscription using below command:

     az account set --subscription  <subid>
    

    enter image description here

    Given below permission or role to my self in the resource:

    enter image description here

    Used below code which sent the message successfully:

    from azure.servicebus import ServiceBusClient, ServiceBusMessage
    from azure.identity import DefaultAzureCredential as cho
    
    rith_servicebus_name = "rith02.servicebus.windows.net"
    q_name = "rith"
    credential = cho()
    servicebus_client = ServiceBusClient(rith_servicebus_name , credential)
    rith = servicebus_client.get_queue_sender(queue_name=q_name)
    with rith:
        val = ServiceBusMessage("Hello Rithwik")
        rith.send_messages(val)
    

    Output:

    enter image description here

    If the above process do not work, as an alternative you can use client id , tenant and secret as client credential login.

    This issue comes when you do not set the account subscription or there is a issue with environment variables. Refer SO-Thread1 and SO-Thread2 for more information.