Using MSI with PowerShell in an Azure Function for AzureRM Commands

Update:
Azure Functions V2 and V3 support using Powershell in a GA’ed fashion. Please use these versions over the experimental V1 version that does not have any support. Code examples can be found in the link below for getting the token using PowerShell, Dotnet, ect. Also the GA’ed version of the PowerShell uses PowerShell Core so it only supports the Az commandlets rather than the AzureRM commands.
https://docs.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=dotnet#code-examples

Here’s a quick tutorial for using MSI with PowerShell in an Azure function to call Login-AzureRMAccount. Note that Functions using PowerShell are in experimental so its not recommended for production use as the same SLA for Generally Available resources doesn’t reflect to preview/experimental resources. This allows you to not have to worry about creating a service principal to use for authentication.

  1. Enable MSI
  2. Get the AccountID from the Object ID under Azure Active Directory -> Enterprise Apps
  3. Copy the code below. The last line is simply printing out the subscription you are accessing so its not needed.

    $apiVersion = “2017-09-01″$resourceURI = “https://management.azure.com/

    $tokenAuthURI = $env:MSI_ENDPOINT + “?resource=$resourceURI&api-version=$apiVersion”

    $tokenResponse = Invoke-RestMethod -Method Get -Headers @{“Secret”=”$env:MSI_SECRET”} -Uri $tokenAuthURI

    $accessToken = $tokenResponse.access_token

    $accessToken

    Login-AzureRmAccount -AccessToken $accessToken -AccountId “ApplicationID from Enterprise Applications”

    (Get-AzureRmContext).Subscription

  4. Add the Enterprise Application to the RBAC permissions of the resource you are trying to access

  5. Add the newest AzureRM.Profile module to the web app

    1. Navigate to C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile
    2. Navagate to Kudu -> Debug Console -> D:/home/site/wwwroot/functionfolder -> Create a folder called modules
    3. Drag and drop the modules from the directory mentioned in a. Web apps aren’t running the most recent modules so you need to install the latest ones. (this step may be needed for the datalake modules as well)See this link for more details : https://stackoverflow.com/questions/37724769/how-to-install-a-powershell-module-in-an-azure-function/39985646

Run your command and see if it works