Conditions

Conditions类型于编程语言中的if/else逻辑,


下面的模板中有一个EnvType参数,当CloudFormation检测到它的值为prod时,额外增加一块磁盘,当标签为test时,仅挂一块磁盘。

EnvType = prod时,CreateProdResources的值为true

NewVolumeMountPoint资源和CreateProdResources条件做了关联,仅当满足条件时才创建这两个资源:

AWSTemplateFormatVersion: "2010-09-09"
Mappings: 
  RegionMap: 
    us-east-1: 
      AMI: "ami-0ff8a91507f77f867"
      TestAz: "us-east-1a"
    us-west-1: 
      AMI: "ami-0bdb828fd58c52235"
      TestAz: "us-west-1a"
    us-west-2: 
      AMI: "ami-a0cfeed8"
      TestAz: "us-west-2a"
Parameters: 
  EnvType: 
    Description: Environment type.
    Default: test
    Type: String
    AllowedValues: 
      - prod
      - test
    ConstraintDescription: must specify prod or test.
Conditions: 
  CreateProdResources: !Equals [ !Ref EnvType, prod ]
Resources: 
  EC2Instance: 
    Type: "AWS::EC2::Instance"
    Properties: 
      ImageId: !FindInMap [RegionMap, !Ref "AWS::Region", AMI]
  MountPoint: 
    Type: "AWS::EC2::VolumeAttachment"
    Condition: CreateProdResources
    Properties: 
      InstanceId: 
        !Ref EC2Instance
      VolumeId: 
        !Ref NewVolume
      Device: /dev/sdh
  NewVolume: 
    Type: "AWS::EC2::Volume"
    Condition: CreateProdResources
    Properties: 
      Size: 100
      AvailabilityZone: 
        !GetAtt EC2Instance.AvailabilityZone
Outputs: 
  VolumeId: 
    Condition: CreateProdResources
    Value: 
      !Ref NewVolume