How to get secret from Key Vault using PowerShell and Managed Identity

First you need to acquire a token using Managed Identity by calling the local Instance Metadata Service (IMDS) endpoint:

$audience = ''
$apiVersion = '2018-02-01'
$url = "$apiVersion&resource=$audience"
$token = Invoke-RestMethod -Method GET -Uri $url -Headers @{ 'Metadata' = 'true' }

Note that audience must match the service you’re calling and is different from example calling ARM.

Then call the Key Vault REST API to get the secret:

$apiVersion = '7.2'
$url = "https://$$secretName/?api-version=$apiVeesion"
$auth = "$($token.token_type) $($token.access_token)"
Invoke-RestMethod -Method GET -Uri $url -Headers @{ 'Authorization' = $auth }

That’s it, folks!

This entry was posted in Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.