Using MSI with PowerShell in an Azure Function for AzureRM Commands

May 31, 2018 0 By JeremyBrooks

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