rand0mb0t
rand0mb0t

Reputation: 144

How to use User-Managed Identity from Azure Cloud Function (python) in making a request to Azure KeyVault?

My current Setup:

My DevOps guy has created a User Managed Identity and have added it to the Access policy of Azure key Vault.
I have Created a function app testing-01 and assigned the User-ManagedIdentity to it under platform settings.
I am using Python 3.6 as runtime language.

This is my helper method that i use to check if i am able to access the secrets from key vault. and i am returning its response.

def cred_checker():
    credential = ManagedIdentityCredential()
    # credential = ManagedIdentityCredential(client_id='client_id 
    vault_name= "myvault"
    client = SecretClient(vault_url=f"https://{vault_name}.vault.azure.net/", credential=credential)
    username = client.get_secret(name="username")
    password= client.get_secret(name="password")

    return f"AKV client created successfully {client} .<br> name: {username},<br> pass: {password} " 

I am able to create the client with no error. But when i try to fetch secret from it, I am getting this ClientAuthenticationError :

Exception while executing function: Functions.HttpTriggerFunc <--- Result: Failure Exception: ClientAuthenticationError: Unexpected response '{'statusCode': 400, 'message': 'Unable to load requested managed identity.', 'correlationId': '92daf146-fed2-4a75-8359-9r955939815e'}'

Upvotes: 3

Views: 16303

Answers (2)

latenighter
latenighter

Reputation: 1

Here is how you would use Managed Identity in python:

from msrestazure.azure_active_directory import MSIAuthentication
creds = MSIAuthentication()
client = SecretClient(vault_url=MyVaultUrl, credentials=creds)

For this to work however, you have to have the identity assigned to your azure function as part of the deployment. If you are using terraform, there is a provider which you can use and it accepts an identity {} block where you can specify type="UserAssigned" and identity_ids = ["id1", "id2",...]

Upvotes: 0

Joy Wang
Joy Wang

Reputation: 42043

When you use a user-assigned identity, you need to specify the client_id of the MSI in ManagedIdentityCredential().

credential = ManagedIdentityCredential(client_id="xxxxxxxx")

To get the client_id, navigate to your function app -> Identity -> User assigned -> click your user-assigned identity -> copy the client_id.

enter image description here

Upvotes: 5

Related Questions