選項
首頁首頁 Skill 開發營運和 CI/CD azure-resource-manager-cosmosdb-dotnet

azure-resource-manager-cosmosdb-dotnet

microsoft/skills microsoft/skills

使用 .NET Azure 資源管理器 SDK 提供和管理 Azure Cosmos DB 帳戶、資料庫、容器、吞吐量以及基於角色的訪問控制 (RBAC)。

...展開全部
0
更新時間 2026-09-19

Azure.ResourceManager.CosmosDB (.NET)

用於透過 Azure Resource Manager 預配和管理 Azure Cosmos DB 資源的管理平面 SDK。

⚠️ 管理平面與資料平面

  • 本 SDK (Azure.ResourceManager.CosmosDB):建立賬戶、資料庫、容器,配置吞吐量,管理基於角色的訪問控制 (RBAC)
  • 資料平面 SDK (Microsoft.Azure.Cosmos):對文件執行 CRUD 操作、查詢、儲存過程執行

安裝

dotnet add package Azure.ResourceManager.CosmosDB
dotnet add package Azure.Identity

當前版本:穩定版 v1.4.0,預覽版 v1.4.0-beta.13

環境變數

AZURE_SUBSCRIPTION_ID=<your-subscription-id> # 必需:Azure 訂閱 ID
AZURE_TOKEN_CREDENTIALS=prod  # 僅在生產環境中使用 DefaultAzureCredential 時必需
AZURE_TENANT_ID=<tenant-id> # 用於服務主體身份驗證(可選)
AZURE_CLIENT_ID=<client-id> # 用於服務主體身份驗證(可選)
AZURE_CLIENT_SECRET=<client-secret> # 用於服務主體身份驗證(可選)
</client-secret></client-id></tenant-id></your-subscription-id>

身份驗證

using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.CosmosDB;

// 本地開發:DefaultAzureCredential。生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// 或者在生產環境中直接使用特定的憑據:
// 請參閱 https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
var armClient = new ArmClient(credential);

// 獲取訂閱
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var subscription = armClient.GetSubscriptionResource(
    new ResourceIdentifier($"/subscriptions/{subscriptionId}"));
</specific_credential>

資源層次結構

ArmClient
└── SubscriptionResource
    └── ResourceGroupResource
        └── CosmosDBAccountResource
            ├── CosmosDBSqlDatabaseResource
            │   └── CosmosDBSqlContainerResource
            │       ├── CosmosDBSqlStoredProcedureResource
            │       ├── CosmosDBSqlTriggerResource
            │       └── CosmosDBSqlUserDefinedFunctionResource
            ├── CassandraKeyspaceResource
            ├── GremlinDatabaseResource
            ├── MongoDBDatabaseResource
            └── CosmosDBTableResource

核心工作流

1. 建立 Cosmos DB 賬戶

using Azure.ResourceManager.CosmosDB;
using Azure.ResourceManager.CosmosDB.Models;

// 獲取資源組
var resourceGroup = await subscription
    .GetResourceGroupAsync("my-resource-group");

// 定義賬戶
var accountData = new CosmosDBAccountCreateOrUpdateContent(
    location: AzureLocation.EastUS,
    locations: new[]
    {
        new CosmosDBAccountLocation
        {
            LocationName = AzureLocation.EastUS,
            FailoverPriority = 0,
            IsZoneRedundant = false
        }
    })
{
    Kind = CosmosDBAccountKind.GlobalDocumentDB,
    ConsistencyPolicy = new ConsistencyPolicy(DefaultConsistencyLevel.Session),
    EnableAutomaticFailover = true
};

// 建立賬戶(長時間執行操作)
var accountCollection = resourceGroup.Value.GetCosmosDBAccounts();
var operation = await accountCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-cosmos-account",
    accountData);

CosmosDBAccountResource account = operation.Value;

2. 建立 SQL 資料庫

var databaseData = new CosmosDBSqlDatabaseCreateOrUpdateContent(
    new CosmosDBSqlDatabaseResourceInfo("my-database"));

var databaseCollection = account.GetCosmosDBSqlDatabases();
var dbOperation = await databaseCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-database",
    databaseData);

