azure-pipelinesazure-resource-managerazure-rm-templateazure-bicep

Bicep - Get Service Principal ID from App ID


I want to create a roleAssignment in bicep using the principal ID of the used service connection in the ADO pipeline.
Since there is no self-method in bicep as in terraform, I try to get the service principal ID of the used ARM service connection. The only solution I found is the following task for the ADO pipeline:

- task: AzureCLI@2
  displayName: Retrieve principal ID of service connection
  continueOnError: false
  inputs:
    azureSubscription: $(armServiceConnectionName)
    scriptType: bash
    scriptLocation: inlineScript
    addSpnToEnvironment: true
    inlineScript: echo "##vso[task.setvariable variable=servicePrincipalId]$servicePrincipalId"

This returns the App ID of the service connection's service principal.

Is it possible to get the principal ID from this app ID?

I tried the following in bicep as documented here:

armPrincipalId = split(extensionResourceId(armConnectionPrincipalAppId, 'Microsoft.ManagedIdentity/userAssignedIdentities', armServiceConnectionName), '/')[8]

But this results in the following error:
DeploymentOutputEvaluationFailed: The template output 'armPrincipalId' is not valid: Unable to evaluate template language function 'extensionResourceId': the provided parent resource id '***' is not a valid uri

This obviously does not work because it needs an uri-shaped ID which the bicep resources would generate. But I only have a UID.


Solution

  • I found a solution by extending the inlineScript of the ADO pipeline task:

    - task: AzureCLI@2
      displayName: Retrieve principal ID of service connection
      continueOnError: false
      inputs:
        azureSubscription: $(armServiceConnectionName)
        scriptType: bash
        scriptLocation: inlineScript
        addSpnToEnvironment: true
        inlineScript: echo "##vso[task.setvariable variable=armConnectionPrincipalId]$(az ad sp show --id $servicePrincipalId --query id --out tsv)"
    

    I now search for the principal ID using az ad sp show:
    az ad sp show --id $servicePrincipalId --query id --out tsv

    This is still a hacky solution. If there is any possibility to use the current user principal within bicep (without any additional ADO task), feel free to post another solution here.