You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Bicep实现Azure ML Notebook增删自动化及解决上传错误

Azure ML Notebook自动化添加/移除问题解决

问题背景

需要实现Azure Machine Learning资源中Notebook的添加与移除全自动化,覆盖用户目录及自定义目录场景。最初尝试通过Microsoft.MachineLearningServices workspaces/data实现,但未找到可用示例。经调研确认,Notebook存储于关联Storage Account的FileShare中,编写Bicep脚本尝试上传文件时出现路径识别错误——文件已上传至CLI控制台,但脚本无法识别路径,单独执行az storage file upload命令可正常运行。


解决方案

1. 修正Bicep脚本的文件路径问题

Deployment Script的Azure CLI运行环境有独立的文件系统,本地上传的文件默认不在脚本可访问的路径下,需调整脚本逻辑:

方式一:利用临时目录中转

修改scriptContent,先将文件复制到脚本可访问的临时目录再上传:

scriptContent: '''
# 将控制台上传的文件复制到临时目录
cp ${__filename} /tmp/${__filename}
# 执行上传命令
az storage file upload --source /tmp/${__filename} -s ${__fileShareName} --path teste
'''

方式二:直接传入文件内容(适合小体积Notebook)

添加参数接收文件内容,写入临时文件后上传:

# 新增参数接收Notebook内容
@description('Content of the target notebook file')
param __notebookContent string

resource deploymentScript 'Microsoft.Resources/deploymentScripts@2023-08-01' = {
  name: 'uploadFile'
  location: location
  kind: 'AzureCLI'
  properties: {
    azCliVersion: '2.52.0'
    retentionInterval: 'PT1H'
    environmentVariables: [
      {
        name: 'AZURE_STORAGE_ACCOUNT'
        value: storageAccount.name
      }
      {
        name: 'AZURE_STORAGE_KEY'
        secureValue: storageAccount.listKeys().keys[0].value
      }
      {
        name: 'NOTEBOOK_CONTENT'
        secureValue: __notebookContent
      }
    ]
    scriptContent: '''
    echo "$NOTEBOOK_CONTENT" > /tmp/${__filename}
    az storage file upload --source /tmp/${__filename} -s ${__fileShareName} --path teste
    '''
  }
}

2. 完整自动化流程实现

添加Notebook

  • 确认目标Storage Account是Azure ML Workspace的关联存储(默认存储或附加存储)
  • 按路径规则上传:
    • 用户目录对应FileShare路径:Users/<你的用户名>
    • 自定义目录对应FileShare路径:Custom/<自定义文件夹名>

移除Notebook

通过Azure CLI命令删除文件共享中的目标Notebook,可集成到Bicep脚本或自动化流水线:

az storage file delete -s <文件共享名称> --path <Notebook完整路径> --account-name <存储账户名称>

3. 更优替代方案:Azure ML Python SDK

使用SDK直接操作Azure ML Workspace的Notebook,无需直接对接存储账户,更贴合原生逻辑:

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

# 初始化Workspace客户端
ml_client = MLClient(
    DefaultAzureCredential(),
    subscription_id="<你的订阅ID>",
    resource_group_name="<资源组名称>",
    workspace_name="<ML工作区名称>"
)

# 上传Notebook到用户目录
ml_client.notebooks.upload(
    source="本地Notebook文件路径",
    target_path="Users/<你的用户名>/目标文件名.ipynb"
)

# 删除指定Notebook
ml_client.notebooks.delete(
    name="目标文件名.ipynb",
    path="Users/<你的用户名>"
)

内容的提问来源于stack exchange,提问作者Guilherme Matheus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 10:42:38