Generated banner for Azure Resource Manager Cosmosdb Dotnet
Generated logo for Azure Resource Manager Cosmosdb Dotnet

Azure Resource Manager Cosmosdb Dotnet

MicrosoftOfficialCreated by Microsoft

  • Skill
  • Tool integration
  • Cloud and DevOps
  • MIT
  • No issues found

From the author

Azure Resource Manager SDK for Cosmos DB in .NET. Use for MANAGEMENT PLANE operations: creating/managing Cosmos DB accounts, databases, containers, throughput settings, and RBAC via Azure Resource Manager. NOT for data plane operations (CRUD on documents) - use Microsoft.Azure.Cosmos for that. Triggers: "Cosmos DB account", "create Cosmos account", "manage Cosmos resources", "ARM Cosmos", "CosmosDBAccountResource", "provision Cosmos DB".
— the description by Microsoft

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The Azure.ResourceManager.CosmosDB SDK provides a .NET interface for management plane operations on Azure Cosmos DB. It allows developers to automate the provisioning and configuration of Cosmos DB accounts, databases, and containers, as well as manage throughput settings and RBAC configurations. This SDK is strictly for infrastructure management and should not be used for data plane operations like document CRUD or query execution.

What it does

  • Provision and configure Cosmos DB accounts with specific consistency and failover policies.
  • Create and manage SQL API databases and containers.
  • Configure manual or autoscale throughput settings for databases and containers.
  • Retrieve account keys and connection strings for application integration.
  • Manage indexing policies, partition keys, and hierarchical partitioning.
  • Perform lifecycle operations including updating and deleting Cosmos DB resources.

When to use it

  • When automating infrastructure-as-code deployments for Cosmos DB.
  • When you need to programmatically scale throughput or modify container settings.
  • When managing multiple Cosmos DB accounts across different resource groups or subscriptions.
  • When setting up environment-specific database configurations in a CI/CD pipeline.

Advantages

  • Native .NET integration for seamless infrastructure management.
  • Strongly typed models for complex resource configurations.
  • Supports long-running operations with built-in wait mechanisms.
  • Enables programmatic enforcement of infrastructure standards and policies.

Usage examples

“How do I create a new Cosmos DB account using the .NET SDK?”
The agent provides a code snippet using CosmosDBAccountCreateOrUpdateContent to define the account settings and calls CreateOrUpdateAsync on the account collection.
“Show me how to update throughput for an existing SQL container.”
The agent demonstrates using ThroughputSettingsUpdateData to set either manual or autoscale throughput and applying it via the container resource.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/microsoft/azure-resource-manager-cosmosdb-dotnet/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip azure-resource-manager-cosmosdb-dotnet.zip -d .agents/skills

Documentation by Microsoft

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

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

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

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
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
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
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
// 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
// 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

TypePurpose
ArmClientEntry point for all ARM operations
CosmosDBAccountResourceRepresents a Cosmos DB account
CosmosDBAccountCollectionCollection for account CRUD
CosmosDBSqlDatabaseResourceSQL API database
CosmosDBSqlContainerResourceSQL API container
CosmosDBAccountCreateOrUpdateContentAccount creation payload
CosmosDBSqlDatabaseCreateOrUpdateContentDatabase creation payload
CosmosDBSqlContainerCreateOrUpdateContentContainer creation payload
ThroughputSettingsUpdateDataThroughput 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

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

FileWhen to Read
references/account-management.mdAccount CRUD, failover, keys, connection strings, networking
references/sql-resources.mdSQL databases, containers, stored procedures, triggers, UDFs
references/throughput.mdManual/autoscale throughput, migration between modes
SDKPurposeInstall
Microsoft.Azure.CosmosData plane (document CRUD, queries)dotnet add package Microsoft.Azure.Cosmos
Azure.ResourceManager.CosmosDBManagement plane (this SDK)dotnet add package Azure.ResourceManager.CosmosDB

Files

