CloudFormation - Mappings
Mappings are fixed values in the CloudFormation template specified in key-value format. To access the mapping values, use Fn::FindInMap.
!FindInMap[MapName, TopLevelKey, SecondLevelKey]
example: !FindInMap [environmentMap, dev, ami]
AWSTemplateFormatVersion: 2010-09-09
Parameters:
env:
Description: "Enter Environment: (dev/prod)"
Type: String
Mappings:
environmentMap:
dev:
instype : "t2.micro"
ami: "ami-0c6120f461d6b39e9"
prod:
instype: "t2.small"
ami: "ami-0a443decce6d88dc2"
Resources:
AppServer:
Type: 'AWS::EC2::Instance'
Properties:
ImageId: !FindInMap [environmentMap, !Ref env, ami]
InstanceType: !FindInMap [environmentMap, !Ref env, instype]
SecurityGroups:
- "sshSG"
Tags:
- Key: "Name"
Value: !Sub
- '${environment}_server'
- environment: !Ref env
In the above template, the mapping "environmentMap" has two Top Level Keys [dev/prod]. Based on the input parameter passed (dev/prod), the instance is created with the corresponding mapping values for ami & instance type.
aws cloudformation create-stack --stack-name myteststack1 --template-body file:///home/ec2-user/CF_Learnings/004_Mappings/mappings.yaml --region ap-southeast-2 --parameters ParameterKey=env,ParameterValue=prod
In the input parameter, we specified environment parameter value to be "prod " and hence appropriate ImageId & InstanceType are chosen from the mapping defined for "prod".