Retrieve Secret from Key-Vault using PowerShell in Azure Runbook

 

Retrieve Secret from Key-Vault using PowerShell in Azure Runbook @SharePointWidgets.com

Today I will showcase to you how to retrieve the Secret from the Key-Vault using PowerShell in Azure Runbook.

This is one of the most common scenarios whenever you are writing the script and need credentials for authentication. 

Step 1:

Check if the following Modules are available in the Azure Runbook
  • AZ.KeyVault
  • AZ.Accounts
To check to Navigate to your Automation account, then in the left navigation click on Modules and search for the modules

Step 2:

If the modules mentioned in Step 1 are not found, then navigate to the "Modules gallery", search for the modules, and then install. Once installed, re-check for the installed modules as mentioned in step 1. 

Step 3:

Copy the below script and paste it into your runbook


    try {
        $connectionName = "AzureRunAsConnection"

        # Get the connection "AzureRunAsConnection "
        $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName

        "Logging in to Azure..."
        Connect-AzAccount `
            -ServicePrincipal `
            -TenantId $servicePrincipalConnection.TenantId `
            -ApplicationId $servicePrincipalConnection.ApplicationId `
            -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint | out-null
    }
    catch {
        if (!$servicePrincipalConnection) {
            $ErrorMessage = "Connection $connectionName not found."
            throw $ErrorMessage
        }
        else {
            Write-Error -Message $_.Exception
            throw $_.Exception
        }
    }

    # Variables for retrieving the correct secret from the correct vault
    $VaultName = "KeyVaultName"
    $SecretName = "SecretName"
 
    # Retrieve value from Key Vault
    $secret = Get-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName
    try {
        $SECRET_TEXT = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret.SecretValue))
    }
    finally {
        [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret.SecretValue))
    }
    Write-Output "Values retrieved from the key vault: $SECRET_TEXT"

 Replace the following variables within the script with the actual values

  • $VaultName: Name of the key-vault
  • $SecretName: Name of the secret key created in the key-vault

Happy Coding... !!!


Comments

Popular posts from this blog

Rename Folder using Microsoft Flow / Power Automate in a Document Library in SharePoint Online

Power Automate: How to Add "New Line" to the text in SharePoint multiline text field

Power Automate: Rename file in SharePoint Online