references/account-management.md

Account Management

Detailed patterns for managing Cosmos DB accounts via Azure Resource Manager.

Create Account with Full Configuration

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

var accountData = new CosmosDBAccountCreateOrUpdateContent(
    location: AzureLocation.EastUS,
    locations: new[]
    {
        new CosmosDBAccountLocation
        {
            LocationName = AzureLocation.EastUS,
            FailoverPriority = 0,
            IsZoneRedundant = true
        },
        new CosmosDBAccountLocation
        {
            LocationName = AzureLocation.WestUS,
            FailoverPriority = 1,
            IsZoneRedundant = false
        }
    })
{
    Kind = CosmosDBAccountKind.GlobalDocumentDB,
    
    // Consistency
    ConsistencyPolicy = new ConsistencyPolicy(DefaultConsistencyLevel.BoundedStaleness)
    {
        MaxStalenessPrefix = 100000,
        MaxIntervalInSeconds = 300
    },
    
    // High availability
    EnableAutomaticFailover = true,
    EnableMultipleWriteLocations = false,
    
    // Backup
    BackupPolicy = new ContinuousModeBackupPolicy
    {
        ContinuousModeTier = ContinuousModeTier.Continuous7Days
    },
    
    // Networking
    PublicNetworkAccess = CosmosDBPublicNetworkAccess.Enabled,
    IsVirtualNetworkFilterEnabled = false,
    
    // Features
    EnableFreeTier = false,
    EnableAnalyticalStorage = true,
    AnalyticalStorageSchemaType = AnalyticalStorageSchemaType.WellDefined,
    
    // Tags
    Tags =
    {
        ["Environment"] = "Production",
        ["CostCenter"] = "Engineering"
    }
};

var operation = await accountCollection.CreateOrUpdateAsync(
    WaitUntil.Completed,
    "my-cosmos-account",
    accountData);

Get Existing Account

// By name from resource group
var account = await resourceGroup.GetCosmosDBAccountAsync("my-cosmos-account");

// By resource ID
var accountId = CosmosDBAccountResource.CreateResourceIdentifier(
    subscriptionId, resourceGroupName, accountName);
var account = armClient.GetCosmosDBAccountResource(accountId);
await account.GetAsync(); // Fetch latest data

Update Account

// Get current account
var account = await resourceGroup.GetCosmosDBAccountAsync("my-cosmos-account");

// Create patch data
var patchData = new CosmosDBAccountPatch
{
    EnableAutomaticFailover = true,
    ConsistencyPolicy = new ConsistencyPolicy(DefaultConsistencyLevel.Session)
};
patchData.Tags.Add("UpdatedBy", "Automation");

// Apply update
var operation = await account.Value.UpdateAsync(WaitUntil.Completed, patchData);

Delete Account

var account = await resourceGroup.GetCosmosDBAccountAsync("my-cosmos-account");
await account.Value.DeleteAsync(WaitUntil.Completed);

List Accounts

// In resource group
await foreach (var account in resourceGroup.GetCosmosDBAccounts())
{
    Console.WriteLine($"Account: {account.Data.Name}");
    Console.WriteLine($"  Location: {account.Data.Location}");
    Console.WriteLine($"  Kind: {account.Data.Kind}");
}

// In subscription
await foreach (var account in subscription.GetCosmosDBAccountsAsync())
{
    Console.WriteLine($"{account.Data.Name} in {account.Data.ResourceGroupName}");
}

Get Keys and Connection Strings

// Get keys
var keys = await account.GetKeysAsync();
Console.WriteLine($"Primary Key: {keys.Value.PrimaryMasterKey}");
Console.WriteLine($"Secondary Key: {keys.Value.SecondaryMasterKey}");
Console.WriteLine($"Primary Read-Only: {keys.Value.PrimaryReadonlyMasterKey}");
Console.WriteLine($"Secondary Read-Only: {keys.Value.SecondaryReadonlyMasterKey}");

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

