在CloudFormation中创建"Mappings"的目的是什么?



见下面的代码:

Mappings:
RegionMap:
us-east-1:
bucketname: s3bucketname-us-east-1
us-east-2:
bucketname: s3bucketname-us-east-2
us-west-1:
bucketname: s3bucketname-us-west-1
us-west-2:
bucketname: s3bucketname-us-west-2
ap-south-1:
bucketname: s3bucketname-ap-south-1
ap-northeast-2:
bucketname: s3bucketname-ap-northeast-2
ap-southeast-1:
bucketname: s3bucketname-ap-southeast-1
ap-southeast-2:
bucketname: s3bucketname-ap-southeast-2
ap-northeast-1:
bucketname: s3bucketname-ap-northeast-1
ca-central-1:
bucketname: s3bucketname-ca-central-1
eu-central-1:
bucketname: s3bucketname-eu-central-1
eu-west-1:
bucketname: s3bucketname-eu-west-1
eu-west-2:
bucketname: s3bucketname-eu-west-2
eu-west-3:
bucketname: s3bucketname-eu-west-3
eu-north-1:
bucketname: s3bucketname-eu-north-1
sa-east-1:
bucketname: s3bucketname-east-1
af-south-1:
bucketname: s3bucketname-south-1
ap-east-1:
bucketname: s3bucketname-east-1
ap-northeast-3:
bucketname: s3bucketname-ap-northeast-3
eu-south-1:
bucketname: s3bucketname-eu-south-1
me-south-1:
bucketname: s3bucketname-me-south-1
Resources:
StateS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "cfntf-${AWS::Region}-${AWS::AccountId}"

还有更多的代码,但是我只包含了与问题相关的片段。

总结一下—当直接使用"资源"部分中的区域和帐户ID设置bucketname时,为什么要包含bucketname的映射?

这里使用Fn::FindInMap函数作为ExecutorLambdaFunction的一部分:

ExecutorLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: myfunction
Handler: index.handler
Role: !GetAtt ExecutorLambdaServiceRole.Arn
Environment:
Variables:
BUCKET: !Ref StateS3Bucket
Code:
S3Bucket: !If
- S3Defined
- !Ref S3Bucket
- Fn::FindInMap:
- RegionMap
- !Ref AWS::Region
- bucketname
S3Key: !If
- S3Defined
- !Ref S3Key
- /app.zip
Runtime: python3.8

StateS3Bucket是从区域和帐户ID构建的,但这与无关Mappings部分有关。

在这种情况下,映射被用来为ExecutorLambdaFunction的打包源代码所在的位置提供正确的特定于区域的S3桶名——这就是为什么在Lambda声明中使用Fn::FindInMap的原因。


有时您可能希望基于特定的键具有动态值- CloudFormationMappings部分是解决此问题的完美方案。

您打包的Lambda(源代码)在本例中指向S3位置&S3 bucket的特定区域,您需要一种方法的正确斗名字堆栈被部署在该地区。

的代码ExecutorLambdaFunction必须从S3 bucket加载相关地区的否则它将无法工作。

例如,当您的Lambda部署在eu-west-2中时,试图从us-east-1中的bucket加载Lambda源代码将不起作用(注意:如果它部署在us-east-2中,它将工作,因为它在另一个可用区中,它仍在同一区域内)

即使你只打算让你的堆栈只在一个区域,它不会伤害你有一个Mappings节,因为它将证明你的CloudFormation模板。

如果您没有任何特定于区域的基础设施(非常罕见,但例如仅创建全局IAM角色&(在帐户级别设置),则不能包含。

如果你只是多花3分钟来定义&使用Mappings作为你写你的模板-你会感谢你自己,如果你以后决定部署你的堆栈在另一个地区。

最新更新