azureazure-active-directoryazure-cli

Is it possible to have a non-interactive code that logs in to Azure and creates users in Microsoft Entra ID?


I know how to create users via command line:

Now I want to make it non-interactive.

I've found that if you want non-interactive login you can create a Service Principal and log in to it as explained here. However as I understand Service Principals have different sets of permissions than users, which are assigned by roles (AFAIK built-in are listed here). I've tried to create Service Principal with the highest (Owner) permissions, but it still cannot create users.

In AWS to solve analogous problem (log in non-interactively to AWS and create users in AWS IAM) you just log in non-interactively as a user:

However I cannot find a way to non-interactively login to Azure as a user. I've found only how to log in non-interactively as a Service principal and I don't know how to give it permission to add Microsoft Entra ID users.

I have two questions:

  1. Is it possible to log non-interactively via azure-cli and act as a user, with exactly the same permissions as a user?
  2. Is it possible to give permissions to Service principal to create Microsoft Entra ID users? Can it be done with built-in roles, or does it require custom role?

Solution

  • Note that, Azure RBAC roles are different from Microsoft Entra roles. To create users, you need to either assign directory roles or Microsoft Graph permissions.

    For non-interactive login to Azure CLI, you can make use of service principal authentication.

    Initially, create one app registration and add User.ReadWrite.All permission of Application type by granting admin consent to it as below:

    enter image description here

    Now, create one client secret in above app registration and note it's value:

    enter image description here

    You can get App ID and Tenant ID values of application's Overview page:

    enter image description here

    To login to Azure CLI as service principal, make use of below command:

    az login --service-principal -u <app-id> -p <client-secret> --tenant <tenantId>
    

    Response:

    enter image description here

    As you already granted User.ReadWrite.All Application permission with admin consent to service principal, you can directly run below command to create user:

    az ad user create --display-name <NAME> --password <PASS> --user-principal-name <PRINCIPAL>
    

    Response:

    enter image description here

    Alternatively, you can also assign "Directory Writer" or "User Administrator" Microsoft Entra roles to service principal like this:

    Go to Azure Portal -> Microsoft Entra ID -> Roles and administrators -> User administrator -> Add assignment -> Select service principal

    enter image description here