Error getting Azure secret value by secret name in python

169 views Asked by At

I am receiving the below error when trying to get the secret value,

AttributeError: 'coroutine' object has no attribute 'token'
sys:1: RuntimeWarning: coroutine 'AzureCliCredential.get_token' was never awaited

Code-

#secrets.py

   from azure.identity.aio import AzureCliCredential
   from azure.keyvault.secrets import SecretClient
    
    
   KVUri = f"https://{keyVaultName}.vault.azure.net"
    
    
   credential = AzureCliCredential()
    
   secret_client = SecretClient(vault_url=KVUri, credential=credential)    
    
   async def get_secret(name: str):
        secret = await secret_client.get_secret(name)
        return secret.value

#main.py

 async def print_hi(name):
        # Use a breakpoint in the code line below to debug your script.
        print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.
        secret_value = await secrets.get_secret("order-cat-appinsights-instrumentation-key")
        print(f"Secret value is {secret_value}")
       
 
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    asyncio.run(print_hi('PyCharm'))
    # print_hi('PyCharm')
1

There are 1 answers

0
Venkatesan On BEST ANSWER

AttributeError: 'coroutine' object has no attribute 'token' sys:1: RuntimeWarning: coroutine 'AzureCliCredential.get_token' was never awaited

I agree with mycooyp's comment you need to use azure.keyvault.secrets.aio library to fetch the secret with the async process.

You can use the below-modified code to get the secret value with a secret name using Python SDK.

secret.py

from azure.identity.aio import AzureCliCredential
from azure.keyvault.secrets.aio import SecretClient

keyVaultName="xxxx"
KVUri = f"https://{keyVaultName}.vault.azure.net"

async def get_secret(name: str):
    credential = AzureCliCredential()
    async with SecretClient(vault_url=KVUri, credential=credential) as secret_client:
        secret = await secret_client.get_secret(name)
        return secret.value

main.py

import asyncio
import secret

async def print_hi(name):
    print(f'Hi, {name}')
    secret_value = await secret.get_secret("secret3")
    print(f"Secret value is {secret_value}")

if __name__ == '__main__':
    asyncio.run(print_hi('Azure'))

Output:

Hi, Azure
Secret value is Wxxxxxxx

enter image description here