Hello!

A popular way of connecting to Azure Subscriptions in Azure Devops is to make use of Service Connections. These allow steps to execute Azure Devops tasks remotely.

However, there are a few issues with them; the most notable being that you cannot store the values in somewhere like a KeyVault and update them when they expire. So once they’re entered, the cannot be retrieved.

Or can they? If you use the task azurecli@2 there is an option to access SPN details. I’ll copy and paste the documentation to save you a click:

*** addSpnToEnvironment - Access service principal details in script *** boolean. Default value: false.

Adds the service principal ID, service principal key, and tenant ID of the Azure endpoint you chose to the script’s execution environment. You can use the servicePrincipalId, servicePrincipalKey and tenantId variables in your script.

This is honored only when the Azure endpoint has service principal authentication scheme.

The following list shows the syntax to access environment variables based on the script type.

  • PowerShell script syntax: $env:servicePrincipalId
  • Batch script syntax: %servicePrincipalId%
  • Shell script syntax: $servicePrincipalId

Okay! So the values are stored to secret environment variables with masked values and can be used if they ae required. And waht if we want to get the value of them? Well, we can print them out to the screen quite easily.

- task: AzureCLI@2
  inputs:
    azureSubscription: bzzzt-dev-subscription
    scriptType: 'pscore'
    scriptLocation: 'inlineScript'
    inlineScript: |
            Write-Host 'spi'
            $env:servicePrincipalId.ToCharArray() | %{$_}
            Write-Host 'spk'
            $env:servicePrincipalKey.ToCharArray() | %{$_}
            Write-Host 'tid'
            $env:tenantId.ToCharArray() | %{$_}
    addSpnToEnvironment: true

This prints them out to the screen one char at a time unmasked. Then it’s a case of switching them back horizontally. There might be a simpler way than printing out horizontally, but this is my tried and trusted method for doing this!