giklo
giklo

Reputation: 172

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.

Upvotes: 0

Views: 1317

Answers (2)

Thomas
Thomas

Reputation: 29491

Starting with Bicep v0.32.4, you can now use the deployer() function to get the objectId of the principal running the deployment:

deployer().objectId

Upvotes: 0

giklo
giklo

Reputation: 172

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.

Upvotes: 3

Related Questions