Search code examples
azurepowershellazure-keyvaultservice-principal

Connecting to Azure KeyVault via SPN


I need help accessing an Azure KeyVault via Service Principal. I currently have two subscriptions that need to communicate and access the other subscription's Key Vault but in order to do so I would need the connection to occur via SPN. I have looked at the documentation for Get-AzureRmKeyVault and it provides no way to authenticate via a SPN from what I can find.

If anyone has a solution I would greatly appreciate it!


Solution

  • Not sure what actually do you mean access keyvault, in azure keyvault, there are Management plane and Data plane, they use different access control mechanisms.

    If you want your service principal to do Management plane operations(e.g. set the tag of your keyvault), you need to give it a role in Access control (IAM) of your keyvault in the portal. If you want to do Data plane operations(e.g. operate on the keys, secrets, certificates in the keyvault), you need to add your service principal with correct permissions to the Access policies of the keyvault.

    For more details about access control of keyvault, you could check - Secure access to a key vault.

    So make sure your service principal already had the correct permission, then use the command below.

    $azureAplicationId ="<application-id>"
    $azureTenantId= "<tenant-id>"
    $azurePassword = ConvertTo-SecureString "<client-secret>" -AsPlainText -Force
    $psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
    Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal 
    

    Then you can do the Management plane operations like Update-AzKeyVault, or the Data plane operations like Get-AzKeyVaultSecret.

    To access the keyvault in a different subscription, just use the command below to select subscription.

    Set-AzContext -Subscription <subscription-id>
    

    And I notice seems you are using the old AzureRm module, it was deprecated and will not be updated anymore, I recommend you to use the new Az module, follow Migrate Azure PowerShell from AzureRM to Az.