Astrophe
Astrophe

Reputation: 574

Get a value from user-secrets for use in the dotnet CLI

How do I pull a value from user-secrets for use in a dotnet command?

The best I can do at the moment is:

$c = dotnet user-secrets list 

Shows me: AppSettings:MyConnectionString = "Value of the connection string"

$c.GetType() //tells me BaseType = System.Object, Name = String, etc.

Now I can potentially try to extract the value of the connection string but that doesn't seem like a good way to do it.

I want to use the user-secret in the command:

dotnet ef dbcontext scaffold <MyConnectionString> Microsoft.EntityFrameworkCore.SqlServer -o Models

If I enter it in manually, then the database credentials will be stored in the command line history and I will get a warning in Visual Studio about how to protect potentially sensitive information by including it in my configuration file. However, I want to use user-secrets for development rather than adding the connection string to my configuration file.

Upvotes: 7

Views: 2696

Answers (1)

Steven Liekens
Steven Liekens

Reputation: 14113

You can do dotnet user-secrets list --json to get the values in machine-readable format. Then you can use PowerShell's ConvertFrom-Json to turn the output into a PSCustomObject where each secret key is available as a NoteProperty.

$secrets = dotnet user-secrets list --json | ConvertFrom-Json
dotnet ef dbcontext scaffold $secrets.'AppSettings:MyConnectionString' ...

(The quotes around the secret name are only necessary when you have a non-alphanumeric character in the name.)

NB

For some unfathomable reason, the JSON is wrapped by //BEGIN and //END.

//BEGIN
{
  "AppSettings:MyConnectionString": "Data Source=..."
}
//END

PowerShell 7 ignores the comments, but if you are using Windows PowerShell then you get an error.

ConvertFrom-Json : Invalid JSON primitive: .

A possible workaround for this error is to remove //BEGIN and //END using the -replace operator. Another workaround is to skip the first and the last lines.

# Using Windows PowerShell
$json = dotnet user-secrets list --json
$secrets = $json | % { $_ -replace '//(BEGIN|END)' } | ConvertFrom-Json
# or
$secrets = $json | select -Skip 1 | select -SkipLast 1 | ConvertFrom-Json

Upvotes: 4

Related Questions