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 { 
    
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '', Justification = "There's required to convert the string to the secure string.")]
    [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 -Message ("[ START: {0}:{1} (v.{2}) ]" -f $Local:MyInvocation.MyCommand.Source, $Local:MyInvocation.MyCommand.Name, $Local:MyInvocation.MyCommand.Version)
    foreach ($arg in $PSBoundParameters.GetEnumerator()) {
        if ([string]::IsNullOrEmpty($arg.Value)) {
            Write-Debug -Message ("[null] {0}: {1}" -f $arg.Key, $arg.Value) -ErrorAction SilentlyContinue 
        }
        else {
            Write-Debug -Message ("[{2}] {0}: {1}" -f $arg.Key, $arg.Value, $arg.Value.GetType().Name) -ErrorAction SilentlyContinue 
        }
    }
    $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-Debug "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 -Message ("[ END: {0} ]" -f $Local:MyInvocation.MyCommand.Name)
    return $toReturn
}