Conditions 區段中的 Fn::ForEach 範例 - AWS CloudFormation

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

Conditions 區段中的 Fn::ForEach 範例

這些範例會示範如何使用 CloudFormation 範本Conditions語法 區段中的 Fn::ForEach 內部函數。

重要

Conditions 必須是列出的第二個屬性,或更高版本。如果 ConditionsFn::ForEach 的範本片段參數中列出的第一個屬性,則堆疊建立將會失敗。

Resources: 'Fn::ForEach::Topics': - LogicalId - !Ref TopicList - '${LogicalId}': Condition: !Sub 'TopicCondition${LogicalId}' Type: AWS::SNS::Topic Properties: TopicName: !Sub 'My${LogicalId}'

Conditions 必須以第二個金鑰 (或更高版本) 來新增,才能順利建立堆疊:

Resources: 'Fn::ForEach::Topics': - LogicalId - !Ref TopicList - '${LogicalId}': Type: AWS::SNS::Topic Condition: !Sub 'TopicCondition${LogicalId}' Properties: TopicName: !Sub 'My${LogicalId}'

複寫單一條件

此範例會使用 CloudFormation 範本Conditions語法 區段中的 Fn::ForEach 內部函數,來複寫具有不同屬性的多個類似條件。

JSON

{ "AWSTemplateFormatVersion": "2010-09-09", "Transform": "AWS::LanguageExtensions", "Parameters": { "ParamA": { "Type": "String", "AllowedValues": [ "true", "false" ] }, "ParamB": { "Type": "String", "AllowedValues": [ "true", "false" ] }, "ParamC": { "Type": "String", "AllowedValues": [ "true", "false" ] }, "ParamD": { "Type": "String", "AllowedValues": [ "true", "false" ] } }, "Conditions": { "Fn::ForEach::CheckTrue": [ "Identifier", ["A", "B", "C", "D"], { "IsParam${Identifier}Enabled": { "Fn::Equals": [ {"Ref": {"Fn::Sub": "Param${Identifier}"}}, "true" ] } } ] }, "Resources": { "WaitConditionHandle": { "Type": "AWS::CloudFormation::WaitConditionHandle" } } }

YAML

AWSTemplateFormatVersion: 2010-09-09 Transform: 'AWS::LanguageExtensions' Parameters: ParamA: Type: String AllowedValues: - 'true' - 'false' ParamB: Type: String AllowedValues: - 'true' - 'false' ParamC: Type: String AllowedValues: - 'true' - 'false' ParamD: Type: String AllowedValues: - 'true' - 'false' Conditions: 'Fn::ForEach::CheckTrue': - Identifier - [A, B, C, D] - 'IsParam${Identifier}Enabled': !Equals - !Ref 'Fn::Sub': 'Param${Identifier}' - 'true' Resources: WaitConditionHandle: Type: 'AWS::CloudFormation::WaitConditionHandle'

轉換後範本將等同於下列範本:

AWSTemplateFormatVersion: 2010-09-09 Parameters: ParamA: Type: String AllowedValues: - 'true' - 'false' ParamB: Type: String AllowedValues: - 'true' - 'false' ParamC: Type: String AllowedValues: - 'true' - 'false' ParamD: Type: String AllowedValues: - 'true' - 'false' Conditions: IsParamAEnabled: !Equals - !Ref ParamA - 'true' IsParamBEnabled: !Equals - !Ref ParamB - 'true' IsParamCEnabled: !Equals - !Ref ParamC - 'true' IsParamDEnabled: !Equals - !Ref ParamD - 'true' Resources: WaitConditionHandle: Type: 'AWS::CloudFormation::WaitConditionHandle'