

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 共享 Lambda 图层
<a name="sharing-lambda-layers"></a>

如果您已在 Lambda 层中实现了功能，则可能需要在不托管该层的全局实例的情况下共享该层。通过以这种方式共享层，其他用户可以将层的实例部署到自己的账户。这样可以防止客户端应用程序依赖于层的全局实例。 AWS Serverless Application Repository 使您能够以这种方式轻松共享 Lambda 层。

有关 Lambda 层的更多信息，请参阅*AWS Lambda 开发者*指南中的[AWS Lambda 层](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)。

## 工作方式
<a name="sharing-lambda-layers-how-it-works"></a>

以下是使用 AWS Serverless Application Repository共享层的步骤。这允许在用户的 AWS 账户中创建图层的副本。

1. 使用包含您的层作为资源的 AWS SAM 模板来定义无服务器应用程序，即[https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-layerversion.html](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-layerversion.html)或[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-layerversion.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-layerversion.html)资源。

1. 将您的应用程序发布到 AWS Serverless Application Repository并共享（公开或私下）。

1. 客户部署了您的应用程序，该应用程序会在自己的 AWS 账户中创建您的图层副本。现在，客户可以在其客户端应用程序中在其 AWS 账户中引用该层的 Amazon 资源名称 (ARN)。

## 示例
<a name="sharing-layers-example"></a>

以下是包含您要共享的 Lambda 层的应用程序的示例 AWS SAM 模板：

```
Resources:
  SharedLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: shared-layer
      ContentUri: source/layer-code/
      CompatibleRuntimes:
        - python3.7
Outputs:
  LayerArn:
    Value: !Ref SharedLayer
```

当客户从部署您的应用程序时 AWS Serverless Application Repository，将在他们的 AWS 账户中创建一个层。层的 ARN 如下所示：

`arn:aws:lambda:us-east-1:012345678901:layer:shared-layer:1`

客户现在可以在自己的客户端应用程序中引用此 ARN，如下例所示：

```
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: python3.7
      CodeUrl: source/app-code/
      Layers:
        - arn:aws:lambda:us-east-1:012345678901:layer:shared-layer:1
```