步骤1:创建一个名为template.yaml的文件,在其中定义每个“资源”及其属性。例如:
Resources:
FirstFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: FirstFunction
CodeUri: ./first/
Handler: app.lambda_handler
Runtime: python3.8
MemorySize: 128
Timeout: 60
Role: !GetAtt SampleRole.Arn
SecondFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: SecondFunction
CodeUri: ./second/
Handler: app.lambda_handler
Runtime: python3.8
MemorySize: 256
Timeout: 120
Role: !GetAtt SampleRole.Arn
步骤2:对每个资源分别创建一个文件夹,并在其中分别定义功能代码文件和其他配置文件。
在以上示例中,我们创建了两个函数资源:FirstFunction 和 SecondFunction。因此,在当前目录下,我们将创建一个名为first的目录,并在其中包含此函数的Python代码。我们还将在每个目录中创建其他配置文件,例如首个函数的配置文件。
目录结构如下:
/
├── first/
│ ├── app.py
│ ├── requirements.txt
│ └── config.yml
├── second/
│ ├── app.py
│ ├── requirements.txt
│ └── config.yml
└── template.yaml
步骤3:在template.yaml文件中将资源更改为以下内容:
Resources:
FirstFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: FirstFunction
CodeUri: ./first/
Handler: app.lambda_handler
Runtime: python3.8
MemorySize: 128
Timeout: 60
Role: !GetAtt SampleRole.Arn
SecondFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: SecondFunction
CodeUri: ./second/
Handler: app.lambda_handler
Runtime: python3.8
MemorySize: 256
Timeout: 120
Role: !GetAtt SampleRole.Arn
FirstFunctionBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: first-function-bucket
SecondFunctionBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: second-function-bucket
通过这些步骤,您已实现AWS SAM 模板的拆分,从而大大减少了代码管理的复杂性。