BennyM
BennyM

Reputation: 2856

Use Azure DevOps service principal details in Azure Powershell task

When writing an Azure CLI script in a Azure DevOps pipeline you can get access to the the serviceprincpal id, key and tenantid. Is there a way to get this info in a Azure Powershell task?

Upvotes: 10

Views: 13125

Answers (2)

Uchitha
Uchitha

Reputation: 1038

You can invoke a powershell script via Azure CLI task and use the 'addSpnToEnvironment' flag as explained in accepted answer.

    - task: AzureCLI@2
      displayName: 'Custom ps script'
      inputs:
        azureSubscription: ${{ parameters.serviceConnection }}
        addSpnToEnvironment: true  # Adds DevOps SP details to context
        scriptType: pscore
        scriptPath: '$(System.DefaultWorkingDirectory)/somescript.ps1'
 
 

Upvotes: 0

LoLance
LoLance

Reputation: 28086

The addSpnToEnvironment input which adds service principal id and key of the Azure endpoint you chose to the script's context is one option available only in Azure ClI Task, but not Azure Powershell Task.

Is there a way to get this info in a Azure Powershell task?

As an alternative workaround, we can define job-scoped variables in Azure ClI Task, check this document.

Steps to test:

1.Using latest Azure CLI task 2.0-preview and choose Powershell type. Try inline script like this:

Write-Host "##vso[task.setvariable variable=SpId;]$env:servicePrincipalId"

Write-Host "##vso[task.setvariable variable=SpKey;]$env:servicePrincipalKey"

Write-Host "##vso[task.setvariable variable=TenantId;]$env:tenantId"

Write-Host "##vso[task.setvariable variable=TestVar;]JustForTest"

2.Then add one Azure Powershell task after Azure CLI Task to test:

Write-Host $env:SpId

Write-Host $env:SpKey

Write-Host $env:TenantId

Write-Host $env:TestVar

3.Output:

enter image description here

So if you define the job-scoped variables using Write-Host "##vso[task.setvariable variable=xxx]xxx"(Powershell) or echo "##vso[task.setvariable variable=xxx]xxx"(Batch), you can then use something like $env:VariableName to access the info. The *** in log is because these are secrets projected by Azure Devops, so they're masked.

Upvotes: 14

Related Questions