Azure WebApp Containers and AppSettings/Environment Variables - azure

I've created an AzureWebApp running a docker image. The app starts, but it does not appear to be getting a connection string. I've defined the connection string as an AppSetting but I am not seeing that setting passed as an environment variable.
Should I expect to see my AppSetting on the container output? Something like
docker run -e CONNSTR=FOO
The docs imply that it should just be passed automatically, but I feel like I'm missing something.
Thanks
Joe

Turns out it was working all along. I had a legit issue with authenticating against the db. I needed some logging in the service to verify that it was getting the right connection string.
It appears that the app settings are passed to the container implicitly without showing up in the logs as an -e param.

I run into a similar issues when deploying an .NET Core 2 Azure Function, which was reading settings and connection strings using System.Configuration.ConfigurationManager. The root cause in my case was that ASP.NET Core introduced a new configuration API.
Find more details at https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.0&tabs=basicconfiguration.
Assuming you're deploying an ASP.NET Core application deployed into Web Apps for Containers, you may be running into a similar issue. Please try to the following:
a) Initialize the configuration as follows:
using Microsoft.Extensions.Configuration;
...
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json")
.AddEnvironmentVariables()
.Build();
b) Read connection strings as follows:
configuration.GetConnectionString("StorageAccountConnectionString");
c) Read settings as follows:
configuration["ContainerName"];
Here is a sample configuration file for my Azure Function:
{
"IsEncrypted": true,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true",
"ContainerName": "container"
},
"Host": {
"LocalHttpPort": 7071
},
"ConnectionStrings": {
"StorageAccountConnectionString": "UseDevelopmentStorage=true"
}
}

Related

Why I am not seeing all properties available in local.settings.json file after deploying Azure function

I created an Azure function using Visual Studio. Local.setting.json file had following properties:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"ServiceBusConnString": "Endpoint=sb://sb-new-two.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=9FygKPHH2eJVp3GmAiUxtT7sGnddsaddadNIrciM0=",
"Test": "sb-new-two.servicebus.windows.net"
}
}
This is how my function looks:
[FunctionName("Function1")]
public void Run([ServiceBusTrigger("topic-one", "sub-one", Connection = "ServiceBusConnString")] string mySbMsg)
{
_logger.LogInformation("Processing message");
_logger.LogInformation($"Message : {mySbMsg}");
Console.WriteLine(mySbMsg);
}
After deploying the azure function, I do not see the test property. I am not using it in my code. But wondering why is this property missing?
Check in your .gitignore file if it includes the local.settings.json. Better yet add the value of your Test config manually in the Configuration section of your Azure function. Go to your function app in Azure, under Settings > Configuration > New Application setting, then add your Test config.
One of the workarounds to publish the app settings from local.settings.json to the Azure Portal Function App Configuration is:
Before publishing the function project to the Azure Portal, below is the configuration of my Function App:
Azure Functions Core Tools cmdlet:
func azure functionapp publish KrishSbFunApp01 --publish-local-settings -i
Before running this cmdlet, you have to change the value of AzureWebJobsStorage to the Azure Storage account connection string.
Also, you can overwrite the app settings by using the parameter --overwrite-settings -y, available in MS Doc Source.

Dummy Connection String Stopped Working When the Azure Web App was Migrated to .Net 6

We have a Web Api 2 application that is using .Net Framework 4.6.1. Since we don't want our connection string to be exposed, the app has a dummy connection string in web.config when deployed to Azure App Service.
That dummy connection string is being overridden by the connection string in Azure App Service Configuration. See this article: https://mohitgoyal.co/2017/07/05/update-connection-string-for-entity-framework-in-azure-web-app-settings/
It stopped working when we migrated to Asp.Net Core using .Net 6.
I have tried moving it to app.config but it still doesn't work.
We are still using Entity Framework 6 on .Net 6 and the connection string is being referenced in the constructor.
public AppDBContext() : base("name=AppDBContext")
{
}
This is why we need to have our connection string in a config xml file rather than in the appsettings.json.
My questions are:
Shouldn't azure app service treat app.config the same way it treats web.config?
Should we change the way we reference the connection string so that we can read from the Azure AppService Configuration?
When we create Asp. Net Core Web App using .Net 6, appsettings.json file will be created.
Add your Connection String in appsettings.json
My appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Your Connection String"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
My Program.cs
var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("DefaultConnection");
Shouldn't azure app service treat app.config the same way it treats web.config?
app.config is available in Console and Windows applications, whereas .NET Core Applications will have appsettings.json file to store connection strings and other Environment Variables.
The setting in appsettings.json will be overrided by Environment variables added in Azure App Settings .
Make sure your Connection String name in Azure App settings is same as in appsettings.json file.
Connection String in Azure App Settings

Azure function nested configuration

