Using an SPN in a different Tenant
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