Search code examples
azureazure-powershellazure-keyvault

Export Azure key vault secrets as json list (or file)


Azure powershell - how to create json file with azure keyvaults secrets (I know how to read the secrets with power shell). I do know how to put key values pairs and export as a file. So, given I have this

    secret1Name - secret1Value
    secret2Name - secret2Value
    secret3Name - secret3Value 

I need a file saved to the file system

{
  "secret1Name":"secret1Value",
  "secret2Name":"secret2Value",
  "secret3Name":"secret3Value",
}

I found that there is something like this for reading from a file

$globalParametersJson = Get-Content $globalParametersFilePath
$globalParametersObject = [Newtonsoft.Json.Linq.JObject]::Parse($globalParametersJson)

And I (think) i need help doing it for writing a file.
Can anyone help ??


Solution

  • Export Azure key vault secrets as json list (or file)

    I have tried to reproduce your ask and I have received expected results:

    What I have understood from your question is that you want to write a secret to file (then below is the answer for that).

    Firstly, created an empty Json file and copied its path and I followed Microsoft-Document.

    Then I executed the below script:

    $y="C:\Users\vs\emo.json"
    $secret = Get-AzKeyVaultSecret -VaultName "rithkey"
    $secretnames=$secret.Name
    $Target = @()
    $result = New-Object -TypeName PSObject
    foreach($em in $secretnames )
    {
    $Target=Get-AzKeyVaultSecret -VaultName rithkey -Name $em
    
    $x=Get-AzKeyVaultSecret -VaultName rithkey -AsPlainText -Name $em
    
    $result | Add-Member -Type NoteProperty -Name $Target.Name  -Value $x
    }
    $result | ConvertTo-Json | Set-Content $y
    

    enter image description here

    Now we can check file emo.json as we used Set-Content to write to emo.json file and output is below:

    enter image description here