다음을 통해 공유


빠른 시작: Bicep을 사용하여 Azure Cosmos DB 및 컨테이너 만들기

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 체험 계정.

  • Azure 계정이 없는 경우 시작하기 전에 체험 계정을 만듭니다.

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 파일에는 세 개의 Azure 리소스가 정의되어 있습니다.

다음 표에서는 이 Bicep 파일에서 가장 일반적으로 검토하거나 사용자 지정할 주요 매개 변수 및 출력을 강조 표시합니다.

매개 변수 또는 출력 기본값 또는 예제 값 범위 및 참고 사항
accountName 생성된 고유 이름 글로벌 Azure Cosmos DB 계정 이름입니다.
databaseName myDatabase SQL API 데이터베이스 이름입니다.
containerName myContainer SQL API 컨테이너 이름입니다.
throughput 400 프로비전된 처리량(RU/s, 초당 요청 단위)입니다.
partitionKeyPath /myPartitionKey 논리 파티션 키 경로입니다.
defaultTtl -1 초 단위로 설정된 수명입니다. -1는 항목이 만료되지 않음을 의미합니다.
API 버전 2023-11-15 사용된 SQL API 버전; 동작은 최신 버전에서 변경 될 수 있습니다.

중요합니다

Azure Resource Manager 공급자 Microsoft.DocumentDB/databaseAccounts는 수년 동안 같은 이름을 사용해 왔습니다. 이를 통해 서비스 및 하위 서비스의 이름이 바뀌더라도 몇 년 전에 작성된 템플릿이 동일한 공급자와 계속 호환되도록 할 수 있습니다.

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>
    

    비고

    주 지역을< westus와 같은 Azure Cosmos DB 계정의 주 복제본 지역으로 바꿉>니다. secondary-region을 eastus와 같은 Azure Cosmos DB 계정의 보조 복제 지역으로 바꿉니다.

    지역 값은 Azure 지역 이름 형식(예: eastus, westus2)을 사용합니다.

    배포가 완료되면 배포가 성공했음을 나타내는 메시지가 표시됩니다.

다음 코드 조각은 예제 매개 변수 값과 배포를 확인하는 방법을 보여 있습니다.

az deployment group create \
  --resource-group exampleRG \
  --template-file main.bicep \
  --parameters primaryRegion=eastus secondaryRegion=westus
az cosmosdb sql database list --account-name <account-name> --resource-group exampleRG

예상 출력에는 지정한 데이터베이스 이름(예: "name": "myDatabase".)이 포함됩니다.

배포 유효성 검사

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에 대해 자세히 알아보려면 아래 문서로 계속 진행하세요.