Search code examples
pythonazureazure-functions

Azure function python app - getting nested environments variables


I have an azure function app written in python that does not return environment variables from other sections than values.

localsettings.json:

{
  "IsEncrypted": false,
  "IBAN": {
    "API_KEY": "xx",
    "CURRENCY": "USD"
  }, 
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "APPINSIGHTS_CONNECTION_STRING": "InstrumentationKey=xx-xx-xx-9c3c-4d3c4d3c4d3c",

  }
}

I have tried:

os.getenv('IBAN:API_KEY', '')
and
os.getenv('IBAN_API_KEY', '')

Both fails getting value. Is it not an option like in .NET to use nested sections in python?


Solution

  • Environment variables should be added under Values section in local.settings.json.

    You can configure the nested environment variables in two ways.

    1. Using colon(:) i.e.,IBAN:API_KEY
    2. Using double underscore(__) i.e., IBAN__API_KEY.

    local.settings.json:

    {
      "IsEncrypted": false,
      "Values": {
        "FUNCTIONS_WORKER_RUNTIME": "python",
        "AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "IBAN:API_KEY": "xx",
        "IBAN:CURRENCY": "USD"
      }
    }
    

    function_app.py:

    app = func.FunctionApp()
    
    @app.route(route="http_trigger", auth_level=func.AuthLevel.ANONYMOUS)
    def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
        logging.info('Python HTTP trigger function processed a request.')
        
        logging.info('API KEY: '+os.getenv("IBAN:API_KEY"))
        logging.info('CURRENCY: '+os.getenv("IBAN:CURRENCY"))
    
        name = req.params.get('name')
        if not name:
            try:
                req_body = req.get_json()
            except ValueError:
                pass
            else:
                name = req_body.get('name')
    
        if name:
            return func.HttpResponse(f"Hello, {name}. This HTTP triggered function executed successfully.")
        else:
            return func.HttpResponse(
                 "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
                 status_code=200
            )
    

    Output:

    Functions:
    
            http_trigger:  http://localhost:7071/api/http_trigger
    
    For detailed output, run func with --verbose flag.
    [2025-01-23T07:08:43.699Z] Executing 'Functions.http_trigger' (Reason='This function was programmatically called via the host APIs.', Id=ffdb7321-216b-4d15-960a-8b1dfd38aaf7)
    [2025-01-23T07:08:43.776Z] Python HTTP trigger function processed a request.
    [2025-01-23T07:08:43.776Z] CURRENCY: USD
    [2025-01-23T07:08:43.776Z] API KEY: xx
    [2025-01-23T07:08:43.845Z] Executed 'Functions.http_trigger' (Succeeded, Id=ffdb7321-216b-4d15-960a-8b1dfd38aaf7, Duration=169ms)