適用於:
Azure CLI ml 延伸模組 v2 (目前)
Python SDK azure-ai-ml v2 (目前)
了解如何使用線上端點以及系統指派的受控識別或使用者指派的受控識別,從評分指令碼存取 Azure 資源。
受控端點和 Kubernetes 端點皆可讓 Azure Machine Learning 處理佈建計算資源和部署機器學習模型的負擔。 一般來說,您的模型需要存取 Azure 資源 (例如 Azure Container Registry) 或您的 Blob 儲存體以進行推斷;使用受控識別時,您不需要在程式碼中管理認證,即可存取這些資源。 深入了解受控識別。
本指南假設您沒有受控識別、儲存體帳戶或線上端點。 如果您已經有這些元件,請跳至授與受控識別的存取權限一節。
必要條件
如要使用 Azure Machine Learning,您必須擁有 Azure 訂閱。 如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶。 立即試用免費或付費版本的 Azure Machine Learning。
安裝和設定 Azure CLI 和 ML (v2) 延伸模組。 如需詳細資訊,請參閱安裝、設定和使用 2.0 CLI。
Azure 資源群組,您 (或您使用的服務主體) 必須擁有其「使用者存取管理員」和「參與者」存取權。 如果您在上述文章中設定了 ML 擴充功能,您就會有這類資源群組。
Azure Machine Learning 工作區。 如果您在上述文章中設定了 ML 擴充功能,您已經有工作區。
已定型的機器學習模型,可供評分和部署。 如果您遵循此範例,則會提供模型。
如果您尚未設定 Azure CLI 的預設值,請儲存您的預設設定。 若要避免多次傳遞訂用帳戶、工作區和資源群組的值,請執行下列程式碼:
az account set --subscription <subscription ID>
az configure --defaults gitworkspace=<Azure Machine Learning workspace name> group=<resource group>
若要遵循此範例,請複製範例存放庫,然後將目錄變更為 cli。
git clone https://github.com/Azure/azureml-examples --depth 1
cd azureml-examples/cli
如要使用 Azure Machine Learning,您必須擁有 Azure 訂閱。 如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶。 立即試用免費或付費版本的 Azure Machine Learning。
安裝和設定 Azure CLI 和 ML (v2) 延伸模組。 如需詳細資訊,請參閱安裝、設定和使用 2.0 CLI。
Azure 資源群組,您 (或您使用的服務主體) 必須擁有其「使用者存取管理員」和「參與者」存取權。 如果您在上述文章中設定了 ML 擴充功能,您就會有這類資源群組。
Azure Machine Learning 工作區。 如果您在上述文章中設定了 ML 擴充功能,您就會有工作區。
已定型的機器學習模型,可供評分和部署。 如果您遵循此範例,則會提供模型。
如果您尚未設定 Azure CLI 的預設值,請儲存您的預設設定。 若要避免多次傳遞訂用帳戶、工作區和資源群組的值,請執行下列程式碼:
az account set --subscription <subscription ID>
az configure --defaults gitworkspace=<Azure Machine Learning workspace name> group=<resource group>
若要遵循此範例,請複製範例存放庫,然後將目錄變更為 cli。
git clone https://github.com/Azure/azureml-examples --depth 1
cd azureml-examples/cli
如要使用 Azure Machine Learning,您必須擁有 Azure 訂閱。 如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶。 立即試用免費或付費版本的 Azure Machine Learning。
安裝並設定 Azure Machine Learning Python SDK (v2)。 如需詳細資訊,請參閱安裝和設定 SDK (v2)。
Azure 資源群組,您 (或您使用的服務主體) 必須擁有其「使用者存取管理員」和「參與者」存取權。 如果您在上述文章中設定了 ML 擴充功能,您就會有這類資源群組。
Azure Machine Learning 工作區。 如果您在上述文章中設定了 ML 擴充功能,您已經有工作區。
已定型的機器學習模型,可供評分和部署。 如果您遵循此範例,則會提供模型。
複製範例存放庫,然後變更目錄。
git clone https://github.com/Azure/azureml-examples --depth 1
cd azureml-examples/sdk/endpoints/online/managed/managed-identities
若要跟著這個筆記本操作,請存取 sdk/endpoints/online/managed/managed-identities 目錄中隨附的範例筆記本。
此範例需要其他 Python 套件:
- Microsoft Azure 儲存體管理用戶端
- Microsoft Azure 授權管理用戶端
使用下列程式碼進行安裝:
%pip install --pre azure-mgmt-storage
%pip install --pre azure-mgmt-authorization
如要使用 Azure Machine Learning,您必須擁有 Azure 訂閱。 如尚未擁有 Azure 訂用帳戶,請在開始之前先建立免費帳戶。 立即試用免費或付費版本的 Azure Machine Learning。
您的訂用帳戶或使用者指派身分識別所存取的 Azure 資源之角色建立權限。
安裝並設定 Azure Machine Learning Python SDK (v2)。 如需詳細資訊,請參閱安裝和設定 SDK (v2)。
Azure 資源群組,您 (或您使用的服務主體) 必須擁有其「使用者存取管理員」和「參與者」存取權。 如果您在上述文章中設定了 ML 擴充功能,您就會有這類資源群組。
Azure Machine Learning 工作區。 如果您在上述文章中設定了 ML 擴充功能,您已經有工作區。
已定型的機器學習模型,可供評分和部署。 如果您遵循此範例,則會提供模型。
複製範例存放庫。
git clone https://github.com/Azure/azureml-examples --depth 1
cd azureml-examples/sdk/endpoints/online/managed/managed-identities
若要跟著這個筆記本操作,請存取 sdk/endpoints/online/managed/managed-identities 目錄中隨附的範例筆記本。
此範例需要其他 Python 套件:
- Microsoft Azure MSI 管理用戶端
- Microsoft Azure 儲存體用戶端
- Microsoft Azure 授權管理用戶端
使用下列程式碼進行安裝:
%pip install --pre azure-mgmt-msi
%pip install --pre azure-mgmt-storage
%pip install --pre azure-mgmt-authorization
限制
- 端點的身分識別是不可變的。 在端點建立期間,您可以將其關聯至系統指派的身分識別 (預設) 或使用者指派的身分識別。 您無法在建立端點之後變更身分識別。
- 如果您的 ARC 和 Blob 儲存體都設定為私人 (即位於虛擬網路後方),則無論您的工作區是公用還是私人,都應透過私人連結從 Kubernetes 端點存取。 如需私人連結設定的更多詳細資料,請參閱如何保護工作區 VNet。
設定工作區的變數名稱、工作區位置,以及您想要建立以與部署搭配使用的端點。
下列程式碼會將這些值匯出為您端點中的環境變數:
export WORKSPACE="<WORKSPACE_NAME>"
export LOCATION="<WORKSPACE_LOCATION>"
export ENDPOINT_NAME="<ENDPOINT_NAME>"
接下來,指定您要為 Blob 儲存體帳戶、Blob 容器和檔案命名的內容。 在這裡定義這些變數名稱,並在下一節中參考 az storage account create
和 az storage container create
命令。
下列程式碼會將這些值匯出為環境變數:
export STORAGE_ACCOUNT_NAME="<BLOB_STORAGE_TO_ACCESS>"
export STORAGE_CONTAINER_NAME="<CONTAINER_TO_ACCESS>"
export FILE_NAME="<FILE_TO_ACCESS>"
匯出這些變數之後,請在本機建立文字檔。 部署端點時,評分指令碼會使用在建立端點時產生的系統指派受控識別來存取此文字檔。
決定端點、工作區和工作區位置的名稱,然後將該值匯出為環境變數:
export WORKSPACE="<WORKSPACE_NAME>"
export LOCATION="<WORKSPACE_LOCATION>"
export ENDPOINT_NAME="<ENDPOINT_NAME>"
接下來,指定您要為 Blob 儲存體帳戶、Blob 容器和檔案命名的內容。 在這裡定義這些變數名稱,並在下一節中參考 az storage account create
和 az storage container create
命令。
export STORAGE_ACCOUNT_NAME="<BLOB_STORAGE_TO_ACCESS>"
export STORAGE_CONTAINER_NAME="<CONTAINER_TO_ACCESS>"
export FILE_NAME="<FILE_TO_ACCESS>"
匯出這些變數之後,請在本機建立文字檔。 部署端點時,評分指令碼會使用端點中使用的使用者指派受控識別來存取此文字檔。
決定您的使用者身分識別名稱,然後將該值匯出為環境變數:
export UAI_NAME="<USER_ASSIGNED_IDENTITY_NAME>"
指派工作區和部署相關變數的值:
subscription_id = "<SUBSCRIPTION_ID>"
resource_group = "<RESOURCE_GROUP>"
workspace_name = "<AML_WORKSPACE_NAME>"
endpoint_name = "<ENDPOINT_NAME>"
接下來,指定您要為 Blob 儲存體帳戶、Blob 容器和檔案命名的內容。 這些變數名稱需在這裡定義,並由 StorageManagementClient
和 ContainerClient
在儲存體帳戶和容器建立程式碼中參考。
storage_account_name = "<STORAGE_ACCOUNT_NAME>"
storage_container_name = "<CONTAINER_TO_ACCESS>"
file_name = "<FILE_TO_ACCESS>"
指派這些變數之後,請在本機建立文字檔。 部署端點時,評分指令碼會使用在建立端點時產生的系統指派受控識別來存取此文字檔。
現在,取得工作區的控制代碼並擷取其位置:
from azure.ai.ml import MLClient
from azure.identity import AzureCliCredential
from azure.ai.ml.entities import (
ManagedOnlineDeployment,
ManagedOnlineEndpoint,
Model,
CodeConfiguration,
Environment,
)
credential = AzureCliCredential()
ml_client = MLClient(credential, subscription_id, resource_group, workspace_name)
workspace_location = ml_client.workspaces.get(workspace_name).location
使用此值來建立儲存體帳戶。
指派工作區和部署相關變數的值:
subscription_id = "<SUBSCRIPTION_ID>"
resource_group = "<RESOURCE_GROUP>"
workspace_name = "<AML_WORKSPACE_NAME>"
endpoint_name = "<ENDPOINT_NAME>"
接下來,指定您要為 Blob 儲存體帳戶、Blob 容器和檔案命名的內容。 這些變數名稱需在這裡定義,並由 StorageManagementClient
和 ContainerClient
在儲存體帳戶和容器建立程式碼中參考。
storage_account_name = "<STORAGE_ACCOUNT_NAME>"
storage_container_name = "<CONTAINER_TO_ACCESS>"
file_name = "<FILE_TO_ACCESS>"
指派這些變數之後,請在本機建立文字檔。 部署端點時,評分指令碼會使用在建立端點時產生的使用者指派受控識別來存取此文字檔。
決定使用者身分識別名稱:
uai_name = "<USER_ASSIGNED_IDENTITY_NAME>"
現在,取得工作區的控制代碼並擷取其位置:
from azure.ai.ml import MLClient
from azure.identity import AzureCliCredential
from azure.ai.ml.entities import (
ManagedOnlineDeployment,
ManagedOnlineEndpoint,
Model,
CodeConfiguration,
Environment,
)
credential = AzureCliCredential()
ml_client = MLClient(credential, subscription_id, resource_group, workspace_name)
workspace_location = ml_client.workspaces.get(workspace_name).location
使用此值來建立儲存體帳戶。
定義部署設定
若要使用 CLI 部署線上端點,您需要在 YAML 檔案中定義設定。 如需有關 YAML 結構描述的詳細資訊,請參閱線上端點 YAML 參考文件。
下列範例中的 YAML 檔案是用來建立線上端點。
下列 YAML 範例位於 endpoints/online/managed/managed-identities/1-sai-create-endpoint 中。 檔案,
- 定義您想要用來參考端點的名稱,
my-sai-endpoint
。
- 指定用來存取端點的授權類型,
auth-mode: key
。
$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineEndpoint.schema.json
name: my-sai-endpoint
auth_mode: key
此 YAML 範例 2-sai-deployment.yml 會:
- 指定您想要建立的端點類型是
online
端點。
- 指出端點具有名為
blue
的相關聯部署。
- 設定部署的詳細資料,例如要部署的模型,以及要使用的環境和評分指令碼。
$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineDeployment.schema.json
name: blue
model:
path: ../../model-1/model/
code_configuration:
code: ../../model-1/onlinescoring/
scoring_script: score_managedidentity.py
environment:
conda_file: ../../model-1/environment/conda-managedidentity.yaml
image: mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04:latest
instance_type: Standard_DS3_v2
instance_count: 1
environment_variables:
STORAGE_ACCOUNT_NAME: "storage_place_holder"
STORAGE_CONTAINER_NAME: "container_place_holder"
FILE_NAME: "file_place_holder"
若要使用 CLI 部署線上端點,您需要在 YAML 檔案中定義設定。 如需有關 YAML 結構描述的詳細資訊,請參閱線上端點 YAML 參考文件。
下列範例中的 YAML 檔案是用來建立線上端點。
下列 YAML 範例位於 endpoints/online/managed/managed-identities/1-uai-create-endpoint 中。 檔案,
- 定義您想要用來參考端點的名稱,
my-uai-endpoint
。
- 指定用來存取端點的授權類型,
auth-mode: key
。
- 指出要使用的身分識別類型,
type: user_assigned
$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineEndpoint.schema.json
name: my-uai-endpoint
auth_mode: key
identity:
type: user_assigned
user_assigned_identities:
- resource_id: user_identity_ARM_id_place_holder
此 YAML 範例 2-sai-deployment.yml 會:
- 指定您想要建立的端點類型是
online
端點。
- 指出端點具有名為
blue
的相關聯部署。
- 設定部署的詳細資料,例如要部署的模型,以及要使用的環境和評分指令碼。
$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineDeployment.schema.json
name: blue
model:
path: ../../model-1/model/
code_configuration:
code: ../../model-1/onlinescoring/
scoring_script: score_managedidentity.py
environment:
conda_file: ../../model-1/environment/conda-managedidentity.yaml
image: mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04:latest
instance_type: Standard_DS3_v2
instance_count: 1
environment_variables:
STORAGE_ACCOUNT_NAME: "storage_place_holder"
STORAGE_CONTAINER_NAME: "container_place_holder"
FILE_NAME: "file_place_holder"
UAI_CLIENT_ID: "uai_client_id_place_holder"
若要透過 Python SDK (v2) 部署線上端點,可以使用物件來定義下列設定。 或者,可以使用 .load
方法來載入 YAML 檔案。
下列 Python 端點物件:
- 將您要參考的端點名稱指派給變數
endpoint_name
。
- 指定用來存取端點
auth-mode="key"
的授權類型。
endpoint = ManagedOnlineEndpoint(name=endpoint_name, auth_mode="key")
此部署物件會:
- 透過類別指定您想要建立的部署類型為
ManagedOnlineDeployment
。
- 指出端點具有名為
blue
的相關聯部署。
- 設定部署的詳細資料,例如
name
和 instance_count
- 定義額外的內嵌物件,並將其與
Model
、CodeConfiguration
和 Environment
的部署建立關聯。
- 包含系統指派的受控識別存取儲存體所需的環境變數。
deployment = ManagedOnlineDeployment(
name="blue",
endpoint_name=endpoint_name,
model=Model(path="../../model-1/model/"),
code_configuration=CodeConfiguration(
code="../../model-1/onlinescoring/", scoring_script="score_managedidentity.py"
),
environment=Environment(
conda_file="../../model-1/environment/conda-managedidentity.yml",
image="mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04:latest",
),
instance_type="Standard_DS3_v2",
instance_count=1,
environment_variables={
"STORAGE_ACCOUNT_NAME": storage_account_name,
"STORAGE_CONTAINER_NAME": storage_container_name,
"FILE_NAME": file_name,
},
)
若要透過 Python SDK (v2) 部署線上端點,可以使用物件來定義下列設定。 或者,可以使用 .load
方法來載入 YAML 檔案。
針對使用者指派的身分識別,您可以在建立使用者指派的受控識別之後定義端點設定。
此部署物件會:
- 透過類別指定您想要建立的部署類型為
ManagedOnlineDeployment
。
- 指出端點具有名為
blue
的相關聯部署。
- 設定部署的詳細資料,例如
name
和 instance_count
- 定義更多內嵌物件,並將其與
Model
、CodeConfiguration
和 Environment
的部署建立關聯。
- 包含使用者指派的受控識別存取儲存體所需的環境變數。
- 新增
UAI_CLIENT_ID
的預留位置環境變數,系統會在建立變數之後和實際部署此設定之前新增。
deployment = ManagedOnlineDeployment(
name="blue",
endpoint_name=endpoint_name,
model=Model(path="../../model-1/model/"),
code_configuration=CodeConfiguration(
code="../../model-1/onlinescoring/", scoring_script="score_managedidentity.py"
),
environment=Environment(
conda_file="../../model-1/environment/conda-managedidentity.yml",
image="mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04:latest",
),
instance_type="Standard_DS3_v2",
instance_count=1,
environment_variables={
"STORAGE_ACCOUNT_NAME": storage_account_name,
"STORAGE_CONTAINER_NAME": storage_container_name,
"FILE_NAME": file_name,
# We will update this after creating an identity
"UAI_CLIENT_ID": "uai_client_id_place_holder",
},
)
建立受控識別
若要存取 Azure 資源,請為您的線上端點建立系統指派或使用者指派的受控識別。
當您建立線上端點時,系統會為您自動產生系統指派的受控識別,因此不需要另外建立一個受控識別。
若要建立使用者指派的受控識別,請使用下列命令:
az identity create --name $UAI_NAME
當您建立線上端點時,系統會為您自動產生系統指派的受控識別,因此不需要另外建立一個受控識別。
若要建立使用者指派的受控識別,請先取得 的 ManagedServiceIdentityClient
控制代碼:
from azure.mgmt.msi import ManagedServiceIdentityClient
from azure.mgmt.msi.models import Identity
credential = AzureCliCredential()
msi_client = ManagedServiceIdentityClient(
subscription_id=subscription_id,
credential=credential,
)
然後建立身分識別:
msi_client.user_assigned_identities.create_or_update(
resource_group_name=resource_group,
resource_name=uai_name,
parameters=Identity(location=workspace_location),
)
現在,擷取身分識別物件,其中包含您要使用的詳細資料:
uai_identity = msi_client.user_assigned_identities.get(
resource_group_name=resource_group,
resource_name=uai_name,
)
uai_identity.as_dict()
建立儲存體帳戶和容器
針對這個範例,請建立 Blob 儲存體帳戶和 Blob 容器,然後將先前建立的文字檔上傳至 Blob 容器。 您會為線上端點和受控識別提供此儲存體帳戶和 Blob 容器的存取權。
首先,請建立儲存體帳戶。
az storage account create --name $STORAGE_ACCOUNT_NAME --location $LOCATION
接下來,在儲存體帳戶中建立 Blob 容器。
az storage container create --account-name $STORAGE_ACCOUNT_NAME --name $STORAGE_CONTAINER_NAME
然後,將您的文字檔上傳至 Blob 容器。
az storage blob upload --account-name $STORAGE_ACCOUNT_NAME --container-name $STORAGE_CONTAINER_NAME --name $FILE_NAME --file endpoints/online/managed/managed-identities/hello.txt
首先,請建立儲存體帳戶。
az storage account create --name $STORAGE_ACCOUNT_NAME --location $LOCATION
您也可以使用下列項目來擷取現有的儲存體帳戶識別碼。
storage_id=`az storage account show --name $STORAGE_ACCOUNT_NAME --query "id" -o tsv`
接下來,在儲存體帳戶中建立 Blob 容器。
az storage container create --account-name $STORAGE_ACCOUNT_NAME --name $STORAGE_CONTAINER_NAME
然後,在容器中上傳檔案。
az storage blob upload --account-name $STORAGE_ACCOUNT_NAME --container-name $STORAGE_CONTAINER_NAME --name $FILE_NAME --file endpoints/online/managed/managed-identities/hello.txt
首先,取得 StorageManagementclient
的控制代碼:
from azure.mgmt.storage import StorageManagementClient
from azure.storage.blob import ContainerClient
from azure.mgmt.storage.models import Sku, StorageAccountCreateParameters, BlobContainer
credential = AzureCliCredential()
storage_client = StorageManagementClient(
credential=credential, subscription_id=subscription_id
)
然後建立儲存體帳戶:
storage_account_parameters = StorageAccountCreateParameters(
sku=Sku(name="Standard_LRS"),
kind="Storage",
location=workspace_location,
tags={"NRMS.NSP-extension": "ServiceTag-storage"},
)
storage_account = storage_client.storage_accounts.begin_create(
resource_group_name=resource_group,
account_name=storage_account_name,
parameters=storage_account_parameters,
).result()
接下來,在儲存體帳戶中建立 Blob 容器:
blob_container = storage_client.blob_containers.create(
resource_group_name=resource_group,
account_name=storage_account_name,
container_name=storage_container_name,
blob_container=BlobContainer(),
)
使用 ContainerClient
擷取儲存體帳戶金鑰,並建立容器的控制代碼:
res = storage_client.storage_accounts.list_keys(
resource_group_name=resource_group,
account_name=storage_account_name,
)
key = res.keys[0].value
container_client = ContainerClient(
account_url=storage_account.primary_endpoints.blob,
container_name=storage_container_name,
credential=key,
)
接下來,使用 ContainerClient
將 Blob 上傳至容器:
with open(file_name, "rb") as f:
container_client.upload_blob(name=file_name, data=f.read())
首先,取得 StorageManagementclient
的控制代碼:
from azure.mgmt.storage import StorageManagementClient
from azure.storage.blob import ContainerClient
from azure.mgmt.storage.models import Sku, StorageAccountCreateParameters, BlobContainer
credential = AzureCliCredential()
storage_client = StorageManagementClient(
credential=credential, subscription_id=subscription_id
)
然後建立儲存體帳戶:
storage_account_parameters = StorageAccountCreateParameters(
sku=Sku(name="Standard_LRS"),
kind="Storage",
location=workspace_location,
tags={"NRMS.NSP-extension": "ServiceTag-storage"},
)
storage_account = storage_client.storage_accounts.begin_create(
resource_group_name=resource_group,
account_name=storage_account_name,
parameters=storage_account_parameters,
).result()
接下來,在儲存體帳戶中建立 Blob 容器:
blob_container = storage_client.blob_containers.create(
resource_group_name=resource_group,
account_name=storage_account_name,
container_name=storage_container_name,
blob_container=BlobContainer(),
)
使用 ContainerClient
擷取儲存體帳戶金鑰,並建立容器的控制代碼:
res = storage_client.storage_accounts.list_keys(
resource_group_name=resource_group,
account_name=storage_account_name,
)
key = res.keys[0].value
container_client = ContainerClient(
account_url=storage_account.primary_endpoints.blob,
container_name=storage_container_name,
credential=key,
)
接下來,使用 ContainerClient
將 Blob 上傳至容器:
with open(file_name, "rb") as f:
container_client.upload_blob(name=file_name, data=f.read())
建立線上端點
下列程式碼會在不指定部署的情況下建立線上端點。
警告
端點的身分識別是不可變的。 在端點建立期間,您可以將其關聯至系統指派的身分識別 (預設) 或使用者指派的身分識別。 您無法在建立端點之後變更身分識別。
當您建立線上端點時,預設會為端點建立系統指派的受控識別。
az ml online-endpoint create --name $ENDPOINT_NAME -f endpoints/online/managed/managed-identities/1-sai-create-endpoint.yml
使用下列項目來檢查端點的狀態。
az ml online-endpoint show --name $ENDPOINT_NAME
如果您遇到任何問題,請參閱針對線上端點部署和評分進行疑難排解。
az ml online-endpoint create --name $ENDPOINT_NAME -f endpoints/online/managed/managed-identities/1-uai-create-endpoint.yml --set identity.user_assigned_identities[0].resource_id=$uai_id
使用下列項目來檢查端點的狀態。
az ml online-endpoint show --name $ENDPOINT_NAME
如果您遇到任何問題,請參閱針對線上端點部署和評分進行疑難排解。
當您建立線上端點時,預設會為端點建立系統指派的受控識別。
ml_client.online_endpoints.begin_create_or_update(endpoint).result()
使用下列程式碼,透過已部署端點物件的詳細資料檢查端點的狀態:
endpoint = ml_client.online_endpoints.get(endpoint_name)
print(endpoint.identity.type)
print(endpoint.identity.principal_id)
如果您遇到任何問題,請參閱針對線上端點部署和評分進行疑難排解。
下列 Python 端點物件:
- 將您要參考的端點名稱指派給變數
endpoint_name
。
- 指定用來存取端點
auth-mode="key"
的授權類型。
- 將其身分識別定義為
ManagedServiceIdentity
,並將受控識別指定為使用者指派的受控識別。
定義及部署端點:
from azure.ai.ml.entities import ManagedIdentityConfiguration, IdentityConfiguration
endpoint = ManagedOnlineEndpoint(
name=endpoint_name,
auth_mode="key",
identity=IdentityConfiguration(
type="user_assigned",
user_assigned_identities=[
ManagedIdentityConfiguration(resource_id=uai_identity.id)
],
),
)
ml_client.online_endpoints.begin_create_or_update(endpoint).result()
使用下列程式碼,透過已部署端點物件的詳細資料檢查端點的狀態:
endpoint = ml_client.online_endpoints.get(endpoint_name)
print(endpoint.identity.type)
print(endpoint.identity.user_assigned_identities)
如果您遇到任何問題,請參閱針對線上端點部署和評分進行疑難排解。
授與受控識別的存取權限
重要
線上端點需要 Azure Container Registry 的提取權限、AcrPull 權限、容器登錄,以及工作區預設資料存放區的儲存體 Blob 資料讀取器權限。
您可以允許線上端點權限透過其系統指派的受控識別來存取您的儲存體,或授與使用者指派的受控識別權限,以存取上一節所建立的儲存體帳戶。
擷取針對您的端點所建立的系統指派受控識別。
system_identity=`az ml online-endpoint show --name $ENDPOINT_NAME --query "identity.principal_id" -o tsv`
您可以從這裡提供系統指派的受控識別權限,以存取您的儲存體。
az role assignment create --assignee-object-id $system_identity --assignee-principal-type ServicePrincipal --role "Storage Blob Data Reader" --scope $storage_id
擷取使用者指派的受控識別用戶端識別碼。
uai_clientid=`az identity list --query "[?name=='$UAI_NAME'].clientId" -o tsv`
uai_principalid=`az identity list --query "[?name=='$UAI_NAME'].principalId" -o tsv`
擷取使用者指派的受控識別識別碼。
uai_id=`az identity list --query "[?name=='$UAI_NAME'].id" -o tsv`
取得與工作區相關聯的容器登錄。
container_registry=`az ml workspace show --name $WORKSPACE --query container_registry -o tsv`
擷取工作區的預設儲存體。
storage_account=`az ml workspace show --name $WORKSPACE --query storage_account -o tsv`
將儲存體帳戶的權限授與使用者指派的受控識別。
az role assignment create --assignee-object-id $uai_principalid --assignee-principal-type ServicePrincipal --role "Storage Blob Data Reader" --scope $storage_id
將容器登錄的權限授與使用者指派的受控識別。
az role assignment create --assignee-object-id $uai_principalid --assignee-principal-type ServicePrincipal --role "AcrPull" --scope $container_registry
將預設工作區儲存體的權限授與使用者指派的受控識別。
az role assignment create --assignee-object-id $uai_principalid --assignee-principal-type ServicePrincipal --role "Storage Blob Data Reader" --scope $storage_account
首先,讓 AuthorizationManagementClient
列出角色定義:
from azure.mgmt.authorization import AuthorizationManagementClient
from azure.mgmt.authorization.v2018_01_01_preview.models import RoleDefinition
import uuid
role_definition_client = AuthorizationManagementClient(
credential=credential,
subscription_id=subscription_id,
api_version="2018-01-01-preview",
)
現在,進行初始化以建立角色指派:
from azure.mgmt.authorization.v2020_10_01_preview.models import (
RoleAssignment,
RoleAssignmentCreateParameters,
)
role_assignment_client = AuthorizationManagementClient(
credential=credential,
subscription_id=subscription_id,
api_version="2020-10-01-preview",
)
然後,取得系統指派受控識別的主體識別碼:
endpoint = ml_client.online_endpoints.get(endpoint_name)
system_principal_id = endpoint.identity.principal_id
接下來,將「儲存體 Blob 資料讀者」角色指派給端點。 系統會依名稱擷取角色定義,並連同端點的主體識別碼一起傳遞。 角色會套用在上面建立的儲存體帳戶範圍,並允許端點讀取檔案。
role_name = "Storage Blob Data Reader"
scope = storage_account.id
role_defs = role_definition_client.role_definitions.list(scope=scope)
role_def = next((r for r in role_defs if r.role_name == role_name))
role_assignment_client.role_assignments.create(
scope=scope,
role_assignment_name=str(uuid.uuid4()),
parameters=RoleAssignmentCreateParameters(
role_definition_id=role_def.id, principal_id=system_principal_id
),
)
首先,讓 AuthorizationManagementClient
列出角色定義:
from azure.mgmt.authorization import AuthorizationManagementClient
from azure.mgmt.authorization.v2018_01_01_preview.models import RoleDefinition
import uuid
role_definition_client = AuthorizationManagementClient(
credential=credential,
subscription_id=subscription_id,
api_version="2018-01-01-preview",
)
現在,進行初始化以建立角色指派:
from azure.mgmt.authorization.v2020_10_01_preview.models import (
RoleAssignment,
RoleAssignmentCreateParameters,
)
role_assignment_client = AuthorizationManagementClient(
credential=credential,
subscription_id=subscription_id,
api_version="2020-10-01-preview",
)
然後,取得使用者指派受控識別的主體識別碼和用戶端識別碼。 若要指派角色,只需要用到主體識別碼。 不過建立部署之前,您會使用用戶端識別碼來填入 UAI_CLIENT_ID
預留位置環境變數。
uai_identity = msi_client.user_assigned_identities.get(
resource_group_name=resource_group, resource_name=uai_name
)
uai_principal_id = uai_identity.principal_id
uai_client_id = uai_identity.client_id
接下來,將「儲存體 Blob 資料讀者」角色指派給端點。 系統會依名稱擷取角色定義,並連同端點的主體識別碼一起傳遞。 角色會套用到上面建立的儲存體帳戶範圍,以允許端點讀取檔案。
role_name = "Storage Blob Data Reader"
scope = storage_account.id
role_defs = role_definition_client.role_definitions.list(scope=scope)
role_def = next((r for r in role_defs if r.role_name == role_name))
role_assignment_client.role_assignments.create(
scope=scope,
role_assignment_name=str(uuid.uuid4()),
parameters=RoleAssignmentCreateParameters(
role_definition_id=role_def.id,
principal_id=uai_principal_id,
principal_type="ServicePrincipal",
),
)
在接下來的兩個權限中,需要使用工作區和容器登錄物件:
workspace = ml_client.workspaces.get(workspace_name)
container_registry = workspace.container_registry
接下來,將 AcrPull 角色指派給使用者指派的身分識別。 此角色可從 Azure Container Registry 提取映像。 範圍會套用至與工作區相關聯的容器登錄層級。
role_name = "AcrPull"
scope = container_registry
role_defs = role_definition_client.role_definitions.list(scope=scope)
role_def = next((r for r in role_defs if r.role_name == role_name))
role_assignment_client.role_assignments.create(
scope=scope,
role_assignment_name=str(uuid.uuid4()),
parameters=RoleAssignmentCreateParameters(
role_definition_id=role_def.id,
principal_id=uai_principal_id,
principal_type="ServicePrincipal",
),
)
最後,將「儲存體 Blob 資料讀者」角色指派給工作區儲存體帳戶範圍的端點。 此角色指派可讓端點讀取工作區儲存體帳戶中的 Blob,以及新建立的儲存體帳戶。
角色的名稱和功能與上面指派的第一個角色相同,不過會套用至不同的範圍,而且識別碼不同。
role_name = "Storage Blob Data Reader"
scope = workspace.storage_account
role_defs = role_definition_client.role_definitions.list(scope=scope)
role_def = next((r for r in role_defs if r.role_name == role_name))
role_assignment_client.role_assignments.create(
scope=scope,
role_assignment_name=str(uuid.uuid4()),
parameters=RoleAssignmentCreateParameters(
role_definition_id=role_def.id,
principal_id=uai_principal_id,
principal_type="ServicePrincipal",
),
)
用來存取 Azure 資源的評分指令碼
請參閱下列指令碼,以了解如何使用您的身分識別權杖來存取 Azure 資源,在此案例中是在先前章節建立的儲存體帳戶。
import os
import logging
import json
import numpy
import joblib
import requests
from azure.identity import ManagedIdentityCredential
from azure.storage.blob import BlobClient
def access_blob_storage_sdk():
credential = ManagedIdentityCredential(client_id=os.getenv("UAI_CLIENT_ID"))
storage_account = os.getenv("STORAGE_ACCOUNT_NAME")
storage_container = os.getenv("STORAGE_CONTAINER_NAME")
file_name = os.getenv("FILE_NAME")
blob_client = BlobClient(
account_url=f"https://{storage_account}.blob.core.windows.net/",
container_name=storage_container,
blob_name=file_name,
credential=credential,
)
blob_contents = blob_client.download_blob().content_as_text()
logging.info(f"Blob contains: {blob_contents}")
def get_token_rest():
"""
Retrieve an access token via REST.
"""
access_token = None
msi_endpoint = os.environ.get("MSI_ENDPOINT", None)
msi_secret = os.environ.get("MSI_SECRET", None)
# If UAI_CLIENT_ID is provided then assume that endpoint was created with user assigned identity,
# # otherwise system assigned identity deployment.
client_id = os.environ.get("UAI_CLIENT_ID", None)
if client_id is not None:
token_url = (
msi_endpoint + f"?clientid={client_id}&resource=https://storage.azure.com/"
)
else:
token_url = msi_endpoint + f"?resource=https://storage.azure.com/"
logging.info("Trying to get identity token...")
headers = {"secret": msi_secret, "Metadata": "true"}
resp = requests.get(token_url, headers=headers)
resp.raise_for_status()
access_token = resp.json()["access_token"]
logging.info("Retrieved token successfully.")
return access_token
def access_blob_storage_rest():
"""
Access a blob via REST.
"""
logging.info("Trying to access blob storage...")
storage_account = os.environ.get("STORAGE_ACCOUNT_NAME")
storage_container = os.environ.get("STORAGE_CONTAINER_NAME")
file_name = os.environ.get("FILE_NAME")
logging.info(
f"storage_account: {storage_account}, container: {storage_container}, filename: {file_name}"
)
token = get_token_rest()
blob_url = f"https://{storage_account}.blob.core.windows.net/{storage_container}/{file_name}?api-version=2019-04-01"
auth_headers = {
"Authorization": f"Bearer {token}",
"x-ms-blob-type": "BlockBlob",
"x-ms-version": "2019-02-02",
}
resp = requests.get(blob_url, headers=auth_headers)
resp.raise_for_status()
logging.info(f"Blob contains: {resp.text}")
def init():
global model
# AZUREML_MODEL_DIR is an environment variable created during deployment.
# It is the path to the model folder (./azureml-models/$MODEL_NAME/$VERSION)
# For multiple models, it points to the folder containing all deployed models (./azureml-models)
# Please provide your model's folder name if there is one
model_path = os.path.join(
os.getenv("AZUREML_MODEL_DIR"), "model/sklearn_regression_model.pkl"
)
# deserialize the model file back into a sklearn model
model = joblib.load(model_path)
logging.info("Model loaded")
# Access Azure resource (Blob storage) using system assigned identity token
access_blob_storage_rest()
access_blob_storage_sdk()
logging.info("Init complete")
# note you can pass in multiple rows for scoring
def run(raw_data):
logging.info("Request received")
data = json.loads(raw_data)["data"]
data = numpy.array(data)
result = model.predict(data)
logging.info("Request processed")
return result.tolist()
使用您的組態建立部署
建立與線上端點相關聯的部署。 深入了解如何部署到線上端點。
警告
這項部署可能需要大約 8-14 分鐘的時間,視基礎環境/映像是否為第一次建立而定。 使用相同環境的後續部署將會更快。
az ml online-deployment create --endpoint-name $ENDPOINT_NAME --all-traffic --name blue --file endpoints/online/managed/managed-identities/2-sai-deployment.yml --set environment_variables.STORAGE_ACCOUNT_NAME=$STORAGE_ACCOUNT_NAME environment_variables.STORAGE_CONTAINER_NAME=$STORAGE_CONTAINER_NAME environment_variables.FILE_NAME=$FILE_NAME
注意
引數 --name
的值可能會覆寫 YAML 檔案內的 name
索引鍵。
檢查部署狀態。
az ml online-deployment show --endpoint-name $ENDPOINT_NAME --name blue
若要將上述查詢修改為只傳回特定資料,請參閱查詢 Azure CLI 命令輸出。
注意
評分指令碼中的 init 方法會使用系統指派的受控識別權杖,從您的儲存體帳戶讀取檔案。
若要檢查 init 方法輸出,請使用下列程式碼來查看部署記錄。
# Check deployment logs to confirm blob storage file contents read operation success.
az ml online-deployment get-logs --endpoint-name $ENDPOINT_NAME --name blue
az ml online-endpoint create --name $ENDPOINT_NAME -f endpoints/online/managed/managed-identities/1-uai-create-endpoint.yml --set identity.user_assigned_identities[0].resource_id=$uai_id
注意
引數 --name
的值可能會覆寫 YAML 檔案內的 name
索引鍵。
執行命令之後,您就可以檢查部署的狀態。
az ml online-endpoint show --name $ENDPOINT_NAME
若要將上述查詢修改為只傳回特定資料,請參閱查詢 Azure CLI 命令輸出。
# Check deployment logs to confirm blob storage file contents read operation success.
az ml online-deployment get-logs --endpoint-name $ENDPOINT_NAME --name blue
注意
評分指令碼中的 init 方法會使用使用者指派的受控識別權杖,從您的儲存體帳戶讀取檔案。
若要檢查 init 方法輸出,請使用下列程式碼來查看部署記錄。
# Check deployment logs to confirm blob storage file contents read operation success.
az ml online-deployment get-logs --endpoint-name $ENDPOINT_NAME --name blue
首先,建立部署:
ml_client.online_deployments.begin_create_or_update(deployment).result()
部署完成後,請檢查其狀態並確認身分識別詳細資料:
deployment = ml_client.online_deployments.get(
endpoint_name=endpoint_name, name=deployment.name
)
print(deployment)
注意
評分指令碼中的 init 方法會使用系統指派的受控識別權杖,從您的儲存體帳戶讀取檔案。
若要檢查 init 方法輸出,請使用下列程式碼來查看部署記錄。
ml_client.online_deployments.get_logs(deployment.name, deployment.endpoint_name, 1000)
現在已確認部署,請將流量設為 100%:
endpoint.traffic = {str(deployment.name): 100}
ml_client.begin_create_or_update(endpoint).result()
部署之前,請先更新 UAI_CLIENT_ID
環境變數預留位置。
deployment.environment_variables["UAI_CLIENT_ID"] = uai_client_id
現在,建立部署:
ml_client.online_deployments.begin_create_or_update(deployment).result()
部署完成後,請檢查其狀態並確認身分識別詳細資料:
deployment = ml_client.online_deployments.get(
endpoint_name=endpoint_name, name=deployment.name
)
print(deployment)
注意
評分指令碼中的 init 方法會使用使用者指派的受控識別權杖,從您的儲存體帳戶讀取檔案。
若要檢查 init 方法輸出,請使用下列程式碼來查看部署記錄。
ml_client.online_deployments.get_logs(deployment.name, deployment.endpoint_name, 1000)
現在已確認部署,請將流量設為 100%:
endpoint.traffic = {str(deployment.name): 100}
ml_client.begin_create_or_update(endpoint).result()
當您的部署完成時,會在您的 Azure Machine Learning 工作區中註冊模型、環境和端點。
測試端點
部署線上端點後,請透過要求測試並確認其作業。 推斷的詳細資料會因模型而異。 在本指南中,JSON 查詢參數看起來如下所示:
{"data": [
[1,2,3,4,5,6,7,8,9,10],
[10,9,8,7,6,5,4,3,2,1]
]}
若要呼叫您的端點,請執行:
az ml online-endpoint invoke --name $ENDPOINT_NAME --request-file endpoints/online/model-1/sample-request.json
az ml online-endpoint invoke --name $ENDPOINT_NAME --request-file endpoints/online/model-1/sample-request.json
sample_data = "../../model-1/sample-request.json"
ml_client.online_endpoints.invoke(endpoint_name=endpoint_name, request_file=sample_data)
sample_data = "../../model-1/sample-request.json"
ml_client.online_endpoints.invoke(endpoint_name=endpoint_name, request_file=sample_data)
刪除端點和儲存體帳戶
如果您不打算繼續使用已部署的線上端點和儲存體,請將其刪除以降低成本。 當您刪除端點時,也會一併刪除其所有相關聯的部署。
az ml online-endpoint delete --name $ENDPOINT_NAME --yes
az storage account delete --name $STORAGE_ACCOUNT_NAME --yes
az ml online-endpoint delete --name $ENDPOINT_NAME --yes
az storage account delete --name $STORAGE_ACCOUNT_NAME --yes
az identity delete --name $UAI_NAME
刪除端點:
ml_client.online_endpoints.begin_delete(endpoint_name)
刪除儲存體帳戶:
storage_client.storage_accounts.delete(
resource_group_name=resource_group, account_name=storage_account_name
)
刪除端點:
ml_client.online_endpoints.begin_delete(endpoint_name)
刪除儲存體帳戶:
storage_client.storage_accounts.delete(
resource_group_name=resource_group, account_name=storage_account_name
)
刪除使用者指派的受控識別:
msi_client.user_assigned_identities.delete(
resource_group_name=resource_group, resource_name=uai_name
)
相關內容