了解 Bicep 檔案結構和語法

已完成

Azure Bicep 有自己的語法,不過該語法很容易理解及遵循。 我們不會深入探討語法和結構,但讓我們使用範例來檢閱主要概念。

範例 Bicep .bicep 檔案

@minLength(3)
@maxLength(11)
param storagePrefix string

param storageSKU string = 'Standard_LRS'
param location string = resourceGroup().location

var uniqueStorageName = '${storagePrefix}${uniqueString(resourceGroup().id)}'

resource stg 'Microsoft.Storage/storageAccounts@2019-04-01' = {
    name: uniqueStorageName
    location: location
    sku: {
        name: storageSKU
    }
    kind: 'StorageV2'
    properties: {
        supportsHttpsTrafficOnly: true
    }

    resource service 'fileServices' = {
        name: 'default'

        resource share 'shares' = {
            name: 'exampleshare'
        }
    }
}

module webModule './webApp.bicep' = {
    name: 'webDeploy'
    params: {
        skuName: 'S1'
        location: location
    }
}

output storageEndpoint object = stg.properties.primaryEndpoints

範圍

根據預設,所有範本的目標範圍都會設定為 resourceGroup,不過,您可以透過明確設定來加以自訂。 其他的允許值包括 subscriptionmanagementGrouptenant

參數

您已經在上一個單元中使用參數。 其可讓您提供名稱、位置、前置詞等潛在值,來自訂執行階段的範本部署。

參數也會有編輯器可以驗證的類型,也可以有預設值,使其在部署期間具有選擇性。 此外,您可以看到其可以有驗證規則,以透過從撰寫開始便防止任何無效值,來使部署更加可靠。 如需詳細資訊,請參閱 Bicep 中的參數

變數

變數與參數類似,其扮演使範本更加強固且容易讀取的角色。 任何複雜的運算式都可以儲存在變數中,並在整個範本中使用。 當您定義變數時,系統會從值中推斷類型。

在上述範例中,是使用 uniqueStorageName 來簡化資源定義。 如需詳細資訊,請參閱 Bicep 中的變數

資源

當您需要在範本中宣告資源時,會使用 resource 關鍵字。 資源宣告針對資源具有符號名稱,可用來於稍後參考該資源,以定義子資源或將其屬性用於隱含相依性 (例如父代-子系關聯性)。

所有資源都有一些共通的屬性,例如 locationnameproperties。 有一些資源特定的屬性可用來自訂資源定價層,例如 SKU 等。

您可以透過參考父代,來在資源內部或外部定義子資源。 在上述範例中,檔案共用是在儲存體帳戶資源內定義。 如果意圖是要在資源外部加以定義,您必須變更範本:

resource storage 'Microsoft.Storage/storageAccounts@2021-02-01' = {
    name: 'examplestorage'
    location: resourceGroup().location
    kind: 'StorageV2'
    sku: {
        name: 'Standard_LRS'
    }
}

resource service 'Microsoft.Storage/storageAccounts/fileServices@2021-02-01' = {
    name: 'default'
    parent: storage
}

resource share 'Microsoft.Storage/storageAccounts/fileServices/shares@2021-02-01' = {
    name: 'exampleshare'
    parent: service
}

如需詳細資訊,請參閱 Bicep 中的資源宣告

模組

如果您想要真正可重複使用的範本,就一定得用到模組。 模組可讓您在其他 Bicep 檔案中重複使用 Bicep 檔案。 在模組中,您會定義部署所需的項目及任何所需的參數;當您在另一個檔案中加以重複使用時,您只需參考該檔案並提供參數。 其餘部分都會由 Azure Bicep 處理。

在上述範例中,您是使用假設正在部署 App Service 的模組。 如需詳細資訊,請參閱在 Bicep 中使用模組

輸出

您可以使用輸出來將值從部署中傳遞到外部世界,無論其是在 CI/CD 管線中進行,還是在本機終端或 Cloud Shell 中進行。 那可讓您在部署完成後存取如儲存體端點或應用程式 URL 的值。

您只需要 output 關鍵字和您想要存取的屬性:

output storageEndpoint endpoints = stg.properties.primaryEndpoints

如需詳細資訊,請參閱 Bicep 中的輸出

其他功能

Bicep 檔案內還有許多其他可用的功能,例如迴圈、條件式部署、多行字串、參考現有雲端資源等。 事實上,ARM 範本內的任何有效函式,在 Bicep 檔案內也都是有效的。

下一步

在下一個單元中,您將了解如何在 Azure Pipelines 中使用 Bicep。