Assign Key Vault Access to Azure Function App with PowerShell

Introduction

Assigning Key Vault access policies to Azure Function Apps is crucial for securely managing secrets and keys used in your applications. With the advent of system-managed identities for Azure resources, this process can be automated to ensure efficient and secure access control. In this blog post, we'll explore how to use PowerShell scripting to assign Key Vault access policies to Function Apps using system-managed identities. This approach streamlines access management, enhances security, and reduces manual effort in configuring access policies.

Current approaches

Traditionally, managing Key Vault access policies involved manual configuration through the Azure Portal or using Azure CLI commands. However, this approach required frequent updates and posed challenges in maintaining consistency across environments. With the introduction of system-managed identities, Function Apps can now seamlessly authenticate with Azure services, simplifying access management and enhancing security.

Use cases

  1. Automated access control: Assigning Key Vault access policies to Function Apps using system-managed identities allows for automated and granular access control, ensuring that only authorized applications can access secrets and keys.
  2. Secure secrets management: By integrating Function Apps with Key Vault and automating access policy assignments, organizations can centralize secrets management and enforce strict security policies to protect sensitive information.
  3. Efficient deployment: Automating the assignment of access policies streamlines the deployment process, enabling seamless integration into CI/CD pipelines and reducing manual intervention in access management tasks.

Step 1. Assign system-managed identity to the Function app

Ensure your Azure Function App has System Managed Identity Assigned. Navigate Function App -> Left Menu -> Identity -> Enable -> Save

System assigned

Step 2. Install Azure CLI

  • Install Azure CLI: Install Azure CLI to execute commands seamlessly within PowerShell. Install Azure CLI

Step 3. Authenticate with Azure using Az CLI

az login

Step 4. Run the PowerShell script

Run below Powershell Script

# Parameters - ResourceGroupName, SubscriptionId, FunctionAppName, KeyVaultName, Slot
Function Assign-KVAccessPolicyToFunctionApp {
    param (
        # FunctionApp Name
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]$FunctionAppName,
        # ResourceGroup Name
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]$ResourceGroupName,
        # Subscription Id
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]$SubscriptionId,
        # KeyVaultName
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]$KeyVaultName,
        # Slot
        [Parameter(Mandatory = $false)]
        [String]$Slot
    )
    Write-Host "#### Starting Assign-KVAccessPolicyToFunctionApp! #####" -ForegroundColor Green
    # Get the command name
    $CommandName = $PSCmdlet.MyInvocation.InvocationName;
    # Get the list of parameters for the command
    $ParameterList = (Get-Command -Name $CommandName).Parameters;
    # Grab each parameter value, using Get-Variable
    foreach ($Parameter in $ParameterList) {
        Get-Variable -Name $Parameter.Values.Name -ErrorAction SilentlyContinue;
        # Get-Variable -Name $ParameterList;
    }
    # Set Subscription
    Write-Host "Setting Subscription"
    az account set -s $SubscriptionId
    try {
        Write-Host "Assigning Access Policy for $FunctionAppName to $KeyVaultName KeyVault"
        # Get Object ID of FunctionApp
        if ($Slot) {
            $FunctionId = az resource list -n $FunctionAppName/$Slot --query [*].identity.principalId --out tsv
        } else {
            $FunctionId = az resource list -n $FunctionAppName --query [*].identity.principalId --out tsv
        }
        Write-Host "FunctionId: $FunctionId"
        # Set the Policy
        az keyvault set-policy --name $KeyVaultName --object-id $FunctionId --secret-permissions list get --key-permissions list get --certificate-permissions list get
        Write-Host "Assigned"
        Write-Host "##[section] ##### Completed Assign-KVAccessPolicyToFunctionApp! #####" -ForegroundColor Green
    } catch [Exception] {
        Write-Host $_.Exception.Message
        Write-Host "`nError in Line: " $_.InvocationInfo.Line
        Write-Host "`nError in Line Number: " $_.InvocationInfo.ScriptLineNumber
        Write-Host "`nError Item Name: " $_.Exception.ItemName
        throw $_.Exception.Message
    }
}
Assign-KVAccessPolicyToFunctionApp -FunctionAppName "samplefunc-rg" -ResourceGroupName "sample-rg" -SubscriptionId "6ba2dfac-9ebd" -KeyVaultName "sample-rg"

This will output

Output

Note. In the az key vault set command, you can give what permissions you need to give for Keys, Secrets, and certificates. Also, if you want to assign it to a particular slot in the function app, pass the parameter "Slot" as well

Step 5. Check the output

Check-in Keyvault whether the access policy is assigned or not.

Access policies

Conclusion

Automating the assignment of Key Vault access policies to Azure Function Apps using system-managed identities offers a robust solution for managing secrets and keys securely. By leveraging PowerShell scripting, organizations can streamline access management processes, enhance security posture, and ensure compliance with regulatory requirements. This approach empowers teams to focus on building and deploying applications while maintaining stringent access controls and safeguarding sensitive data.