Using an SPN in a different Tenant

post

Overview

A pipeline task runs in the context of the service connection and sometimes that wont have access to a resource required resource; its possible to workaround this within an Azure DevOps Agent with the following approach.

Solution

The key to the solution below is changing to a different working folder and then using 'az login' with the SPN, the ToggleAlternateSpn function allows switching between the 2 contexts with ease:

- job: alternate_spn
  displayName: 'Job with resource in different subscription'
  pool:
    vmImage: 'ubuntu-latest'
  steps:
    - task: AzureCLI@2
      displayName: 'Alternate Tenant Task'
      inputs:
        failOnStandardError: true
        azureSubscription: $(AzureSubscriptionId)
        scriptType: pscore
        scriptLocation: inlineScript
        inlineScript: |
          function ToggleAlternateSpn {
            param(
              [boolean] $On
            )

            if($On -eq $true){
              $env:AZURE_CONFIG_DIR = Join-Path $([System.IO.Path]::GetTempPath()) 'alternate-spn'
              az login --service-principal -u '[SPN CLIENT ID]' --password '[SPN CLIENT SECRET]' --tenant '[SPN TENANT]' --allow-no-subscriptions | Out-Null
            } else {
              Remove-Item env:\AZURE_CONFIG_DIR
              $env:AZURE_CONFIG_DIR = $azureConfigDir
              az account set --subscription $(AzureSubscriptionId)
            }
          }

          $azureConfigDir = $env:AZURE_CONFIG_DIR

          ToggleAlternateSpn $true
          ... code with the alternate SPN

          ToggleAlternateSpn $false
          ... code with the service connection SPN
Tim Hills

Tim Hills

Tim has been working in solution delivery for over 15 years and has really exceled in the industry. He has been fortunate enough to work with some high-profile clients and challenging projects which has positioned him well for turning business requirements into reality.

Registered office

Address: Arceau Solutions Ltd, Dane John Works, Gordon Rd, Canterbury, CT1 3PP

Telephone: 0208 191 7030