教學:使用代理身份從無伺服器沙箱存取 Azure 資源(預覽版)

透過使用代理程式身份,您可以為 Azure 容器執行個體 中的單一無伺服器沙箱指派 Microsoft Entra Agent ID,讓沙箱中執行的程式碼能取得 Microsoft Entra 令牌並存取 Azure 資源,而無需將密鑰儲存在沙盒。 沒有代理身份的沙盒無法從實例元資料端點取得令牌,即使它們運行於同一 AI 代理群組中。

在本教學課程中,您將設定具有使用者指派受控身分識別的 AI 代理程式群組,以進行同盟權杖交換,授與代理程式身分識別存取 Azure Blob 儲存體容器的權限,確認沒有代理程式身分識別的沙箱會遭拒存取,然後建立具有代理程式身分識別的沙箱,以寫入、讀取及刪除 blob。

在這個教學中,你會學到如何:

  • 為代理程式識別藍圖設定使用者指派的受控識別與同盟識別憑證
  • 在 AI 代理程式群組上設定 identityProfile.federatedIdentityCredential
  • 確認沒有代理程式身分識別的沙箱無法取得權杖
  • 建立一個沙agentIdentities盒,並從沙箱內部存取 Azure Blob 儲存體

Prerequisites

  • Azure 訂用帳戶。 如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶。

  • Azure CLI(版本 2.60 或更新版本)已登入az login,或使用其他工具登入,以向 Azure Resource Manager 傳送經過驗證的 REST 請求。

  • 在您的訂用帳戶中註冊的 Microsoft.ContainerInstance 資源提供者。

    az provider register --namespace Microsoft.ContainerInstance --wait
    
  • 分配給您訂閱中的計算沙盒群組服務主體的貢獻者、Azure 部署堆疊擁有者及儲存 Blob 資料貢獻者角色,以便該服務能配置您訂閱中的受管理資源群組與快照儲存帳戶。 要指派角色,您需要有權限在訂閱上建立角色指派,例如 擁有者 或 使用者存取管理員 角色:

    subscriptionId=$(az account show --query id --output tsv)
    spObjectId=$(az ad sp show --id 1eeacc2b-ec4a-4b1e-977a-2b5fef2131c6 --query id --output tsv 2>/dev/null || \
      az ad sp create --id 1eeacc2b-ec4a-4b1e-977a-2b5fef2131c6 --query id --output tsv)
    
    for role in "Contributor" "Azure Deployment Stack Owner" "Storage Blob Data Contributor"; do
      az role assignment create --assignee-object-id $spObjectId --assignee-principal-type ServicePrincipal \
        --role "$role" --scope /subscriptions/$subscriptionId
    done
    

    角色指派可能需要最多 15 分鐘才能生效。

  • 在您的訂閱中為 Azure 容器執行個體 中無伺服器沙盒配置的配額:

    1. 在 Azure 入口網站中的新增支援要求 (將問題類型設為服務與訂用帳戶限制 (配額),並將配額類型設為容器執行個體),選取您的訂用帳戶,然後前往 [其他詳細資料] 索引標籤。

    2. 選擇「輸入詳細資料」以開啟配額詳細資料窗格,選擇您的位置,為配額類型選擇AIAgentsGroups - StandardCores (Preview),並填寫網路類型、容器類型、總 AIAgentsGroups 群組限制及總 AIAgentsGroups 核心限制:

      Azure 入口網站中新增支援請求頁面的截圖,顯示配額詳細窗格,並選取 AIAgentsGroups - StandardCores (Preview)。

    3. 提交支援申請。 在您的配額申請獲核准後,請重新註冊 Microsoft.ContainerInstance 資源提供者(az provider register --namespace Microsoft.ContainerInstance --wait),以便您的訂閱能接收新啟用的功能。

  • 在建立 AI 代理群組和沙箱後(請參閱 快速入門:建立您的第一個無伺服器沙箱)後,若要連接正在執行中的沙箱,請使用由沙箱閘道 protobuf 檔案 sandboxgateway.proto產生的 gRPC 用戶端。 需要 gRPC 用戶端,因為沙箱閘道會公開一個 gRPC 服務(aci.sandboxgateway.SandboxGatewayService),用於沙盒內的操作,例如等待準備就緒、執行指令、傳輸檔案及讀取日誌。 若要使用本文件中的跨平台範例 C# CLI(支援 Linux、macOS 和 Windows),請安裝 .NET 8 SDK,並編譯 CLI。

    Note

    如果你透過 Azure Kubernetes Service (AKS) 排程和管理無伺服器沙盒,則不需要 gRPC 用戶端。

