'Grant Security Reader role to an Azure Service Principal in az cli

I'm trying to allow a service principal in Azure to read from Azure Active Directory in order to perform lookups against AAD when using Terraform.

I'm pretty sure that the role required is the Security Reader role, however, I'm not sure what the context needs to be in order to add the service principal to the role. I'm assuming it is on the tenantId, but not sure the format that the az role assignment command then needs?

The code I'm currently using is as follows:-

sp=$(az ad sp list --query "[?displayName=='[my app]'].appId" --output tsv)
tenantId=$(az account show --query tenantId --output tsv)
az role assignment create --role "Secuity Reader" --assignee $sp --scope $tenantId

But this does not validate against the scope correctly, so it's clearly not just the tenant id. I know for subscription level scope it would be /subscriptions/[subscription id]... etc, but I don't know what the format would be for tenancy level permissions?



Solution 1:[1]

Use az rest or curl and follow the documentation for more details Assign an Azure role

something like this,

az rest --method PUT --resource "https://management.azure.com/" --uri "https://management.azure.com/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentId}?api-version=2015-07-01" --headers 'Content-Type=application/json' --body $jsonBody

use jsonBody variable to build json Object as per documentation link.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sagar Kulkarni