I’m working on a function app and trying to use the key vault to store my connection string.
In my web MVC application we do not have to put in any C# code into place when we deploy to production.
In the web.config we just this line for our connection string: <connectionStrings configSource="connectionStrings.config" />
and it pulls all of the connection strings that are in the configuration section of our app service in Azure automatically.
My Main question:
Is it possible to do this in function app or do I have to directly put the C# code into pull from there based on connection string name?
Here is an example code that works with doing it via C#. I have to toggle the connection string name based on environment.
public async Task<string> GetConnectionStringAsync(ILogger logger)
{
string connectionStringName = "DefaultConnectionFunction";
string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var connectionString = string.Empty;
logger.LogInformation($"===> environment: {environment}");
try
{
if (environment == "Production" || environment == "Test")
{
var credential = new DefaultAzureCredential();
string apiUrl = Environment.GetEnvironmentVariable("KeyVaultUrl");
var _client = new SecretClient(new Uri(apiUrl), credential);
if (environment == "Test")
{
connectionStringName = $"{connectionStringName}Test";
}
KeyVaultSecret secret = await _client.GetSecretAsync(connectionStringName);
connectionString = secret.Value;
}
else if (environment == "Development")
{
string jsonFile = "local.settings.json";
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile(jsonFile)
.Build();
connectionString = configuration.GetConnectionString(connectionStringName);
}
return connectionString;
}
catch (Exception ex)
{
// Handle exceptions here.
throw new ApplicationException($"Unable to retrieve the secret: {connectionStringName} from Azure Key Vault", ex);
}
}
2
Answers
Do you run the Function App as a container or as a .NET Function App, Linux or Windows?
One option is to define the connection string as a "Application Setting" on the Function App that you can read out as a Environment Variable.
Also, if using Azure SQL, I would recommend looking into using Managed Identity to avoid secrets in the connection string.
Yes, you can use below way to get secret directly in local.settings.json, which after deployment will be stored in configuration section:
Firstly created secret as :
local.settings.json:
Function.cs:
Output: