規則(Rules)用于檢驗在創建或更新資源棧時傳遞給模板的參數值是否符合預期。

語法

您可以在ROS模板中使用關鍵字Rules來聲明模板規則。

您可以在ROS中定義多個規則,每個規則由規則名稱和規則描述組成。如果聲明多個規則項,規則項之間用半角逗號(,)分隔。

Rules:
  規則1名稱:
    RuleCondition: 規則條件內容
    Assertions:
      - Assert: 斷言內容
        AssertDescription: 斷言描述
      - Assert: 斷言內容
        AssertDescription: 斷言描述
  規則2名稱:
    Assertions:
      - Assert: 斷言內容      
  • RuleCondition(可選):定義RuleCondition規則條件。如果未定義規則條件,則斷言始終生效。
  • Assertions:定義Assertions斷言列表。由多個AssertAssertDescription組成,用于描述斷言內容。
    說明 Assertions斷言列表最多由100個AssertAssertDescription組成。
  • Assert:定義Assert斷言內容。
  • AssertDescription(可選):定義AssertDescription斷言描述,當斷言結果為false時給出用戶提示。

每個規則中最多只能定義一個RuleCondition,如果未定義RuleCondition或定義結果為true時,Assertions屬性生效,反之則不生效。

如果Assert返回結果為true時,表示規則校驗通過,您可以繼續完成資源棧的預覽、創建和更新操作。

示例

當您在生產環境創建ECS實例時,ECS實例的公網帶寬必須為0。在預發環境創建ECS實例時,ECS實例的計費方式必須是按量付費。
ROSTemplateFormatVersion: '2015-09-01'
Rules:
  PublicNet:
    RuleCondition:
      Fn::Equals:
        - Ref: Environment
        - prod
    Assertions:
      - Assert:
          Fn::Equals:
            - Ref: InternetMaxBandwidthOut
            - 0
        AssertDescription: ECS instance should be intranet when the environment is prod.
  ChargeType:
    RuleCondition:
      Fn::Equals:
        - Ref: Environment
        - pre
    Assertions:
      - Assert:
          Fn::Equals:
            - Ref: InstanceChargeType
            - PayAsYouGo
        AssertDescription: ECS instance should be postpaid when the environment is pre.
Parameters:
  Environment:
    Type: String
    AllowedValues:
      - prod
      - pre
  InternetMaxBandwidthOut:
    Type: Number
    MaxValue: 10
    MinValue: 0
  InstanceChargeType:
    Type: String
    AllowedValues:
      - PayAsYouGo
      - Subscription
Resources:
  ECS:
    Type: ALIYUN::ECS::InstanceGroup
    Properties:
      InternetMaxBandwidthOut:
        Ref: InternetMaxBandwidthOut
      InstanceChargeType:
        Ref: InstanceChargeType
      #省略其他屬性: null