Reading Docker Secrets in .NET Core 2.0 Preview
Versions used:
- Visual Studio Enterprise 2017 Preview, 15.3.0 Preview 6.0
- .NET Core version 2.0.0-preview2–006497
When creating a project, choose an ASP.NET Core Web Application, using ASP.NET Core 2.0 with the Web API template. In this example, I’ve chosen to call my project AuthenticationService.
The first step is to make the Docker Compose files compatible with secrets, as this is not possibly with version 3. For each docker-compose.**.yml, change the configuration file version to 3.2.
On to adding a secret to read from our application. Creating a subfolder secrets in the root of the solution, with a secret dbpassword.txt containing our very-secure database password of “applesauce”.
Adding the secret both to our Compose configuration, the result is
version: '3.2'
services:
authenticationservice:
image: authenticationservice
secrets:
- db_password
build:
context: ./AuthenticationService
dockerfile: Dockerfile
secrets:
db_password:
file: secrets/dbpassword.txtThe secret has now been added to our service, and when run will be mounted under /run/secrets/dbpassword.txt when running. As such, it will now be readable, either directly through more convential means of reading the file, or can be read using Microsoft.Extensions.Configuration.DockerSecrets. This extension is available on GitHub, but currently unlisted on NuGet. It can still be installed using the command-line
Install-Package Microsoft.Extensions.Configuration.DockerSecrets -Version 2.0.0-preview1-final
, but as it is unlisted there is no telling what Microsoft’s future intentions with it is. It’s worth noting that despite being unlisted on NuGet, it’s still listed as a dependency of the all-inclusive Microsoft.AspNetCore.All package.
After installing, our secret can simply be read using
var Configuration = new ConfigurationBuilder().AddDockerSecrets().Build();
var secret = Configuration["db_password"];Variable secret will now contain our database password applesauce.