CosmosDBSqlDatabaseResource database = dbOperation.Value;

3. 建立 SQL 容器

var containerData = new CosmosDBSqlContainerCreateOrUpdateContent(
    new CosmosDBSqlContainerResourceInfo("my-container")
    {
        PartitionKey = new CosmosDBContainerPartitionKey
        {
            Paths = { "/partitionKey" },
            Kind = CosmosDBPartitionKind.Hash
        },
        IndexingPolicy = new CosmosDBIndexingPolicy
        {
            Automatic = true,
            IndexingMode = CosmosDBIndexingMode.Consistent
        },
        DefaultTtl = 86400 // 24 小時
    });

var containerCollection = database.GetCosmosDBSqlContainers();
var containerOperation = await containerCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-container",
    containerData);

CosmosDBSqlContainerResource container = containerOperation.Value;

4. 配置吞吐量

// 手動吞吐量
var throughputData = new ThroughputSettingsUpdateData(
    new ThroughputSettingsResourceInfo
    {
        Throughput = 400
    });

// 自動縮放吞吐量
var autoscaleData = new ThroughputSettingsUpdateData(
    new ThroughputSettingsResourceInfo
    {
        AutoscaleSettings = new AutoscaleSettingsResourceInfo
        {
            MaxThroughput = 4000
        }
    });

// 應用於資料庫
await database.CreateOrUpdateCosmosDBSqlDatabaseThroughputAsync(
    WaitUntil.Completed,
    throughputData);

5. 獲取連線資訊

// 獲取金鑰
var keys = await account.GetKeysAsync();
Console.WriteLine($"Primary Key: {keys.Value.PrimaryMasterKey}");

// 獲取連線字串
var connectionStrings = await account.GetConnectionStringsAsync();
foreach (var cs in connectionStrings.Value.ConnectionStrings)
{
    Console.WriteLine($"{cs.Description}: {cs.ConnectionString}");
}

關鍵型別參考

型別用途
`ArmClient`所有 ARM 操作的入口點
`CosmosDBAccountResource`表示 Cosmos DB 賬戶
`CosmosDBAccountCollection`賬戶 CRUD 的集合
`CosmosDBSqlDatabaseResource`SQL API 資料庫
`CosmosDBSqlContainerResource`SQL API 容器
`CosmosDBAccountCreateOrUpdateContent`賬戶建立負載
`CosmosDBSqlDatabaseCreateOrUpdateContent`資料庫建立負載
`CosmosDBSqlContainerCreateOrUpdateContent`容器建立負載
`ThroughputSettingsUpdateData`吞吐量配置

最佳實踐

  1. 使用 WaitUntil.Completed 用於必須在繼續之前完成的操作
  2. 使用 WaitUntil.Started 當您希望手動輪詢或並行執行操作時
  3. 使用 DefaultAzureCredential — 切勿硬編碼金鑰
  4. 處理 RequestFailedException 以應對 ARM API 錯誤
  5. 使用 CreateOrUpdateAsync 用於冪等操作
  6. *透過 `Get方法導航層次結構**(例如,account.GetCosmosDBSqlDatabases()`)

錯誤處理

using Azure;

