Mappings - 映射

这一部分将介绍 Mappings . MappingsCloudFormation的顶级对象(top-level object)。 它用于定义映射(键和值),然后可以在模板中引用它们。

下面是一个Mappings示例。AnExampleMap包含三个顶级键TopLevelKey01TopLevelKey02TopLevelKey03,每个顶级键包含一个或多个键值对:

Mappings:
  AnExampleMap:
    TopLevelKey01:
      Key01: Value01
      Key02: Value02
    TopLevelKey02:
      AnotherKey: AnExampleValue
    TopLevelKey03:
      AFinalKey: ADifferentValue

Mappings实验

将以下代码保存为05-lab04-Mappings.yaml:

AWSTemplateFormatVersion: '2010-09-09'

Description: CFN 101 Workshop - Lab 04 Mapping.

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: 'Amazon EC2 Configuration'
        Parameters:
          - AmiID

    ParameterLabels:
      AmiID:
        default: 'Amazon Machine Image ID'

Parameters:
  EnvironmentType:
    Description: 'Specify the Environment type of the stack.'
    Type: String
    Default: Test
    AllowedValues:
      - Dev
      - Test
      - Prod
    ConstraintDescription: 'Specify either Dev, Test or Prod.'

  AmiID:
    Type: AWS::EC2::Image::Id
    Description: 'The ID of the AMI.'

Mappings:
  EnvironmentToInstanceType:
    Dev:
      InstanceType: t2.nano
    Test:
      InstanceType: t2.micro
    Prod:
      InstanceType: t2.small

Resources:
  WebServerInstance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !Ref AmiID
      InstanceType: !FindInMap [EnvironmentToInstanceType, !Ref EnvironmentType, InstanceType]
      Tags:
        - Key: Name
          Value: !Join [ '-', [ !Ref EnvironmentType, webserver ] ]
代码解释:

让我们从创建EnvironmentType参数开始。它定义了三个环境,Test, Dev和Prod。模板的“Parameters”部分代码如下:

Parameters:
  EnvironmentType:
    Description: 'Specify the Environment type of the stack.'
    Type: String
    Default: Test
    AllowedValues:
      - Test
      - Prod
      - Dev
    ConstraintDescription: 'Specify either Test or Prod.'

接下来,在Mappings部分中创建EnvironmentToInstanceType

Mappings:
  EnvironmentToInstanceType: # Map Name
    Test: # Top level key
      InstanceType: t2.micro # Second level key
    Prod:
      InstanceType: t2.small

接下来,通过Fn::FindInMap函数,CloudFormationEnvironmentToInstanceType映射中查找值,并将该值返回给InstanceType属性:

Resources:
  WebServerInstance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !Ref AmiID
      InstanceType: !FindInMap [EnvironmentToInstanceType, !Ref EnvironmentType, InstanceType]

这样CloudFormation将根据传入的值是Test还是Prod,部署对应的EC2实例类型


部署CloudFormation - 在上一节的堆栈中更新:

image-20210522215336233

选择上传 05-lab04-Mapping.yaml

image-20210522215431792

Amazon Machine Image ID 使用默认值,EnvironmentType选择下拉框中的某个环境:

image-20210522224942871

一直点击Next,直至更新完成。

总结

在本实验中完成了以下内容:

  • 为环境类型(例如TestProd)创建映射。每种环境类型都将映射到不同的实例类型
  • 在映射中找到所需的值,并在EC2资源中引用它。