

# 与层结合使用 AWS CloudFormation
<a name="layers-cfn"></a>

您可以使用 CloudFormation 创建层并将层与 Lambda 函数关联起来。以下示例模板会创建一个名为 `my-lambda-layer` 的层，并使用**层**属性将该层附加到 Lambda 函数。

在此示例中，模板指定现有 IAM [执行角色](lambda-intro-execution-role.md)的 Amazon 资源名称（ARN）。您也可以使用 CloudFormation [AWS::IAM::Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html) 资源在模板中创建新的执行角色。

您的函数不需要任何特殊权限即可使用层。

```
---
Description: CloudFormation Template for Lambda Function with Lambda Layer
Resources:
  MyLambdaLayer:
    Type: AWS::Lambda::LayerVersion
    Properties:
      LayerName: my-lambda-layer
      Description: My Lambda Layer
      Content:
        S3Bucket: amzn-s3-demo-bucket
        S3Key: my-layer.zip
      CompatibleRuntimes:
        - python3.9
        - python3.10
        - python3.11

  MyLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: my-lambda-function
      Runtime: python3.9
      Handler: index.handler
      Timeout: 10
      Role: arn:aws:iam::111122223333:role/my_lambda_role
      Layers:
        - !Ref MyLambdaLayer
```