Public/Get-OriAzBopKeyVaultSecret.ps1

<#
.SYNOPSIS
    Read Secret value from the KeyVault based on Managed Identity
.EXAMPLE
    $SecretUsername = Get-OriAzBopKeyVaultSecret `
                    -VaultName "MyKeyVaultName" `
                    -SecretName "MySecretWithUserName" `
                    -IdentityObjectId "xxxxxxxx-4321-1234-4321-xxxxxxxxxxxx" -Verbose
    $SecretCredential = Get-OriAzBopKeyVaultSecret `
                    -VaultName "MyKeyVaultName" `
                    -UserName $SecretUsername
                    -SecretName "MySecretWithUserPassword" `
                    -IdentityObjectId "xxxxxxxx-4321-1234-4321-xxxxxxxxxxxx" -Verbose
 
#>

function Get-OriAzBopKeyVaultSecret { 
    [CmdletBinding()]
    param
    (   
        [Parameter(Mandatory = $false, HelpMessage = "Type of resource")]
        [string] $Resource = "https://vault.azure.net",

        [Parameter(Mandatory = $false, HelpMessage = "Name of the KeyVault")]
        [string] $VaultName,

        [Parameter(Mandatory = $false, HelpMessage = "Name of the Secret in KeyVault")]
        [string] $SecretName,

        [Parameter(Mandatory = $false, HelpMessage = "Username when the value is not empty it returns values in PSCredential")]
        [string] $UserName,

        [Parameter(Mandatory = $false, HelpMessage = "ObejctId indefiticatio of Indentity. Eg. For onl-ci--identity it is ObjectId 'c5026693-9d1f-4131-99f6-17a42edc9e4a'")]
        [string] $IdentityObjectId         
    )
    $ErrorActionPreference = "Stop";
    Write-Verbose "-- Get-OriAzBopKeyVaultSecret --"
    Write-Verbose "Resource: $Resource "
    Write-Verbose "VaultName: $VaultName "
    Write-Verbose "SecretName: $SecretName "
    Write-Verbose "UserName: $UserName "
    Write-Verbose "IdentityObjectId: $IdentityObjectId "
    $authpar = @{ 
        Uri     = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01" 
        Body    = @{
            resource  = $Resource
            object_id = $IdentityObjectId
        }
        Headers = @{Metadata = "true" }
    }
    Write-Verbose "authpar: $(ConvertTo-Json $authpar) "
    $AuthRequest = Invoke-RestMethod @authpar
    if ([string]::IsNullOrEmpty($AuthRequest)) {
        Throw "Issue while Authorize to Manage Identity [Input param: $(ConvertTo-Json $authpar)]"
    }
    if ([string]::IsNullOrEmpty($AuthRequest.access_token)) {
        Throw "Issue getting access_token property from the Managed Identity [Input param: $(ConvertTo-Json $authpar)]"
    }

    $AccessToken = $AuthRequest.access_token

    $KeyvaultSecretUrl = 'https://{0}.vault.azure.net/secrets/{1}?api-version=2016-10-01' -f $VaultName, $SecretName
    $Headers = @{Authorization = "Bearer $AccessToken" }
    $GetKeyVaultSecret = @{
        Method  = "GET"
        Uri     = $KeyvaultSecretUrl
        Headers = $Headers
    }

    $Secret = Invoke-RestMethod @GetKeyVaultSecret
    if ([string]::IsNullOrEmpty($Secret)) {
        Throw "Issue getting KeyVaultSecret [Input param: $(ConvertTo-Json $GetKeyVaultSecret)]"
    }
    if ([string]::IsNullOrEmpty($Secret.value)) {
        Throw "Issue getting value property from the Secret [Input param: $(ConvertTo-Json $GetKeyVaultSecret)]"
    }
    
    $SecretValue = $Secret.value
    
    # When the UserName is set than it returns the content as PSCredential
    if (![string]::IsNullOrEmpty($UserName)) {
        $SecretKey = ConvertTo-SecureString $SecretValue -AsPlainText -Force
        $Credentials = New-Object System.Management.Automation.PSCredential ($UserName, $SecretKey)
        
        $toReturn = $Credentials
        #$Credentials.GetNetworkCredential()
    }
    else {
        $toReturn = $SecretValue
    } 
    Write-Verbose "-- End of Get-OriAzBopKeyVaultSecret --"
    return $toReturn
}