準備管理式識別碼、代理程式識別碼及儲存帳戶

  1. 建立資源群組及使用者指派的管理身份。 記錄其資源 ID、主體 ID 及租戶 ID。

    az group create --name myResourceGroup --location centralus
    
    az identity create --resource-group myResourceGroup --name myGroupIdentity --location centralus
    
    identityResourceId=$(az identity show --resource-group myResourceGroup --name myGroupIdentity --query id --output tsv)
    identityPrincipalId=$(az identity show --resource-group myResourceGroup --name myGroupIdentity --query principalId --output tsv)
    tenantId=$(az account show --query tenantId --output tsv)
    
  2. 在 Microsoft Entra ID 中,建立代理程式身份藍圖,並在藍圖上設定一個聯邦身份憑證,以信任 AI 代理程式群組中使用者指派的管理身份:

    • 發行人:https://login.microsoftonline.com/<tenant-id>/v2.0
    • 主體識別碼:<identityPrincipalId> (即 principalId 的 myGroupIdentity 值)
    • 受眾:api://AzureADTokenExchange

    接著從藍圖建立一個代理識別。 記錄藍圖的應用程式(用戶端)ID(<blueprint-client-id>)以及代理程式身份的應用程式(用戶端)ID(<agent-client-id>)與物件ID(<agent-object-id>)。

  3. 建立一個 Azure 儲存體 帳戶和一個 blob 容器。 將儲存體帳戶上的 Storage Blob Data Contributor 角色指派給 代理程式身分識別(非 myGroupIdentity)。

    storageAccount="aisandboxstore$RANDOM"
    
    az storage account create --resource-group myResourceGroup --name $storageAccount --location centralus --sku Standard_LRS
    az storage container create --account-name $storageAccount --name agentdemo --auth-mode login
    
    storageAccountId=$(az storage account show --resource-group myResourceGroup --name $storageAccount --query id --output tsv)
    
    az role assignment create --assignee-object-id <agent-object-id> --assignee-principal-type ServicePrincipal \
      --role "Storage Blob Data Contributor" --scope $storageAccountId
    

設定 AI 代理群組的同盟身分識別認證

  1. 建立或更新 AI 代理群組,並附加在 identity.userAssignedIdentities 中的使用者指派受控識別,並將其 principalId 設定在 properties.identityProfile.federatedIdentityCredential。

    PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.ContainerInstance/AIAgentsGroups/myAgentsGroup?api-version=2026-08-01-preview
    Content-Type: application/json
    
    {
      "location": "centralus",
      "identity": {
        "type": "UserAssigned",
        "userAssignedIdentities": {
          "/subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myGroupIdentity": {}
        }
      },
      "properties": {
        "identityProfile": {
          "federatedIdentityCredential": "<identity-principal-id>"
        }
      }
    }
    
  2. 持續檢查 AI 代理群組,直到 properties.provisioningState 是 Succeeded,然後呼叫 connect 來取得它的 {endpoint} 和 {accessToken}:

    GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.ContainerInstance/AIAgentsGroups/myAgentsGroup?api-version=2026-08-01-preview
    
    POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.ContainerInstance/AIAgentsGroups/myAgentsGroup/connect?api-version=2026-08-01-preview
    

