Enable Managed Identity for Azure Machine Learning

Managed Identity allows Azure Machine Learning resources to authenticate to Azure services without storing credentials.

Prerequisites

Step‑by‑Step Guide

1. Create a System‑Assigned Managed Identity

az ml workspace update \
    --name MyWorkspace \
    --resource-group MyResourceGroup \
    --identity-type SystemAssigned

2. Grant the Identity Access to the Target Resource

For example, to allow the workspace to read from an Azure Storage account:

STORAGE_ACCOUNT_ID=$(az storage account show \
    --name mystorageaccount \
    --resource-group MyResourceGroup \
    --query id -o tsv)

IDENTITY_PRINCIPAL_ID=$(az ml workspace show \
    --name MyWorkspace \
    --resource-group MyResourceGroup \
    --query "identity.principalId" -o tsv)

az role assignment create \
    --assignee $IDENTITY_PRINCIPAL_ID \
    --role "Storage Blob Data Reader" \
    --scope $STORAGE_ACCOUNT_ID

3. Use the Identity in Your Compute Target

When creating a compute instance or cluster, enable identity usage:

from azure.ai.ml import MLClient
from azure.identity import DefaultAzureCredential

ml_client = MLClient(
    credential=DefaultAzureCredential(),
    subscription_id="YOUR_SUB_ID",
    resource_group_name="MyResourceGroup",
    workspace_name="MyWorkspace"
)

compute = ml_client.compute.create_or_update(
    name="my-cluster",
    type="amlcompute",
    size="Standard_DS3_v2",
    min_instances=0,
    max_instances=4,
    identity_type="SystemAssigned"
)

Accessing Azure Services from Your Job

Use the DefaultAzureCredential within your script to acquire a token automatically:

from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient

credential = DefaultAzureCredential()
blob_service = BlobServiceClient(account_url="https://mystorageaccount.blob.core.windows.net", credential=credential)

container_client = blob_service.get_container_client("mycontainer")
for blob in container_client.list_blobs():
    print(blob.name)

FAQ

Related Articles