如何使用受控識別從 Azure 虛擬機連線到 Azure Cosmos DB

警告

本文參考 CentOS,亦即接近生命週期結束 (EOL) 狀態的 Linux 發行版本。 請據以考慮您的使用和規劃。 如需詳細資訊,請參閱 CentOS 生命週期結束指引

在本文中,我們會設定虛擬機以使用受控識別來連線到 Azure Cosmos DB。 Azure Cosmos DB 是完全受控的 NoSQL 資料庫,可用於新式應用程式開發。 Azure 資源的 受控識別可讓您的應用程式在使用 Azure 管理的身分識別存取支援 Microsoft Entra 驗證的服務時進行驗證。

必要條件

建立資源群組

建立名為 mi-test的資源群組。 我們將此資源群組用於本教學課程中使用的所有資源。

使用受控識別建立 Azure VM

在本教學課程中,您需要 Azure 虛擬機(VM)。 建立已啟用系統指派受控識別的虛擬機,稱為 mi-vm-01。 您也可以在稍早建立的資源群組中建立名為mi-ua-01的使用者指派受控識別mi-test)。 如果您使用使用者指派的受控識別,您可以在建立期間將它指派給 VM。

建立具有系統指派受控識別的 VM

若要建立已啟用系統指派受控識別的 Azure VM,您的帳戶需要 虛擬機參與者 角色指派。 不需要其他 Microsoft Entra 角色指派。

  • 從 Azure 入口網站 搜尋虛擬機
  • 選擇 [建立]
  • 在 [基本] 索引標籤中,提供必要資訊。
  • 選擇 [下一步:磁碟] >
  • 視需要繼續填寫資訊,然後在 [ 管理 ] 索引標籤中尋找 [ 分識別] 區段,然後核取 [系統指派的受控識別] 旁 的方塊

顯示如何在建立 VM 時啟用系統指派受控識別的影像。

如需詳細資訊,請檢閱 Azure 虛擬機檔:

建立具有使用者指派受控識別的 VM

下列步驟說明如何建立已設定使用者指派受控識別的虛擬機。

目前,Azure 入口網站 不支援在建立 VM 期間指派使用者指派的受控識別。 您應該建立虛擬機,然後將使用者指派的受控識別指派給虛擬機。

使用 Azure 入口網站在虛擬機器上設定 Azure 資源受控識別

建立 Azure Cosmos DB 帳戶

既然我們有一個具有使用者指派受控識別或系統指派受控識別的 VM,我們需要您擁有系統管理許可權的 Azure Cosmos DB 帳戶。 如果您需要建立本教學課程的 Azure Cosmos DB 帳戶, Azure Cosmos DB 快速入門 會提供如何執行此動作的詳細步驟。

注意

受控識別可用來存取支援 Microsoft Entra 驗證的任何 Azure 資源。 本教學課程假設您的 Azure Cosmos DB 帳戶將會設定,如下所示。

設定 Description
訂用帳戶 訂用帳戶名稱 選取您要用於此 Azure Cosmos DB 帳戶的 Azure 訂用帳戶。
資源群組 資源群組名稱 選取 [mi-test],或選取 [新建],然後輸入新資源群組的唯一名稱。
客戶名稱 唯一名稱 輸入名稱來識別您的 Azure Cosmos DB 帳戶。 因為 documents.azure.com 會附加到您所提供的名稱以建立 URI,請使用唯一名稱。

名稱只能包含小寫字母、數字及連字號 (-) 字元。 其長度必須介於 3 到 44 個字元之間。
API 要建立的帳戶類型 選取 [適用於 NoSQL 的 Azure Cosmos DB] 以使用 SQL 語法建立文件資料庫和查詢。

進一步了解 SQL API
Location 最接近使用者的區域 選取用來裝載 Azure Cosmos DB 帳戶的地理位置。 使用最接近使用者的位置,讓他們能以最快速度存取資料。

注意

如果您要測試,您可能想要套用 Azure Cosmos DB 免費層折扣。 使用 Azure Cosmos DB 免費層,您會在帳戶中免費取得前 1000 RU/秒和 25 GB 的記憶體。 深入了解免費層。 請記住,針對本教學課程的目的,此選擇不會有任何差異。

授予存取權

此時,我們應該同時設定具有受控識別和 Azure Cosmos DB 帳戶的虛擬機。 在繼續之前,我們需要授與受控識別幾個不同的角色。

  • 首先,使用 Azure RBAC 授與 Azure Cosmos DB 管理平面的存取權。 受控識別必須指派 DocumentDB 帳戶參與者角色,才能建立資料庫和容器。

  • 您也需要使用 Azure Cosmos DB RBAC 將受控識別授與參與者角色。 您可以看到下面的特定步驟。

注意

我們將使用 Cosmos DB內建數據參與者 角色。 若要授與存取權,您必須將角色定義與身分識別產生關聯。 在我們的案例中,與虛擬機相關聯的受控識別。