確認沒有代理程式身份的沙箱是否被拒絕

  1. 在群組中建立沙盒,而不設定 properties.agentIdentities:

    PUT {endpoint}/sandboxes/sandbox-no-id?api-version=2026-08-01-preview
    Authorization: Bearer {accessToken}
    Content-Type: application/json
    
    {
      "location": "centralus",
      "properties": {
        "image": "mcr.microsoft.com/mirror/docker/library/nginx:1.25",
        "resources": {
          "cpu": 1,
          "memory": 2
        }
      }
    }
    

    等待直到 properties.provisioningState 為 properties.connectionString,複製 WaitForReady,並等待來賓準備就緒(Succeeded)。 透過使用 範例 C# CLI:

    dotnet run -- -cs "<sandbox-no-id-connection-string>" wait
    
  2. 在 sandbox-no-id內部嘗試從實例中繼資料端點(http://169.254.169.254/metadata/identity/oauth2/token)請求 Azure 儲存體 的存取權杖。 請使用範例 C# CLI:

    dotnet run -- -cs "<sandbox-no-id-connection-string>" exec /bin/sh -c '
    resp=$(curl -s -H "Metadata: true" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://storage.azure.com/")
    token=$(printf "%s" "$resp" | sed -n "s/.*\"access_token\" *: *\"\([^\"]*\)\".*/\1/p")
    if [ -z "$token" ]; then echo "DENIED: no identity token available for this sandbox"; fi'
    

    由於未將代理身分指派給 sandbox-no-id,因此不會傳回任何 access_token:

    DENIED: no identity token available for this sandbox
    

建立具有代理身份的沙盒並存取 Azure Blob 儲存體

  1. 建立一個沙盒,其中 properties.agentIdentities 設為 agentId(<agent-client-id>),且具有 agentBlueprintId(<blueprint-client-id>):

    PUT {endpoint}/sandboxes/sandbox-with-id?api-version=2026-08-01-preview
    Authorization: Bearer {accessToken}
    Content-Type: application/json
    
    {
      "location": "centralus",
      "properties": {
        "image": "mcr.microsoft.com/mirror/docker/library/nginx:1.25",
        "resources": {
          "cpu": 1,
          "memory": 2
        },
        "agentIdentities": [
          {
            "agentId": "<agent-client-id>",
            "agentBlueprintId": "<blueprint-client-id>"
          }
        ]
      }
    }
    

    等待直到 properties.provisioningState 為 properties.connectionString,複製 WaitForReady,並等待來賓準備就緒(Succeeded)。 透過使用範例 C# CLI:

    dotnet run -- -cs "<sandbox-with-id-connection-string>" wait
    
  2. 在 sandbox-with-id內,請求一個 token http://169.254.169.254/metadata/identity/oauth2/token (或在 Azure SDK 中使用DefaultAzureCredential),並在儲存容器中寫入、讀取及刪除 blob。 將 <storage-account-name> 取代為您的儲存體帳戶名稱。 請使用範例 C# CLI:

    dotnet run -- -cs "<sandbox-with-id-connection-string>" exec /bin/sh -c '
    resp=$(curl -s -H "Metadata: true" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://storage.azure.com/")
    token=$(printf "%s" "$resp" | sed -n "s/.*\"access_token\" *: *\"\([^\"]*\)\".*/\1/p")
    blob="https://<storage-account-name>.blob.core.windows.net/agentdemo/agent-demo.txt"
    put=$(curl -s -o /dev/null -w "%{http_code}" -X PUT -H "Authorization: Bearer $token" -H "x-ms-version: 2021-08-06" -H "x-ms-blob-type: BlockBlob" -H "Content-Type: text/plain" --data "hello from the agent-identity sandbox" "$blob")
    echo "write  (PUT)    : HTTP $put"
    get=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer $token" -H "x-ms-version: 2021-08-06" "$blob")
    echo "read   (GET)    : HTTP $get"
    del=$(curl -s -o /dev/null -w "%{http_code}" -X DELETE -H "Authorization: Bearer $token" -H "x-ms-version: 2021-08-06" "$blob")
    echo "delete (DELETE) : HTTP $del"'
    

    發出給沙盒的令牌承appidoid載代理身份的聲明,且三種儲存操作皆成功:

    write  (PUT)    : HTTP 201
    read   (GET)    : HTTP 200
    delete (DELETE) : HTTP 202
    
  3. 解碼存取 sandbox-with-id 權杖有效載荷,以確認該權杖屬於代理身份(<agent-client-id>),而非使用者指派的管理身份(myGroupIdentity)。 請使用範例 C# CLI:

    dotnet run -- -cs "<sandbox-with-id-connection-string>" exec /bin/sh -c '
    resp=$(curl -s -H "Metadata: true" "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://storage.azure.com/")
    token=$(printf "%s" "$resp" | sed -n "s/.*\"access_token\" *: *\"\([^\"]*\)\".*/\1/p")
    payload=$(printf "%s" "$token" | cut -d. -f2 | tr "_-" "/+")
    case $(( ${#payload} % 4 )) in 2) payload="${payload}==";; 3) payload="${payload}=";; esac
    printf "%s" "$payload" | base64 -d 2>/dev/null | tr "," "\n" | grep -E "\"(appid|oid|azp|sub|xms_act_fct)\""'
    

    解碼後的聲明顯示 appid 設為 <agent-client-id>(被授予存取儲存帳戶的代理程式身分),而 xms_act_fct 則指出實際執行的代理程式:

    "appid":"<agent-client-id>"
    "oid":"<agent-object-id>"
    "sub":"<agent-object-id>"
    "xms_act_fct":"11 3"
    

清理資源

刪除您在本教學中建立的沙盒:

DELETE {endpoint}/sandboxes/sandbox-no-id?api-version=2026-08-01-preview
Authorization: Bearer {accessToken}
DELETE {endpoint}/sandboxes/sandbox-with-id?api-version=2026-08-01-preview
Authorization: Bearer {accessToken}

如果你不打算做其他教學,請刪除 AI agents 群組和資源群組。

下一步