@Yash Thank you for reaching out. I have tested the scenario in my local environment by creating the Timmer trigger function, stored the key Vault name as environment variable in the local.settings.json
file. As documented here I have used os.environ()
to get the key vault name and was able to retrieve the secrets.
init.py:
import datetime
import logging
import os
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
import azure.functions as func
def main(mytimer: func.TimerRequest) -> None:
utc_timestamp = datetime.datetime.utcnow().replace(
tzinfo=datetime.timezone.utc).isoformat()
keyVaultName = os.environ["KEY_VAULT_NAME"]
KVUri = fhttps://{keyVaultName}.vault.azure.net
credential = DefaultAzureCredential()
client = SecretClient(vault_url=KVUri, credential=credential)
secret=client.get_secret("keytest")
logging.info(secret.value)
logging.info('Python timer trigger function ran at %s', utc_timestamp)
local.setting.json:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "<<yourstorageconnectionstring>>",
"FUNCTIONS_WORKER_RUNTIME": "python",
"KEY_VAULT_NAME":"<<yourkeyvalutname>>"
}
}
requirements.txt
azure-functions
azure-identity
azure-keyvault
azure-keyvault-secrets
Output:
Can anyone please help me to understand, what can be the best approach to store environment variable when I'm developing azure function locally(using Visual Studio Code) using Python runtime, so that I don't have to change the code to access the value in azure function(in azure cloud) as well as when I'm developing locally?
It is always recommended to store the environment variables in local.settings.json file during your local development but when deploying to function make sure your local.settings.json settings are reflected/uploaded in the configuration blade of your function app.
Feel free to get back to me if you need any assistance.