目前 Azure 入口網站 中沒有可用的角色指派選項

存取資料

使用受控識別取得 Azure Cosmos DB 的存取權,可以使用 Azure.identity 連結庫在應用程式中啟用驗證。 您可以直接呼叫 ManagedIdentityCredential ,或使用 DefaultAzureCredential

ManagedIdentityCredential 類別會嘗試使用指派給部署環境的受控識別進行驗證。 DefaultAzureCredential 類別會依序經歷不同的驗證選項。 DefaultAzureCredential 嘗試的第二個驗證選項是受控識別。

在下列範例中,您會使用虛擬機的系統指派的受控識別,建立資料庫、容器、容器中的專案,以及讀取新建立的專案。 如果您想要使用使用者指派的受控識別,您必須指定受控識別的用戶端識別碼來指定使用者指派的受控識別。

string userAssignedClientId = "<your managed identity client Id>";
var tokenCredential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = userAssignedClientId });

若要使用下列範例,您需要有下列 NuGet 套件:

  • Azure.Identity
  • Microsoft.Azure.Cosmos
  • Microsoft.Azure.Management.CosmosDB

除了上述 NuGet 套件之外,您還需要啟用 Include 發行前版本 ,然後新增 Azure.ResourceManager.CosmosDB

using Azure.Identity;
using Azure.ResourceManager.CosmosDB;
using Azure.ResourceManager.CosmosDB.Models;
using Microsoft.Azure.Cosmos;
using System;
using System.Threading.Tasks;

namespace MITest
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Replace the placeholders with your own values
            var subscriptionId = "Your subscription ID";
            var resourceGroupName = "You resource group";
            var accountName = "Cosmos DB Account name";
            var databaseName = "mi-test";
            var containerName = "container01";

            // Authenticate to Azure using Managed Identity (system-assigned or user-assigned)
            var tokenCredential = new DefaultAzureCredential();

            // Create the Cosmos DB management client using the subscription ID and token credential
            var managementClient = new CosmosDBManagementClient(tokenCredential)
            {
                SubscriptionId = subscriptionId
            };

            // Create the Cosmos DB data client using the account URL and token credential
            var dataClient = new CosmosClient($"https://{accountName}.documents.azure.com:443/", tokenCredential);

            // Create a new database using the management client
            var createDatabaseOperation = await managementClient.SqlResources.StartCreateUpdateSqlDatabaseAsync(
                resourceGroupName,
                accountName,
                databaseName,
                new SqlDatabaseCreateUpdateParameters(new SqlDatabaseResource(databaseName), new CreateUpdateOptions()));
            await createDatabaseOperation.WaitForCompletionAsync();

            // Create a new container using the management client
            var createContainerOperation = await managementClient.SqlResources.StartCreateUpdateSqlContainerAsync(
                resourceGroupName,
                accountName,
                databaseName,
                containerName,
                new SqlContainerCreateUpdateParameters(new SqlContainerResource(containerName), new CreateUpdateOptions()));
            await createContainerOperation.WaitForCompletionAsync();

            // Create a new item in the container using the data client
            var partitionKey = "pkey";
            var id = Guid.NewGuid().ToString();
            await dataClient.GetContainer(databaseName, containerName)
                .CreateItemAsync(new { id = id, _partitionKey = partitionKey }, new PartitionKey(partitionKey));

            // Read back the item from the container using the data client
            var pointReadResult = await dataClient.GetContainer(databaseName, containerName)
                .ReadItemAsync<dynamic>(id, new PartitionKey(partitionKey));

            // Run a query to get all items from the container using the data client
            await dataClient.GetContainer(databaseName, containerName)
                .GetItemQueryIterator<dynamic>("SELECT * FROM c")
                .ReadNextAsync();
        }
    }
}

使用 ManagedIdentityCredential 的語言特定範例:

.NET

初始化 Azure Cosmos DB 用戶端:

CosmosClient client = new CosmosClient("<account-endpoint>", new ManagedIdentityCredential());

然後 讀取和寫入數據

Java

初始化 Azure Cosmos DB 用戶端:

CosmosAsyncClient Client = new CosmosClientBuilder().endpoint("<account-endpoint>") .credential(new ManagedIdentityCredential()) .build();

然後讀取和寫入數據,如這些範例所述

JavaScript

初始化 Azure Cosmos DB 用戶端:

const client = new CosmosClient({ "<account-endpoint>", aadCredentials: new ManagedIdentityCredential() });

然後讀取和寫入數據,如這些範例所述

清除步驟

提示

本文中的步驟可能會根據您從開始的入口網站稍有不同。

  1. 登入 Azure 入口網站

  2. 選取您要刪除的資源。

  3. 選取 [刪除]

  4. 出現提示時,確認刪除。

下一步

深入了解 Azure 資源的受控識別:

深入瞭解 Azure Cosmos DB: