Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

python - Read Azure KeyVault Secret from Function App

This Python script is deployed to run from Azure Function App on Linux Consumption plan, This script is expected to read secrets from Azure Key Vault.

Apart from code deployment, following configurations are made

1.)System Assigned Managed Access Enabled for Azure Function App

2.)Azure Key Vault's Role Assignments Reference this Function App with >Reader role.

Here is the script from > > >init.py

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    # Get url and filename from postman by using POST method
    #identity = ManagedIdentityCredential()
    credentials = DefaultAzureCredential()
    secretClient = SecretClient(vault_url="https://kvkkpbedpdev.vault.azure.net/", credential=credentials)
    secret = secretClient.get_secret(name = 'st-cs-kkpb-edp-dev')

This function app requires following libraries and defined in requirements.txt file

azure-functions
azure-keyvault-secrets
azure-identity

This function runs and ends up following exception.

warn: Function.Tide_GetFiles.User[0]
python                   |       SharedTokenCacheCredential.get_token failed: SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.
python                   |       Traceback (most recent call last):
python                   |         File "/usr/local/lib/python3.8/site-packages/azure/identity/_internal/decorators.py", line 27, in wrapper
python                   |           token = fn(*args, **kwargs)
python                   |         File "/usr/local/lib/python3.8/site-packages/azure/identity/_credentials/shared_cache.py", line 88, in get_token
python                   |           account = self._get_account(self._username, self._tenant_id)
python                   |         File "/usr/local/lib/python3.8/site-packages/azure/identity/_internal/decorators.py", line 45, in wrapper
python                   |           return fn(*args, **kwargs)
python                   |         File "/usr/local/lib/python3.8/site-packages/azure/identity/_internal/shared_token_cache.py", line 166, in _get_account
python                   |           raise CredentialUnavailableError(message=NO_ACCOUNTS)
python                   |       azure.identity._exceptions.CredentialUnavailableError: SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.
python                   | info: Function.Tide_GetFiles.User[0]
python                   |       DefaultAzureCredential - SharedTokenCacheCredential is unavailab

and error

 fail: Function.Tide_GetFiles[3]
python                   |       Executed 'Functions.Tide_GetFiles' (Failed, Id=9d514a1f-aeae-4625-9379-b2f0bc89f38f, Duration=1673ms)
python                   | Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.Tide_GetFiles
python                   |  ---> Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcException: Result: Failure
python                   | Exception: ClientAuthenticationError: DefaultAzureCredential failed to retrieve a token from the included credentials.
python                   | Attempted credentials:
python                   |      EnvironmentCredential: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.
python                   |      ManagedIdentityCredential: ManagedIdentityCredential authentication unavailable, no managed identity endpoint found.
python                   |      SharedTokenCacheCredential: SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.

how can I figure this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the error, it seems managed identity is not applied to your Function app correctly. You should be able to see that going to the identity blade of Function app.

enter image description here

Additionally, you should add the required access policy (separate from role assignment in access control) (secret get here) to allow the identity (same name as the app) to access keyvault if you are not using the new preview access control. Refer How to set and get secrets from Azure Key Vault with Azure Managed Identities and Python.

Using the Azure Portal, go to the Key Vault's access policies, and grant required access to the Key Vault.

  1. Search for your Key Vault in “Search Resources dialog box” in Azure Portal.
  2. Select "Overview", and click on Access policies
  3. Click on "Add Access Policy", select required permissions.
  4. Click on "Select Principal", add your account
  5. Save the Access Policies

enter image description here

You can also create an Azure service principal either through Azure CLI, PowerShell or the portal and grant it the same access.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...