这一部分将介绍 Mappings
. Mappings是CloudFormation
的顶级对象(top-level object)。 它用于定义映射(键和值),然后可以在模板中引用它们。
下面是一个Mappings示例。AnExampleMap
包含三个顶级键TopLevelKey01
,TopLevelKey02
和TopLevelKey03
,每个顶级键包含一个或多个键值对:
Mappings:
AnExampleMap:
TopLevelKey01:
Key01: Value01
Key02: Value02
TopLevelKey02:
AnotherKey: AnExampleValue
TopLevelKey03:
AFinalKey: ADifferentValue
将以下代码保存为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
函数,CloudFormation
在EnvironmentToInstanceType
映射中查找值,并将该值返回给InstanceType
属性:
Resources:
WebServerInstance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref AmiID
InstanceType: !FindInMap [EnvironmentToInstanceType, !Ref EnvironmentType, InstanceType]
这样CloudFormation将根据传入的值是Test
还是Prod
,部署对应的EC2实例类型
部署CloudFormation
- 在上一节的堆栈中更新:
选择上传 05-lab04-Mapping.yaml
:
Amazon Machine Image ID 使用默认值,EnvironmentType选择下拉框中的某个环境:
一直点击Next,直至更新完成。
在本实验中完成了以下内容: