Skip to content Skip to sidebar Skip to footer

Setting Connection String As App Setting/environment Variable In Azure Function

In my Azure Function, I have specified an Environment Variable/App Setting for a database connection string. I can use the Environment Variable when I run the Function locally on m

Solution 1:

Actually you are almost get the right the connection string, however you use the wrong prepended string. Further more detailed information you could refer to this doc:Configure connection strings.

Which string to use it depends on which type you choose, like in my test I use a custom type. Then I should use os.environ['CUSTOMCONNSTR_testconnectionstring'] to get the value.

From the doc you could find there are following types:

  • SQL Server: SQLCONNSTR_
  • MySQL: MYSQLCONNSTR_
  • SQL Database: SQLAZURECONNSTR_
  • Custom: CUSTOMCONNSTR_

enter image description here

enter image description here

enter image description here

Solution 2:

In Functions application settings, such as service connection strings, are exposed as environment variables during execution. You can access these settings by declaring import os and then using

setting = os.environ["mysetting"]

As Alex said, try to remove CONNECTIONSTRINGS: from the name of the environment variable. In azure portal just add mysetting in application settings as keyName.

enter image description here

Solution 3:

I was struggling with this and found out this solution:

import os

setting = os.getenv("mysetting")

Solution 4:

I figured out the issue with help from George and selected George's answer as the correct answer.

I changed the code to os.environ["SQLCONNSTR_PDMPDBCONNECTIONSTRING"] but also I had been deploying the package from VS Code to Azure via the following code using Azure Command Line Interface (Azure CLI). This code overwrites Azure App Settings with the local.settings.json.

func azure functionapp publish <MY_FUNCTION_NAME> --publish-local-settings -i --overwrite-settings -y

I think that was causing changes to the type of database that I had specified in Azure App Settings (SQL Server), so when I had previously tried os.environ["SQLCONNSTR_PDMPDBCONNECTIONSTRING"] it didn't work because I was overwriting my Azure settings using my local.settings.json, which did not specify a database type.

I finally got it to work by deploying using the VS Code Extension called Azure Functions (Azure Functions: Deploy to Function App). This retains the settings that I had created in Azure App Services.

Post a Comment for "Setting Connection String As App Setting/environment Variable In Azure Function"