クイックスタート: Bicep を使用して Azure Cosmos DB とコンテナーを作成する

適用対象: NoSQL

Azure Cosmos DB は、あらゆる規模に対応する、オープン API を備えた Microsoft の高速 NoSQL データベースです。 Azure Cosmos DB を使用すると、キーと値のデータベース、ドキュメント データベース、グラフ データベースをすばやく作成し、クエリを実行できます。 クレジット カードまたは Azure サブスクリプションがない場合は、無料の Azure Cosmos DB 試用版アカウントをセットアップできます。 このクイックスタートでは、Bicep ファイルをデプロイして Azure Cosmos DB データベースを作成し、そのデータベース内にコンテナーを作成するプロセスについて説明します。 その後、そのコンテナーにデータを格納することができます。

Bicep は、宣言型の構文を使用して Azure リソースをデプロイするドメイン固有言語 (DSL) です。 簡潔な構文、信頼性の高いタイプ セーフ、およびコードの再利用のサポートが提供されます。 Bicep により、Azure のコード ソリューションとしてのインフラストラクチャに最適な作成エクスペリエンスが実現します。

前提条件

Azure サブスクリプションまたは Azure Cosmos DB の無料試用版アカウント。

Bicep ファイルを確認する

このクイックスタートで使用される Bicep ファイルは、Azure クイックスタート テンプレートからのものです。

@description('Azure Cosmos DB account name, max length 44 characters')
param accountName string = 'sql-${uniqueString(resourceGroup().id)}'

@description('Location for the Azure Cosmos DB account.')
param location string = resourceGroup().location

@description('The primary region for the Azure Cosmos DB account.')
param primaryRegion string

@description('The secondary region for the Azure Cosmos DB account.')
param secondaryRegion string

@allowed([
  'Eventual'
  'ConsistentPrefix'
  'Session'
  'BoundedStaleness'
  'Strong'
])
@description('The default consistency level of the Cosmos DB account.')
param defaultConsistencyLevel string = 'Session'

@minValue(10)
@maxValue(2147483647)
@description('Max stale requests. Required for BoundedStaleness. Valid ranges, Single Region: 10 to 2147483647. Multi Region: 100000 to 2147483647.')
param maxStalenessPrefix int = 100000

@minValue(5)
@maxValue(86400)
@description('Max lag time (minutes). Required for BoundedStaleness. Valid ranges, Single Region: 5 to 84600. Multi Region: 300 to 86400.')
param maxIntervalInSeconds int = 300

@allowed([
  true
  false
])
@description('Enable system managed failover for regions')
param systemManagedFailover bool = true

@description('The name for the database')
param databaseName string = 'myDatabase'

@description('The name for the container')
param containerName string = 'myContainer'

@minValue(400)
@maxValue(1000000)
@description('The throughput for the container')
param throughput int = 400

var consistencyPolicy = {
  Eventual: {
    defaultConsistencyLevel: 'Eventual'
  }
  ConsistentPrefix: {
    defaultConsistencyLevel: 'ConsistentPrefix'
  }
  Session: {
    defaultConsistencyLevel: 'Session'
  }
  BoundedStaleness: {
    defaultConsistencyLevel: 'BoundedStaleness'
    maxStalenessPrefix: maxStalenessPrefix
    maxIntervalInSeconds: maxIntervalInSeconds
  }
  Strong: {
    defaultConsistencyLevel: 'Strong'
  }
}
var locations = [
  {
    locationName: primaryRegion
    failoverPriority: 0
    isZoneRedundant: false
  }
  {
    locationName: secondaryRegion
    failoverPriority: 1
    isZoneRedundant: false
  }
]

resource account 'Microsoft.DocumentDB/databaseAccounts@2024-02-15-preview' = {
  name: toLower(accountName)
  location: location
  kind: 'GlobalDocumentDB'
  properties: {
    consistencyPolicy: consistencyPolicy[defaultConsistencyLevel]
    locations: locations
    databaseAccountOfferType: 'Standard'
    enableAutomaticFailover: systemManagedFailover
    disableKeyBasedMetadataWriteAccess: true
  }
}

resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2024-02-15-preview' = {
  parent: account
  name: databaseName
  properties: {
    resource: {
      id: databaseName
    }
  }
}

resource container 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers@2024-02-15-preview' = {
  parent: database
  name: containerName
  properties: {
    resource: {
      id: containerName
      partitionKey: {
        paths: [
          '/myPartitionKey'
        ]
        kind: 'Hash'
      }
      indexingPolicy: {
        indexingMode: 'consistent'
        includedPaths: [
          {
            path: '/*'
          }
        ]
        excludedPaths: [
          {
            path: '/myPathToNotIndex/*'
          }
          {
            path: '/_etag/?'
          }
        ]
        compositeIndexes: [
          [
            {
              path: '/name'
              order: 'ascending'
            }
            {
              path: '/age'
              order: 'descending'
            }
          ]
        ]
        spatialIndexes: [
          {
            path: '/location/*'
            types: [
              'Point'
              'Polygon'
              'MultiPolygon'
              'LineString'
            ]
          }
        ]
      }
      defaultTtl: 86400
      uniqueKeyPolicy: {
        uniqueKeys: [
          {
            paths: [
              '/phoneNumber'
            ]
          }
        ]
      }
    }
    options: {
      throughput: throughput
    }
  }
}

output location string = location
output name string = database.name
output resourceGroupName string = resourceGroup().name
output resourceId string = database.id

Bicep ファイルには、次の 3 つの Azure リソースが定義されています。

Bicep ファイルをデプロイする

  1. Bicep ファイルを main.bicep としてローカル コンピューターに保存します。

  2. Azure CLI または Azure PowerShell のどちらかを使用して Bicep ファイルをデプロイします。

    az group create --name exampleRG --location eastus
    az deployment group create --resource-group exampleRG --template-file main.bicep --parameters primaryRegion=<primary-region> secondaryRegion=<secondary-region>
    

    注意

    <primary-region> を、Azure Cosmos DB アカウントのプライマリ レプリカ リージョン (WestUS など) に置き換えます。 <secondary-region> を、Azure Cosmos DB アカウントのセカンダリ レプリカ リージョン (EastUS など) に置き換えます。

    デプロイが完了すると、デプロイが成功したことを示すメッセージが表示されます。

デプロイの検証

Azure portal、Azure CLI、または Azure PowerShell を使用して、リソースグループ内のデプロイ済みリソースをリスト表示します。

az resource list --resource-group exampleRG

リソースをクリーンアップする

後続のクイック スタートおよびチュートリアルを引き続き実行する場合は、これらのリソースをそのまま残しておくことができます。 不要になったら、Azure portal、Azure CLI、または Azure PowerShell を使用して、リソース グループとそのリソースを削除します。

az group delete --name exampleRG

次のステップ

このクイックスタートでは、Bicep ファイルを使って Azure Cosmos DB アカウント、データベース、コンテナーを作成し、デプロイを検証しました。 Azure Cosmos DB と Bicep について詳しくは、引き続き以下の記事をご覧ください。