Sayli Godage
Sayli Godage

Reputation: 15

How to pass config values to azure function inside docker container

I want to read appsettings/config values from local.settings.json file inside Azure function. This is my function

 public async Task<ObjectResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ExecutionContext context)
        {

            var config = new ConfigurationBuilder().SetBasePath(context.FunctionAppDirectory).AddJsonFile("local.settings.json", optional: true, reloadOnChange: false).AddEnvironmentVariables().Build();
            
            var KeyVaultUrl = config["KeyVaultUrl"];
            var citusDbConnString = config["citusDbKeyVaultSecret"];

I have modified dockerfile to copy local.settings.json from host to container file system. Verified the file is present in container file system

EXPOSE 8080 COPY /bin/Debug/net6.0/local.settings.json /home/site/wwwroot/ COPY --from=installer-env ["/home/site/wwwroot", "/home/site/wwwroot"]

The variables KeyVaultUrl and citusDbConnString return empty and container throws "500Internal Server Error"

here is the container log

2023-06-02 13:52:51 fail: Host.Results[0] 2023-06-02 13:52:51 Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: createTenant 2023-06-02 13:52:51 ---> System.ArgumentNullException: Value cannot be null. (Parameter 'uriString') 2023-06-02 13:52:51 at System.Uri..ctor(String uriString) 2023-06-02 13:52:51 at abc.CreateTenant.getKeyVaultSecret(String secretName) in /src/dotnet-function-app/CreateTenant.cs:line 89 2023-06-02 13:52:51 at abc.CreateTenant.Run(HttpRequest req, ExecutionContext context) in /src/dotnet-function-app/CreateTenant.cs:line 104 2023-06-02 13:52:51 at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync(Object instance, Object[] arguments) in D:\a_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs:line 52

I have not tried using Environment variables, please suggest how can I load them from local.settings.json

Upvotes: 0

Views: 1086

Answers (1)

Venkat V
Venkat V

Reputation: 7820

I have not tried using Environment variables, please suggest how can I load them from local.settings.json

In Visual Studio I used the .Net 6 and enabled docker as shown below for generating docker file automatically.

  • The docker file is automatically created in the project path after you selecting the Enable Docker.

enter image description here

local.settings.json

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "Myname": "Venkat"
  }
}

Function App Code

[FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];
            string str = Environment.GetEnvironmentVariable("Myname");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(str)
                ? "This HTTP triggered function executed successfully. "
                : $"Hello, {str}. This HTTP triggered function executed successfully.";
            Console.WriteLine(str);
            return new OkObjectResult(responseMessage);
        }

Docker file

#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/azure-functions/dotnet:4 AS base
WORKDIR /home/site/wwwroot
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["testingFun/testingFun.csproj", "testingFun/"]
RUN dotnet restore "testingFun/testingFun.csproj"
COPY . .
WORKDIR "/src/testingFun"
RUN dotnet build "testingFun.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "testingFun.csproj" -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /home/site/wwwroot
COPY --from=publish /app/publish .
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
    AzureFunctionsJobHost__Logging__Console__IsEnabled=true

Docker Image:

enter image description here

Output I am able to fetch the config value from local.settings.json file.

enter image description here

Upvotes: 0

Related Questions