// Regenerate key
await account.RegenerateKeyAsync(
    WaitUntil.Completed,
    new CosmosDBAccountRegenerateKeyContent(CosmosDBAccountKeyKind.Primary));

Failover Operations

// Manual failover (for testing)
var failoverContent = new CosmosDBFailoverPolicies(new[]
{
    new CosmosDBFailoverPolicy
    {
        LocationName = AzureLocation.WestUS,
        FailoverPriority = 0
    },
    new CosmosDBFailoverPolicy
    {
        LocationName = AzureLocation.EastUS,
        FailoverPriority = 1
    }
});

await account.FailoverPriorityChangeAsync(WaitUntil.Completed, failoverContent);

Network Configuration

Private Endpoint
// Note: Private endpoints are typically created via Azure.ResourceManager.Network
// The Cosmos account needs to be configured to accept private endpoint connections

var accountData = new CosmosDBAccountCreateOrUpdateContent(location, locations)
{
    PublicNetworkAccess = CosmosDBPublicNetworkAccess.Disabled,
    IsVirtualNetworkFilterEnabled = true
};
IP Firewall Rules
var accountData = new CosmosDBAccountCreateOrUpdateContent(location, locations)
{
    IPRules =
    {
        new CosmosDBIPAddressOrRange { IPAddressOrRange = "104.42.195.92" },
        new CosmosDBIPAddressOrRange { IPAddressOrRange = "40.76.54.131" },
        new CosmosDBIPAddressOrRange { IPAddressOrRange = "52.176.6.30/32" }
    }
};
Virtual Network Rules
var accountData = new CosmosDBAccountCreateOrUpdateContent(location, locations)
{
    IsVirtualNetworkFilterEnabled = true,
    VirtualNetworkRules =
    {
        new CosmosDBVirtualNetworkRule
        {
            Id = new ResourceIdentifier(
                "/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Network/virtualNetworks/{vnet}/subnets/{subnet}"),
            IgnoreMissingVnetServiceEndpoint = false
        }
    }
};

Consistency Levels

LevelDescriptionUse Case
StrongLinearizable readsFinancial transactions
BoundedStalenessReads lag by K versions or T timeGaming leaderboards
SessionRead your own writesUser sessions (default)
ConsistentPrefixReads never see out-of-order writesSocial feeds
EventualNo ordering guaranteeAnalytics, non-critical reads
// Bounded Staleness example
ConsistencyPolicy = new ConsistencyPolicy(DefaultConsistencyLevel.BoundedStaleness)
{
    MaxStalenessPrefix = 100000,  // Max versions behind
    MaxIntervalInSeconds = 300    // Max time behind (5 min)
}

Backup Policies

Periodic Backup
BackupPolicy = new PeriodicModeBackupPolicy
{
    PeriodicModeProperties = new PeriodicModeProperties
    {
        BackupIntervalInMinutes = 240,  // 4 hours
        BackupRetentionIntervalInHours = 720,  // 30 days
        BackupStorageRedundancy = BackupStorageRedundancy.Geo
    }
}
Continuous Backup
BackupPolicy = new ContinuousModeBackupPolicy
{
    ContinuousModeTier = ContinuousModeTier.Continuous30Days
}

Account Kinds

KindAPIDescription
GlobalDocumentDBSQL (Core)Default, most common
MongoDBMongoDBMongoDB wire protocol
ParseSQLParse Server compatibility
// MongoDB account
var accountData = new CosmosDBAccountCreateOrUpdateContent(location, locations)
{
    Kind = CosmosDBAccountKind.MongoDB,
    ApiServerVersion = CosmosDBServerVersion.V4_2
};

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Microsoft
Publisher
Microsoft (Official)
Source
microsoft/skills · .github/plugins/azure-sdk-dotnet/skills/azure-resource-manager-cosmosdb-dotnet · commit 0696600
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Microsoft.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download azure-resource-manager-cosmosdb-dotnet.zip