Use AzureAD PowerShell cmdlets on VSTS agent

Today, I continued working on my custom VSTS extension that I will publish in the near future. In the extension I needed a way how to use AzureAD PowerShell cmdlets on VSTS agent because it isn’t installed by default.

Ship cmdlets in extension

Installing AzureAD cmdlets is not really that difficult. You just download the AzureAD cmdlets module from the PowerShell gallery and put them in your extension so they will be installed with your extension.

Importing the cmdlets

After you put the cmdlets as artifact in your extension, you need to import them. You can do this in example in your execution PowerShell file (in my case Main.ps1) with the following code:

Write-Verbose "Import AzureAD module because is not on default VSTS agent"
$azureAdModulePath = $PSScriptRoot + "\AzureAD\2.0.1.16\AzureAD.psd1"
Import-Module $azureAdModulePath

Connect-AzureAD

After imported, you can use them. Of course you first need to login. Because we don’t want to hard code credentials in our extension, you will have to pass them to the Connect-AzureAD cmdlet. There are multiple ways on how to do this. Think in example of a credential file as variable. I used an Azure Resource Manager endpoint for this. I did this because I actually only wanted to use the AzureRM module for my extension but some of the cmdlets are only in the AzureAD module.

So how do we login? Connect-AzureAD doesn’t allow to login with a Service Principal and a key. You need to use a self-signed certificate for this what I don’t want. I already have an Azure Resource Manager endpoint with a key. I want to use that key so the login procedures for AzureRM and AzureAD are the same. I already wrote a post on how to login with a SP and key but with an existing Azure Resource Manager endpoint in your task you can use the following code:

Write-Verbose "Import AzureAD module because is not on default VSTS agent"
$azureAdModulePath = $PSScriptRoot + "\AzureAD\2.0.1.16\AzureAD.psd1"
Import-Module $azureAdModulePath 

# Workaround to use AzureAD in this task. Get an access token and call Connect-AzureAD
$serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Require
$serviceName = Get-VstsInput -Name $serviceNameInput -Require
$endPointRM = Get-VstsEndpoint -Name $serviceName -Require

$clientId = $endPointRM.Auth.Parameters.ServicePrincipalId
$clientSecret = $endPointRM.Auth.Parameters.ServicePrincipalKey
$tenantId = $endPointRM.Auth.Parameters.TenantId

$adTokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$resource = "https://graph.windows.net/"

$body = @{
    grant_type    = "client_credentials"
    client_id     = $clientId
    client_secret = $clientSecret
    resource      = $resource
}

$response = Invoke-RestMethod -Method 'Post' -Uri $adTokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body
$token = $response.access_token

Write-Verbose "Login to AzureAD with same application as endpoint"
Connect-AzureAD -AadAccessToken $token -AccountId $clientId -TenantId $tenantId

After the above code, you can run any cmdlet that you want (if your AzureRM endpoint SP has permission on it).

Connect to AzureAD with Service Principal

I needed this already multiple times but never got it working. Today, I needed again the ability to Connect to AzureAD with Service Principal because some actions can’t be done (yet) via the Azure Resource Manager.

You can’t login into the Azure AD with a key as a Service Principal. You need a certificate for this. Read for more information the documentation of Connect-AzureAD. In order to use a key for logging into the Azure AD, we need to login first into AzureRM because there it is possible by default. Then call something from the Azure AD (in example a group or application) with AzureRM so the tokencache of the AzureRM context is filled with a valid token to “https://graph.windows.net/”. After that, use the token to login with Connect-AzureAD AadAccessToken cmdlet.

Sample

This script (written in AzureRM 5.1.1 because VSTS hosted agents are using that as well) will get an Azure AD application via AzureRM and then via AzureAD cmdlets.

$ObjectIdOfApplicationToChange = "82bd7dd3-accf-4808-97ef-6bc6e27ade9b"

$TenantId = "You tenant here"
$ApplicationId = "Your application id to login here"
$ServicePrincipalKey = ConvertTo-SecureString -String "Put a key of the application here" -AsPlainText -Force

Write-Information "Login to AzureRM as SP: $ApplicationId"
$AzureADCred = New-Object System.Management.Automation.PSCredential($ApplicationId, $ServicePrincipalKey)
Add-AzureRmAccount -ServicePrincipal -Credential $AzureADCred -TenantId $TenantId

# Get application with AzureRM because this will fill the tokencache for AzureAD as well (hidden feature).
Write-Information "Get application with AzureRM: $ObjectIdOfApplicationToChange"
Get-AzureRmADApplication -ObjectId $ObjectIdOfApplicationToChange

$ctx = Get-AzureRmContext
$cache = $ctx.TokenCache
$cacheItems = $cache.ReadItems()

$token = ($cacheItems | where { $_.Resource -eq "https://graph.windows.net/" })

Write-Information "Login to AzureAD with same SP: $ApplicationId"
Connect-AzureAD -AadAccessToken $token.AccessToken -AccountId $ctx.Account.Id -TenantId $ctx.Tenant.Id

Write-Information "Now get same application with AzureAD: $ObjectIdOfApplicationToChange"
Get-AzureADApplication -ObjectId $ObjectIdOfApplicationToChange