skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Azure Function App: Is it possble to not use KeyVaultSecret C# code in Function App?

    Yes, you can use below way to get secret directly in local.settings.json, which after deployment will be stored in configuration section:

    @Microsoft.KeyVault(VaultName=keyvaultname;SecretName=secrename)
    

    Firstly created secret as :

    enter image description here

    local.settings.json:

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "con": "@Microsoft.KeyVault(VaultName=rithwik8;SecretName=connectionstring)"
      }
    }
    

    Function.cs:

    using System.Net;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Azure.Functions.Worker.Http;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    
    namespace FunctionApp70
    {
        public class Function1
        {
            private readonly ILogger _logger;
            private readonly IConfiguration config;
    
            public Function1(ILoggerFactory loggerFactory, IConfiguration configuration)
            {
                _logger = loggerFactory.CreateLogger<Function1>();
                config = configuration;
            }
    
    
            [Function("Function1")]
            public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
            {
    
    
                string value = config.GetValue<string>("con");
                var response = req.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
    
                response.WriteString("Hello Rithwik The connection string is :" + value);
                return response;
            }
        }
    }
    

    Output:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search