- Published on
.NET in Azure: Where and how to store application settings
While building this app I soon realized I have no clue where to store connection strings and other secrets in production.
appsettings.Production.json
Option 1: When I was deploying to IONOS, I had appsettings.Production.json
file, containing my production database connection string, which I uploaded to IONOS manually via SFTP every time I deploy the app.
{
"ConnectionStrings": {
"MariaDB": "host=<>;port=<>;database=domgie;user id=<>;password=<>"
}
}
It was never being committed to GitHub due to security. You don't want to expose it to the world.
Pros:
- Easy to start with (no hassle with secrets, etc)
Cons:
- Requires to be either manually uploaded, or checked-in to GitHub
- Easy to lose
- Will not work in CI/CD if you don't commit it to repository
Option 2: Store in App Service Secrets (Azure)
With a recent move to Azure App Service for CI/CD implementation, I had to find a different way.
Well, good news, because App Service has it all figured out for you already. So, get your connection string, and:
- Locate to your App Service
- In Settings tab click on Configuration
- Click on New Connection string in the Connection strings table
- Add your connection string and specify a name
BUT... Here is the catch
If you selected PostgreSQL
type, IT WILL NOT WORK (as of today (04/07/2022)).
// Won't work if connection string type is set to PostgreSQL in App Service Configuration
var connectionString = builder.Configuration.GetConnectionString("PostgreSQL");
Why?
Azure magically adds these prefixes to all variables and dotnet
parses SOME of these to magically remove the prefix.
I hear you say "This is the worst situation to be in - you parse some of the stuff, but not all of it. I HATE MAGIC!". Outrageous! I agree!
But... Let's deal with it!
Solution
Change the connection string type from PostgreSQL
to Custom
and let dotnet
deal with it. .NET will magically remove the prefix, and the CUSTOMCONNSTR_<YOUR_CONN_NAME>
will become <YOUR_CONN_NAME>
. So you can use it like this:
// Works for MySQL, SQL Azure, SQL Server, Custom types
var connectionString = builder.Configuration.GetConnectionString("<YOUR_CONN_NAME>");
Option 3: Secrets and Vaults
Depending on how you deploy your application in Azure, you can also store settings as a secrets in vaults. But more on that in another blog post...
Have fun connecting!