In my local.settings I have nested settings like this
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
"Email:Email": "test",
"Email:Password": "*******",
},
}
I am reading the values like this
config.GetValue<string>("Email:Email")
But when I am adding azure settings in azure function app (after deploying) I cannot add : into the name. Any suggestions for it?
One of the workaround you can follow,
When we are creating azure function in local and deploy to azure our localsettings.json file not upload .We need to update them manually by adding it on portal.
In localsettings.json file you have used : which is accepted by local environment. But When deploying we need to use __ instead.
Followed by this MICROSOFT DOCUMENTATION:-
The app setting name like ApplicationInsights:InstrumentationKey
needs to be configured in App Service as
ApplicationInsights__InstrumentationKey for the key name. In other
words, any : should be replaced by __ (double underscore).
Likewise you can set something like below e.g;
"Email__Email": "test",
"Email__Password": "*******",
For more information please refer this SO THREAD| azure application settings - how to add nested item & Nested object from local.settings.json in Azure function v3 settings .

Azure backup, will connection string in app settings cause issues with existing app?

We've upgraded our app service to S1 and want to setup automated backups. This is a .net core app with a SQL database. For the database portion, I get the following:
No supported connection strings of type SQL Database or MySQL found configured in app.
I've adopted this project built by a previous developer and just now getting my feet wet. I understand that I can add connection strings in the app settings, but I'm concerned that it'll break the app.
For example, right now the connection string is set in the code itself, in appsettings.json
{
"Data": {
"ConnectionStrings": {
"ConnectionString":"Server=****;Initial Catalog=*****;Persist Security Info=False;User ID=*****;Password=*****;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
//"ConnectionString":"Server=****;Initial Catalog=*****;Persist Security Info=False;User ID=*****;Password=*****;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
The way the other developer had it setup is the staging connection string is commented out when publishing to production, and swapped in the appsettings.json when published to staging. There's also another one in there that isn't in the example above for just localhost development.
This connection string is utilized in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:ConnectionStrings:ConnectionString"]));
}
Now this might be a silly question, but if within the app in Azure settings, if I add a connection string there to leverage the automated backups, am I going to break anything? I'm referring to selecting the app, clicking on Configure App Settings, and adding a connection string.
I'm not using slots at the moment either. So my goal is for now (as I learn more about the app that I didn't develop and learn how to use Azure) is to:
Setup the automated backups for the app and the SQL database
Not affect the app itself at runtime.
Silly as it may seem, I'm new to this environment and just a little paranoid. My gut tells me that the code will execute and stay the same, but when deploying I'm not sure if Azure does something behind the scenes that will cause this to blow up in my face.
No supported connection strings of type SQL Database or MySQL found configured in app.
To connect to a database, its connection string must exist in the Connection strings section of Application Settings page for your app on azure portal.
So, I suggest that you could go to portal to check the configuration whether connection string value is correct or available. The correct connection string format list at the following site.
For more details, you could refer to how application settings and connections work.
The final and most important thing to keep in mind is that the Azure Backup feature caches the connection string. Any changes made to the connection after setting up your backup, will not be reflected.
If you make changes to the connection string, you will have to hit the reset button in the backup blade and setup the backup again. This will ensure the new connection string is pulled in.
I just had the same issue, luckily I had a working one to draw from on another web app, tcp: and ,1433 is what fixed it for me and it started showing up:
"name": "NameHere",
"value": "Data Source=tcp:sqlservername.database.windows.net,1433;Initial Catalog=DatabaseName;User ID=sa;Password=password",
"type": "SQLAzure",
"slotSetting": true

How set up connection to database - ASP.NET Core hosted on Azure

Here is the connection string I copied from my Azure portal:
Server=tcp:xxxxxxxxxxx.database.windows.net,9999;Initial Catalog=DbNameDB;Persist Security Info=False;User ID={my_username};Password={my_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Here is my appsettings.json file:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=HeroesDB;Integrated Security=True;MultipleActiveResultSets=True"
}
}
Now that I want my app to work on a production server, how do I set it up?
Should I ...
...create an appsettings.production.json file in my project (next to my appsettings.json file) and set it's DefaultConnectionString to Azure server's connection string? If I did so, would Azure automatically know which of the two files to use?
...change my original appsettings.json file's connection string to Azure server connection string?
...look for a totally different solution? If yes, what would you suggest?
I'm leaning towards solution no 1., but I want to be sure.
In general appsettings.json is the main settings file, i.e. the production file if you want. All settings that are not found in other child files (e.g. appsettings.development.json) are taken from this appsettings.json.
So it should be the reverse: your appsettings.json should contain your production connection string, and appsettings.development.json a connection string to your local development DB.
Now how do you pick the right settings file. The key is ASPNETCORE_ENVIRONMENT setting. If it is not set, than appsettings.json is picked automatically. If it's set, the app looks for appsettings.{environment}.json file.
If your app runs in Azure portal, you set environment in the settings of your deployed web app. Locally (and I assume you use Visual Studio) there is a launchSettings.json file, found under Properties folder of your project in Solution explorer. There you can create a local launch configuration with the right environment, e.g.:
"my-local": {
"commandName": "Project",
"launchBrowser": false,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5003/"
}
This will create a "my-local" start option in the dropdown of the "play" button in VS. If you select "my-local" it will pick this settings, from them the "Development" environment, and from it take appsettings.Development.json and from there your connection string.
I hope I got your question right. To sum up again, locally use an evironment configured for appsettings.development.json and local DB. Deploy to Azure and it will pick up the normal appsettings.json file and run against production DB.
In your Azure portal, go to your App, and under Settings, find Configuration.
In the configuration, you can add a connection string. This will override the connection string your json file provided it's the same name.

Resources