Mulai Cepat: Membuat Azure Cosmos DB dan kontainer menggunakan Bicep

BERLAKU UNTUK: NoSQL

Azure Cosmos DB adalah database NoSQL cepat Microsoft dengan API terbuka untuk skala apa pun. Anda dapat menggunakan Azure Cosmos DB untuk membuat dan mengueri database kunci/nilai, dokumen, dan grafik dengan cepat. Tanpa kartu kredit atau langganan Azure, Anda dapat menyiapkan Coba akun Azure Cosmos DB gratis. Mulai cepat ini berfokus pada proses penyebaran file Bicep untuk membuat database Azure Cosmos DB dan kontainer dalam database tersebut. Anda nantinya dapat menyimpan data dalam kontainer ini.

Bicep adalah bahasa pemrogram khusus domain (DSL) yang menggunakan sintaks deklaratif untuk menyebarkan sumber daya Azure. Bicep menyediakan sintaks ringkas, keamanan jenis yang andal, dan dukungan untuk penggunaan kembali kode. Bicep menawarkan pengalaman penulisan terbaik untuk solusi infrastructure-as-code di Azure.

Prasyarat

Langganan Azure atau akun uji coba Azure Cosmos DB gratis.

Tinjau file Bicep

File Bicep yang digunakan dalam mulai cepat berasal dari Templat Mulai Cepat 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

Tiga sumber daya Azure yang ditentukan dalam file Bicep:

Menerapkan file Bicep

  1. Simpan file Bicep sebagai main.bicep ke penyimpanan lokal komputer Anda.

  2. Sebarkan file Bicep menggunakan Azure CLI atau Azure PowerShell.

    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>
    

    Catatan

    Ganti <wilayah> utama dengan wilayah replika utama untuk akun Azure Cosmos DB, seperti WestUS. Ganti <wilayah> sekunder dengan wilayah replika sekunder untuk akun Azure Cosmos DB, seperti EastUS.

    Setelah penyebaran selesai, Anda akan melihat pesan yang menunjukkan penyebaran berhasil.

Memvalidasi penyebaran

Gunakan portal Microsoft Azure, Azure CLI, atau Azure PowerShell untuk mencantumkan sumber daya yang disebarkan di grup sumber daya.

az resource list --resource-group exampleRG

Membersihkan sumber daya

Jika Anda berencana untuk terus bekerja dengan mulai cepat dan tutorial berikutnya, biarkan sumber daya ini tetap di tempatnya. Saat tidak lagi diperlukan, gunakan portal Azure, Azure CLI, atau Azure PowerShell untuk menghapus grup sumber daya dan sumber dayanya.

az group delete --name exampleRG

Langkah berikutnya

Dalam mulai cepat ini, Anda membuat akun Azure Cosmos DB, database, dan kontainer dengan menggunakan file Bicep dan memvalidasi penyebaran. Untuk mempelajari lebih lanjut tentang Azure Cosmos DB dan Bicep, lanjutkan membaca artikel berikut.