Create Azure service principal using python SDK

ghz 8months ago ⋅ 68 views

Is there currently any way to create a service principal using python SDK in azure?

I have tried doing it with azure-graphrbac but it currently is deprecated and it fails to load DefaultAzureCredential from azure-identity. I have tried creating the wrapper and using it as well but it fails while loading session token.

CredentialsWrapper.py

from azure.identity import DefaultAzureCredential
from msrest.authentication import BasicTokenAuthentication
from azure.core.pipeline.policies import BearerTokenCredentialPolicy
from azure.core.pipeline import PipelineRequest, PipelineContext
from azure.core.pipeline.transport import HttpRequest

class CredentialWrapper(BasicTokenAuthentication):
    def __init__(self, credential=None, resource_id="https://graph.microsoft.com/.default", **kwargs):
        super(CredentialWrapper, self).__init__(None)
        if credential is None:
            credential = DefaultAzureCredential()
        self._policy = BearerTokenCredentialPolicy(credential, resource_id, **kwargs)

    def _make_request(self):
        return PipelineRequest(
            HttpRequest(
                "CredentialWrapper",
                "https://fakeurl"
            ),
            PipelineContext(None)
        )

    def set_token(self):
        request = self._make_request()
        self._policy.on_request(request)
        print(request.http_request.headers["Authorization"])
        token = request.http_request.headers["Authorization"]
        self.token = {"access_token": token}

    def signed_session(self, session=None):
        self.set_token()
        return super(CredentialWrapper, self).signed_session(session)

Answers

Yes, you can create a service principal using the Python SDK provided by Azure. You can achieve this using the azure-identity library for authentication and the azure-mgmt-core library for managing resources in Azure.

Here's an example of how you can create a service principal using Python:

from azure.identity import DefaultAzureCredential
from azure.mgmt.authorization import AuthorizationManagementClient
from azure.mgmt.authorization.models import RoleAssignmentProperties

# Initialize the Azure credential
credential = DefaultAzureCredential()

# Initialize the authorization management client
authorization_client = AuthorizationManagementClient(credential, "<your_subscription_id>")

# Define the scope for the role assignment
scope = "/subscriptions/<your_subscription_id>"

# Define the role assignment properties
role_assignment = RoleAssignmentProperties(
    principal_id="<principal_id>",
    role_definition_id="/subscriptions/<your_subscription_id>/providers/Microsoft.Authorization/roleDefinitions/<role_definition_id>"
)

# Create the role assignment
authorization_client.role_assignments.create(scope, "<role_assignment_name>", role_assignment)

In this example:

  • Replace <your_subscription_id> with your Azure subscription ID.
  • Replace <principal_id> with the object ID of the service principal you want to assign the role to.
  • Replace <role_definition_id> with the ID of the role definition you want to assign. You can find the role definition ID by listing the role definitions or by using the Azure portal.
  • <role_assignment_name> is the name of the role assignment you are creating.

Make sure to install the required libraries (azure-identity and azure-mgmt-authorization) using pip:

pip install azure-identity azure-mgmt-authorization

With this setup, you can programmatically create service principals and assign roles to them using Python and the Azure SDK.