如何使用 python SDK 将 Azure ML 计算实例分配给用户

问题描述 投票:0回答:2

如何使用 python SDK 将计算实例分配给用户?

现在我正在使用以下代码通过 serviceprincipal 身份验证连接到我的工作区

from azureml.core import Workspace
from azureml.core.authentication import ServicePrincipalAuthentication

svc_pr = ServicePrincipalAuthentication(
    tenant_id="tenant_id_from_my_account",
    service_principal_id="service_principal_id_of_my_app",
    service_principal_password='password_of_my_service_principal')


ws = Workspace(
    subscription_id="my_subscription_id",
    resource_group="my_resource_group",
    workspace_name="my_workspacename",
    auth=svc_pr)

要创建计算实例,我正在使用此代码片段

from azureml.core.compute import ComputeTarget, ComputeInstance
from azureml.core.compute_target import ComputeTargetException

compute_name = "light-medium-gabriel-2nd"

# Verify that instance does not exist already
try:
    instance = ComputeInstance(workspace=ws, name=compute_name)
    print('Found existing instance, use it.')
except ComputeTargetException:
    compute_config = ComputeInstance.provisioning_configuration(
        vm_size='STANDARD_E4S_V3',
        ssh_public_access=False,
        tags = {'projeto' : 'Data Science','Ambiente':'Homologação'},
    )
    instance = ComputeInstance.create(ws, compute_name, compute_config)
    instance.wait_for_completion(show_output=True)

但是我无法访问计算实例。因为我正在使用服务主体认证,所以就像我正在创建分配给服务主体而不是我的用户的计算实例?

python azure-machine-learning-service azure-machine-learning-studio azure-sdk-python
2个回答
0
投票

我在我的环境中尝试了以下结果:

您可以使用 Defaultazurecredential

 方法在 
AzureML workspace 中与用户一起创建计算实例。

您可以按照这个MS-DOCS创建计算实例。

代码:

from azure.identity import DefaultAzureCredential
from azure.ai.ml.entities import ComputeInstance
import datetime
from azure.ai.ml import MLClient

subscription_id = "<sub id>"
resource_group = "<resource_grp>"
workspace_name = "wrkspace_name"
credential=DefaultAzureCredential()
ml_client = MLClient(subscription_id,resource_group,workspace_name,credential)
ci_basic_name = "v-vsettu1" + datetime.datetime.now().strftime("%Y%m%d%H%M")
ci_basic = ComputeInstance(name=ci_basic_name,size="STANDARD_DS3_v2")
ml_client.begin_create_or_update(ci_basic).result()

控制台:

enter image description here

此外,您可以使用 Cli 命令(v2)创建计算实例。

命令:

az ml compute create -f instance1.yml

yaml

$schema: https://azuremlschemas.azureedge.net/latest/computeInstance.schema.json 
name: v-vsettu1
type: computeinstance
size: STANDARD_DS3_v2

传送门:

enter image description here


0
投票

首先,您需要向 Azure 进行身份验证

import os
from azure.ai.ml import exceptions
from azure.identity import DefaultAzureCredential
from azure.identity import InteractiveBrowserCredential

try:
    # NOTE: Using Azure CLI login
    credential: DefaultAzureCredential = DefaultAzureCredential(
                        exclude_cli_credential=False
                        )
    
    credential.get_token("https://management.azure.com/.default",
                         tenant_id=os.environ.get("AZURE_TENANT_ID"))           
except Exception as ex:
    # Fall back to InteractiveBrowserCredential in case DefaultAzureCredential does not work
    # TODO: Add try-except clause for the AZURE_ variables retrieval 
    credential = InteractiveBrowserCredential(
                        tenant_id=os.environ.get("AZURE_TENANT_ID"),
                        login_hint=os.environ.get("AZURE_USERNAME"))
    credential.get_token("https://management.azure.com/.default",
                         tenant_id=os.environ.get("AZURE_TENANT_ID")) 
finally:
    print("Success!")

其次,您需要创建您的 MLClient

from azure.ai.ml import MLClient
from azure.ai.ml.exceptions import ValidationException

# NOTE: We specify a CONFIG_PATH to store the config.json
CONFIG_PATH = "/home/steeve/Git/azureml-examples/.amls/"
try:
    # Load MLClient from a configuration file
    ml_client = MLClient.from_config(credential=credential,
                                               path=CONFIG_PATH,
                                               file_name="config.json")
except ValidationException as ex:
    # NOTE: Update workspace information if not correctly configured
    client_config = {
        "subscription_id": os.environ.get("AZURE_SUBSCRIPTION_ID"),
        "resource_group": os.environ.get("AMLS_RESOURCE_GROUP"),
        "workspace_name": os.environ.get("AMLS_WORKSPACE")}
 
    # Write and reload from config file
    import json

    os.makedirs(name=os.path.dirname(CONFIG_PATH), exist_ok=True)
    with open(file=os.path.join(CONFIG_PATH, "config.json"), mode="w") as file:
        file.write(json.dumps(client_config))

    ml_client = MLClient.from_config(credential=credential, 
                                               path=CONFIG_PATH, 
                                               file_name="config.json")
# Print the ml_client
print(ml_client)

第三,您创建一个计算实例

import random
from azure.ai.ml.entities import ComputeInstance
from azure.core.exceptions import ResourceNotFoundError
from azure.ai.ml.entities import AssignedUserConfiguration

# NOTE: Refer to AAD to find the user Object ID and Tenant ID
ci_user = AssignedUserConfiguration(                                               
                     user_tenant_id=os.environ.get("AZURE_TENANT_ID"),                                                  
                     user_object_id=os.environ.get("AZURE_USER_ID"))

# Set the random seed
random.seed(a=12)

# NOTE: The pattern is simple: username + some random integer + -ci 
compute_instance_name = f"{os.environ.get('AZURE_USERNAME').split('@')[0]}-{random.randint(a=0, b=1000)}-ci"

# Create compute instance
try:
    compute_instance = ml_client.compute.get(name=compute_instance_name)
    print(f"Found compute instance {compute_instance.name}. Use it.")
except ResourceNotFoundError as e:
    compute_instance = ComputeInstance(
                                name=compute_instance_name, 
                                create_on_behalf_of=ci_user)
                                )

    # Compute instance creation
    print(f"Creating {compute_instance.name}...")
    ml_client.compute.begin_create_or_update(compute=compute_instance)

计算实例将分配给

ci_user
.

© www.soinside.com 2019 - 2024. All rights reserved.