try
{
    var operation = await accountCollection.CreateOrUpdateAsync(
        WaitUntil.Completed, accountName, accountData);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
    Console.WriteLine("Account already exists");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"ARM Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

參考檔案

檔案何時閱讀
references/account-management.md賬戶 CRUD、故障轉移、金鑰、連線字串、網路
references/sql-resources.mdSQL 資料庫、容器、儲存過程、觸發器、UDF
references/throughput.md手動/自動縮放吞吐量、模式間遷移

相關 SDK

SDK用途安裝
`Microsoft.Azure.Cosmos`資料平面(文件 CRUD、查詢)`dotnet add package Microsoft.Azure.Cosmos`
`Azure.ResourceManager.CosmosDB`管理平面(本 SDK)`dotnet add package Azure.ResourceManager.CosmosDB`
在 GitHub 上查看
---
name: azure-resource-manager-cosmosdb-dotnet
description: Provision and manage Azure Cosmos DB accounts, databases, containers, throughput, and RBAC using the .NET Azure Resource Manager SDK.
license: MIT
---

# Azure.ResourceManager.CosmosDB (.NET)

Management plane SDK for provisioning and managing Azure Cosmos DB resources via Azure Resource Manager.

> **⚠️ Management vs Data Plane**
> - **This SDK (Azure.ResourceManager.CosmosDB)**: Create accounts, databases, containers, configure throughput, manage RBAC
> - **Data Plane SDK (Microsoft.Azure.Cosmos)**: CRUD operations on documents, queries, stored procedures execution

## Installation

```bash
dotnet add package Azure.ResourceManager.CosmosDB
dotnet add package Azure.Identity
```

**Current Versions**: Stable v1.4.0, Preview v1.4.0-beta.13

## Environment Variables

```bash
AZURE_SUBSCRIPTION_ID=<your-subscription-id> # Required: Azure subscription ID
AZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production
AZURE_TENANT_ID=<tenant-id> # For service principal auth (optional)
AZURE_CLIENT_ID=<client-id> # For service principal auth (optional)
AZURE_CLIENT_SECRET=<client-secret> # For service principal auth (optional)
```

## Authentication

```csharp
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.CosmosDB;

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
var armClient = new ArmClient(credential);

// Get subscription
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var subscription = armClient.GetSubscriptionResource(
    new ResourceIdentifier($"/subscriptions/{subscriptionId}"));
```

## Resource Hierarchy

```
ArmClient
└── SubscriptionResource
    └── ResourceGroupResource
        └── CosmosDBAccountResource
            ├── CosmosDBSqlDatabaseResource
            │   └── CosmosDBSqlContainerResource
            │       ├── CosmosDBSqlStoredProcedureResource
            │       ├── CosmosDBSqlTriggerResource
            │       └── CosmosDBSqlUserDefinedFunctionResource
            ├── CassandraKeyspaceResource
            ├── GremlinDatabaseResource
            ├── MongoDBDatabaseResource
            └── CosmosDBTableResource
```

## Core Workflow

### 1. Create Cosmos DB Account

```csharp
using Azure.ResourceManager.CosmosDB;
using Azure.ResourceManager.CosmosDB.Models;

// Get resource group
var resourceGroup = await subscription
    .GetResourceGroupAsync("my-resource-group");

// Define account
var accountData = new CosmosDBAccountCreateOrUpdateContent(
    location: AzureLocation.EastUS,
    locations: new[]
    {
        new CosmosDBAccountLocation
        {
            LocationName = AzureLocation.EastUS,
            FailoverPriority = 0,
            IsZoneRedundant = false
        }
    })
{
    Kind = CosmosDBAccountKind.GlobalDocumentDB,
    ConsistencyPolicy = new ConsistencyPolicy(DefaultConsistencyLevel.Session),
    EnableAutomaticFailover = true
};

// Create account (long-running operation)
var accountCollection = resourceGroup.Value.GetCosmosDBAccounts();
var operation = await accountCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-cosmos-account",
    accountData);

CosmosDBAccountResource account = operation.Value;
```

### 2. Create SQL Database

```csharp
var databaseData = new CosmosDBSqlDatabaseCreateOrUpdateContent(
    new CosmosDBSqlDatabaseResourceInfo("my-database"));

var databaseCollection = account.GetCosmosDBSqlDatabases();
var dbOperation = await databaseCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-database",
    databaseData);

CosmosDBSqlDatabaseResource database = dbOperation.Value;
```

### 3. Create SQL Container

```csharp
var containerData = new CosmosDBSqlContainerCreateOrUpdateContent(
    new CosmosDBSqlContainerResourceInfo("my-container")
    {
        PartitionKey = new CosmosDBContainerPartitionKey
        {
            Paths = { "/partitionKey" },
            Kind = CosmosDBPartitionKind.Hash
        },
        IndexingPolicy = new CosmosDBIndexingPolicy
        {
            Automatic = true,
            IndexingMode = CosmosDBIndexingMode.Consistent
        },
        DefaultTtl = 86400 // 24 hours
    });

var containerCollection = database.GetCosmosDBSqlContainers();
var containerOperation = await containerCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-container",
    containerData);

CosmosDBSqlContainerResource container = containerOperation.Value;
```

### 4. Configure Throughput

```csharp
// Manual throughput
var throughputData = new ThroughputSettingsUpdateData(
    new ThroughputSettingsResourceInfo
    {
        Throughput = 400
    });

// Autoscale throughput
var autoscaleData = new ThroughputSettingsUpdateData(
    new ThroughputSettingsResourceInfo
    {
        AutoscaleSettings = new AutoscaleSettingsResourceInfo
        {
            MaxThroughput = 4000
        }
    });

// Apply to database
await database.CreateOrUpdateCosmosDBSqlDatabaseThroughputAsync(
    WaitUntil.Completed,
    throughputData);
```

### 5. Get Connection Information

```csharp
// Get keys
var keys = await account.GetKeysAsync();
Console.WriteLine($"Primary Key: {keys.Value.PrimaryMasterKey}");

// Get connection strings
var connectionStrings = await account.GetConnectionStringsAsync();
foreach (var cs in connectionStrings.Value.ConnectionStrings)
{
    Console.WriteLine($"{cs.Description}: {cs.ConnectionString}");
}
```

## Key Types Reference

| Type | Purpose |
|------|---------|
| `ArmClient` | Entry point for all ARM operations |
| `CosmosDBAccountResource` | Represents a Cosmos DB account |
| `CosmosDBAccountCollection` | Collection for account CRUD |
| `CosmosDBSqlDatabaseResource` | SQL API database |
| `CosmosDBSqlContainerResource` | SQL API container |
| `CosmosDBAccountCreateOrUpdateContent` | Account creation payload |
| `CosmosDBSqlDatabaseCreateOrUpdateContent` | Database creation payload |
| `CosmosDBSqlContainerCreateOrUpdateContent` | Container creation payload |
| `ThroughputSettingsUpdateData` | Throughput configuration |

## Best Practices

1. **Use `WaitUntil.Completed`** for operations that must finish before proceeding
2. **Use `WaitUntil.Started`** when you want to poll manually or run operations in parallel
3. **Use `DefaultAzureCredential`** — never hardcode keys
4. **Handle `RequestFailedException`** for ARM API errors
5. **Use `CreateOrUpdateAsync`** for idempotent operations
6. **Navigate hierarchy** via `Get*` methods (e.g., `account.GetCosmosDBSqlDatabases()`)

## Error Handling

```csharp
using Azure;

try
{
    var operation = await accountCollection.CreateOrUpdateAsync(
        WaitUntil.Completed, accountName, accountData);
}
catch (RequestFailedException ex) when (ex.Status == 409)
{
    Console.WriteLine("Account already exists");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"ARM Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
```

## Reference Files

| File | When to Read |
|------|--------------|
| [references/account-management.md](references/account-management.md) | Account CRUD, failover, keys, connection strings, networking |
| [references/sql-resources.md](references/sql-resources.md) | SQL databases, containers, stored procedures, triggers, UDFs |
| [references/throughput.md](references/throughput.md) | Manual/autoscale throughput, migration between modes |

## Related SDKs

| SDK | Purpose | Install |
|-----|---------|---------|
| `Microsoft.Azure.Cosmos` | Data plane (document CRUD, queries) | `dotnet add package Microsoft.Azure.Cosmos` |
| `Azure.ResourceManager.CosmosDB` | Management plane (this SDK) | `dotnet add package Azure.ResourceManager.CosmosDB` |

所有檔案

0 個檔案

安裝 azure-resource-manager-cosmosdb-dotnet

將技能檔案下載並解壓至你的 .claude/skills/ 目錄。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-resource-manager-cosmosdb-dotnet # Copy SKILL.md to your .claude/skills/ directory

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/ 目錄。Claude 將自動檢測並使用該技能。
儲存庫 microsoft/skills

相關技能

Verification &amp; Quality Assurance
更新時間 2026-06-29
klingai-upgrade-migration
更新時間 2026-07-03
base44-cli
更新時間 2026-06-29
Railway CLI Management
更新時間 2026-07-02
OR