how to add secret and retrieve it in vm powershell

Vishwa teja Devarakonda 0 Reputation points
2024-11-17T05:42:51.75+00:00

I have configured a secret in key vault so i'm trying to retrieve it in my vm by using powershell commands so i just need navigation steps to retrieve the secret and also i have added the access policies and selected the particular vm.

Azure Key Vault
Azure Key Vault
An Azure service that is used to manage and protect cryptographic keys and other secrets used by cloud apps and services.
1,322 questions
Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
8,070 questions
{count} votes

1 answer

Sort by: Most helpful
  1. TP 99,531 Reputation points
    2024-11-20T05:23:03.1666667+00:00

    Hi,

    Below is sample code to retrieve a secret using PowerShell running inside of vm using system managed identity. I modified this sample to create it.

    $vaultUri = "https://mykeyvault.vault.azure.net"
    $secretName = "testsecretname"
    $response = Invoke-WebRequest -Uri "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=$vaultUri" -Headers @{Metadata="true"}
    $access_token = ($response.Content|ConvertFrom-Json).access_token
    $requestUri = $vaultUri + "/secrets/" + $secretName + "?api-version=7.4"
    $vaultResponse = (Invoke-WebRequest -Uri $requestUri -Method GET -ContentType "application/json" -Headers @{Authorization ="Bearer $access_token"}).content
    $secretValue = ($vaultResponse|ConvertFrom-Json).value
    echo $secretValue
    
    
    

    NOTE: for the above sample you need to enable the System Managed Identity on the VM via its Identity blade, and on your key vault the managed identity needs to be assigned Key Vault Secrets User role. The key vault access configuration needs to be set to Azure role-based access control.

    Alternatively you can use vault access policy mode if you prefer (from your description it sounds like that is what you are using) just make sure to grant the managed identity permission to secrets.

    Please click Accept Answer and upvote if the above was helpful. If something is unclear please add a comment below.

    Thanks.

    -TP

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.