

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

# 添加和自定义 Elastic Beanstalk 环境资源
<a name="environment-resources"></a>

您可能希望自定义属于 Elastic Beanstalk 环境一部分的环境资源。例如，您可能想要添加 Amazon SQS 队列和队列深度警报，或者您可能想要添加一个 Ama ElastiCache zon 集群。在部署应用程序版本的同时，您就可以轻松地自定义环境，只需使用源包将配置文件添加进来即可。

您可以使用[配置文件](ebextensions.md)中的`Resources`密钥在您的环境中创建和自定义 AWS 资源。配置文件中定义的资源将添加到用于启动环境的 CloudFormation 模板中。支持所有 CloudFormation [资源类型](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)。

**注意**  
每当您添加不由 Elastic Beanstalk 管理的资源时，请务必为您的 (IAM) 用户添加具有相应权限 AWS Identity and Access Management 的用户策略。Elastic Beanstalk 提供的[托管用户策略](AWSHowTo.iam.managed-policies.md)仅涵盖对 Elastic Beanstalk 托管资源的权限。

例如，以下配置文件将 Auto Scaling 生命周期挂钩添加到 Elastic Beanstalk 创建的默认 Auto Scaling 组中：

**`~/my-app/.ebextensions/as-hook.config`**

```
Resources:
  hookrole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument: {
               "Version": "2012-10-17",		 	 	 
               "Statement": [ {
                  "Effect": "Allow",
                  "Principal": {
                     "Service": [ "autoscaling.amazonaws.com" ]
                  },
                  "Action": [ "sts:AssumeRole" ]
               } ]
            }
      Policies: [ {
               "PolicyName": "SNS",
               "PolicyDocument": {
                      "Version": "2012-10-17",		 	 	 
                      "Statement": [{
                          "Effect": "Allow",
                          "Resource": "*",
                          "Action": [
                              "sqs:SendMessage",
                              "sqs:GetQueueUrl",
                              "sns:Publish"
                          ]
                        }
                      ]
                  }
               } ]
  hooktopic:
    Type: AWS::SNS::Topic
    Properties:
      Subscription:
        - Endpoint: "my-email@example.com"
          Protocol: email
  lifecyclehook:
    Type: AWS::AutoScaling::LifecycleHook
    Properties:
      AutoScalingGroupName: { "Ref" : "AWSEBAutoScalingGroup" }
      LifecycleTransition: autoscaling:EC2_INSTANCE_TERMINATING
      NotificationTargetARN: { "Ref" : "hooktopic" }
      RoleARN: { "Fn::GetAtt" : [ "hookrole", "Arn"] }
```

此示例定义三个资源：`hookrole`、`hooktopic` 和 `lifecyclehook`。前两个资源是 IAM 角色，它授予 Amazon A EC2 uto Scaling 向亚马逊 SNS 发布消息的权限，以及一个 SNS 主题，用于将来自 Auto Scaling 组的消息中继到电子邮件地址。Elastic Beanstalk 使用指定的属性和类型创建这些资源。

最后一个资源 `lifecyclehook` 是生命周期钩子本身：

```
  lifecyclehook:
    Type: AWS::AutoScaling::LifecycleHook
    Properties:
      AutoScalingGroupName: { "Ref" : "AWSEBAutoScalingGroup" }
      LifecycleTransition: autoscaling:EC2_INSTANCE_TERMINATING
      NotificationTargetARN: { "Ref" : "hooktopic" }
      RoleARN: { "Fn::GetAtt" : [ "hookrole", "Arn"] }
```

生命周期钩子使用两个[函数](ebextensions-functions.md)填充钩子属性值。`{ "Ref" : "AWSEBAutoScalingGroup" }` 检索 Elastic Beanstalk 为环境创建的 Auto Scaling 组的名称。`AWSEBAutoScalingGroup` 是 Elastic Beanstalk 提供的标准[资源名称](customize-containers-format-resources-eb.md)之一。

对于 `[AWS::IAM::Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#d0e48356)`，`Ref` 只返回角色名称，而不返回 ARN。要获取 `RoleARN` 参数的 ARN，需要改用另一个内部函数 `Fn::GetAtt`，该函数获取一个资源的所有属性。`RoleARN: { "Fn::GetAtt" : [ "hookrole", "Arn"] }` 将从 `hookrole` 资源获取 `Arn` 属性。

`{ "Ref" : "hooktopic" }` 获取之前在配置文件中创建的 Amazon SNS 主题的 ARN。返回的值因资源类型`Ref`而异，可以在该[ AWS::SNS::Topic 资源类型的 CloudFormation 用户指南主题](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-topic.html#d0e62250)中找到。

# 修改 Elastic Beanstalk 为环境创建的资源
<a name="customize-containers-format-resources-eb"></a>

Elastic Beanstalk 为您的环境创建的资源有名称。您可以使用这些名称通过[函数](ebextensions-functions.md)来获取有关资源的信息，或修改资源中的属性来自定义其行为。本主题介绍了 Elastic Beanstalk 在不同类型的环境中使用的 AWS 资源。

**注意**  
上一主题[自定义资源](environment-resources.md)提供了一些用于自定义环境资源的使用案例和示例。另外，您可以在后面的主题 [自定义资源示例](customize-environment-resources-examples.md) 中找到更多配置文件示例。

Web 服务器环境具有以下资源。

**Web 服务器环境**
+ `AWSEBAutoScalingGroup`（[AWS::AutoScaling::AutoScaling群组](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html)）— 连接到您的环境的 Auto Scaling 群组。
+ 以下两种资源之一。
  + `AWSEBAutoScalingLaunchConfiguration`([AWS::AutoScaling::LaunchConfiguration](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html))-附加到您环境的 Auto Scaling 组的启动配置。
  + `AWSEBEC2LaunchTemplate`([AWS::EC2::LaunchTemplate](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html)) — 您的环境的 Auto Scaling 组使用的 Amazon EC2 启动模板。
**注意**  
如果您的环境使用需要 Amazon EC2 启动模板的功能，并且您的用户策略缺少所需权限，则创建或更新环境可能会失败。[使用 **AdministratorAccess-AWSElastic Beanstalk**[托管用户策略](AWSHowTo.iam.managed-policies.md)，或向您的自定义策略添加所需的权限。](AWSHowTo.iam.managed-policies.md#AWSHowTo.iam.policies)
+ `AWSEBEnvironmentName`([AWS::ElasticBeanstalk::Environment](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html)) — 您的环境。
+ `AWSEBSecurityGroup`([AWS::EC2::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html)) — 附加到您的 Auto Scaling 组的安全组。
+ `AWSEBRDSDatabase`([AWS:: RDS:: DBInstance](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html)) — 连接到您的环境的 Amazon RDS 数据库实例（如果适用）。

在负载均衡的环境中，您可以访问与负载均衡器相关的其他资源。传统负载均衡器有一个资源用于负载均衡器，一个资源用于连接到它的安全组。应用程序和网络负载均衡器还有附加资源可用于负载均衡器的默认侦听器、侦听器规则和目标组。

**负载均衡环境**
+ `AWSEBLoadBalancer`([AWS::ElasticLoadBalancing::LoadBalancer](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html))-您的环境的经典负载均衡器。
+ `AWSEBV2LoadBalancer`([AWS::ElasticLoadBalancingV2::LoadBalancer](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html))-您的环境的应用程序或网络负载均衡器。
+ `AWSEBLoadBalancerSecurityGroup`([AWS::EC2::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html)) — 仅在自定义[亚马逊虚拟私有云](https://docs.aws.amazon.com/vpc/latest/userguide/)（亚马逊 VPC）中，Elastic Beanstalk 为负载均衡器创建的安全组的名称。在默认 VPC 或 EC2 Classic 中，Elastic Load Balancing 会将默认安全组分配给负载均衡器。
+ `AWSEBV2LoadBalancerListener`([AWS::ElasticLoadBalancingV2::Listener](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html)) — 允许负载均衡器检查连接请求并将其转发给一个或多个目标组的侦听器。
+ `AWSEBV2LoadBalancerListenerRule`([AWS::ElasticLoadBalancingV2::ListenerRule](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenerrule.html)) — 定义 Elastic Load Balancing 侦听器对哪些请求采取操作以及它采取的操作。
+ `AWSEBV2LoadBalancerTargetGroup`([AWS::ElasticLoadBalancingV2::TargetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html)) — 一个 Elastic Load Balancing 目标组，用于将请求路由到一个或多个注册目标，例如 Amazon EC2 实例。

工作线程环境具有用于可缓存传入请求的 SQS 队列的资源，还有一个 Amazon DynamoDB 表，实例可使用该表来选择领导。

**工作线程环境**
+ `AWSEBWorkerQueue`([AWS::SQS::Queue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html)) — Amazon SQS 队列，守护程序从中提取需要处理的请求。
+ `AWSEBWorkerDeadLetterQueue`([AWS::SQS::Queue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html)) — Amazon SQS 队列，用于存储守护程序无法传送或未成功处理的消息。
+ `AWSEBWorkerCronLeaderRegistry`([AWS::DynamoDB::Table](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html)) — Amazon DynamoDB 表，它是守护程序用于执行定期任务的内部注册表。

# 其他 CloudFormation 模板密钥
<a name="ebextensions-otherkeys"></a>

我们已经引入了 CloudFormation 诸如`Resources``files`、和之类的配置文件密钥`packages`。Elastic Beanstalk 将配置文件 CloudFormation 内容添加到支持您的环境的模板中，因此 CloudFormation 您可以使用其他部分在配置文件中执行高级任务。

**Topics**
+ [参数](#ebextensions-otherkeys-parameters)
+ [输出](#ebextensions-otherkeys-outputs)
+ [映像](#ebextensions-otherkeys-mappings)

## 参数
<a name="ebextensions-otherkeys-parameters"></a>

参数是 Elastic Beanstalk 自己的[自定义选项](configuration-options-custom.md)的替代项，您可以用来定义要在配置文件的其他位置使用的值。与自定义选项相似，您可以使用参数在一个位置，收集用户可配置值。与自定义选项不同，您不能使用 Elastic Beanstalk 的 API 来设置参数值，并且可以在模板中定义的参数数量受到限制。 CloudFormation

您可能想要使用参数的原因之一是让您的配置文件兼作 CloudFormation 模板。如果您使用参数而不是自定义选项，则可以使用配置文件在中 CloudFormation 创建与其自己的堆栈相同的资源。例如，您可能有一个配置文件用于向环境中添加用于测试的 Amazon EFS 文件系统，然后使用同一个文件创建独立的文件系统，不绑定到用于生产用途的环境生命周期。

以下示例演示使用参数在配置文件顶部收集用户可配置的值。

**Example [L oadbalancer-accesslogs-existingbucket .config](https://github.com/awsdocs/elastic-beanstalk-samples/tree/main/configuration-files/aws-provided/resource-configuration/loadbalancer-accesslogs-existingbucket.config) — 参数**  

```
Parameters:
  bucket:
    Type: String
    Description: "Name of the Amazon S3 bucket in which to store load balancer logs"
    Default: "amzn-s3-demo-bucket"
  bucketprefix:
    Type: String
    Description: "Optional prefix. Can't start or end with a /, or contain the word AWSLogs"
    Default: ""
```

## 输出
<a name="ebextensions-otherkeys-outputs"></a>

您可以使用 `Outputs` 数据块，将有关已创建资源的信息导出到 CloudFormation。然后，你可以使用该`Fn::ImportValue`函数将该值提取到 Elastic Beanstalk 之外的 CloudFormation 模板中。

以下示例创建了一个 Amazon SNS 主题，并将其 ARN 导出到名称为。 CloudFormation `NotificationTopicArn`

**Example [sns-topic.config](https://github.com/awsdocs/elastic-beanstalk-samples/tree/main/configuration-files/aws-provided/resource-configuration/sns-topic.config)**  

```
Resources:
  NotificationTopic:
    Type: AWS::SNS::Topic

Outputs:
  NotificationTopicArn:
    Description: Notification topic ARN
    Value: { "Ref" : "NotificationTopic" }
    Export:
      Name: NotificationTopicArn
```

在其他环境的配置文件或 Elastic Beanstalk 之外的 CloudFormation 模板中，`Fn::ImportValue`您可以使用该函数来获取导出的 ARN。此示例将导出的值分配给名为 `TOPIC_ARN` 的环境属性。

**Example env.config**  

```
option_settings:
  aws:elasticbeanstalk:application:environment:
    TOPIC_ARN: '`{ "Fn::ImportValue" : "NotificationTopicArn" }`'
```

## 映像
<a name="ebextensions-otherkeys-mappings"></a>

您可以使用映射，来存储按命名空间组织的键-值对。映射可以帮助组织您在配置中使用的值，或根据其它值来更改参数值。例如，以下配置根据当前区域来设置账户 ID 参数的值。

**Example [L oadbalancer-accesslogs-newbucket .config](https://github.com/awsdocs/elastic-beanstalk-samples/tree/main/configuration-files/aws-provided/resource-configuration/loadbalancer-accesslogs-newbucket.config) — 映射**  

```
Mappings: 
  Region2ELBAccountId: 
    us-east-1: 
      AccountId: "111122223333"
    us-west-2: 
      AccountId: "444455556666"
    us-west-1: 
      AccountId: "123456789012"
    eu-west-1: 
      AccountId: "777788889999"
...
            Principal: 
              AWS: 
                ? "Fn::FindInMap"
                : 
                  - Region2ELBAccountId
                  - 
                    Ref: "AWS::Region"
                  - AccountId
```

# 函数
<a name="ebextensions-functions"></a>

您可以在配置文件中使用函数，通过来自其他资源或来自 Elastic Beanstalk 配置选项设置的信息填充资源属性的值。Elastic B CloudFormation eanstalk 支持`Ref`函数 `Fn::GetAtt` (`Fn::Join`、、) 和一个特定于 Elastic BeanStalk 的函数。`Fn::GetOptionSetting`

**Topics**
+ [Ref](#ebextensions-functions-ref)
+ [Fn:: GetAtt](#ebextensions-functions-getatt)
+ [Fn::Join](#ebextensions-functions-join)
+ [Fn:: GetOptionSetting](#ebextensions-functions-getoptionsetting)

## Ref
<a name="ebextensions-functions-ref"></a>

`Ref`用于检索 AWS 资源的默认字符串表示形式。`Ref` 返回的值取决于资源类型，有时也取决于其他因素。例如，安全组 ([AWS::EC2::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html)) 返回安全组的名称或 ID，具体取决于该安全组是在默认的[亚马逊虚拟私有云 (Amazon](https://docs.aws.amazon.com/vpc/latest/userguide/) VPC)、 EC2经典还是自定义 VPC 中。

```
{ "Ref" : "resource name" }
```

**注意**  
有关每个资源类型的详细信息（包括 `Ref` 的返回值），请参阅 *CloudFormation 用户指南*中的 [AWS 资源类型参考](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)。

在 [Auto Scaling 生命周期挂钩](environment-resources.md)示例中：

```
Resources:
  lifecyclehook:
    Type: AWS::AutoScaling::LifecycleHook
    Properties:
      AutoScalingGroupName: { "Ref" : "AWSEBAutoScalingGroup" }
```

您还可以使用`Ref`检索在同一文件或其他配置文件中其他位置定义的 CloudFormation 参数的值。

## Fn:: GetAtt
<a name="ebextensions-functions-getatt"></a>

`Fn::GetAtt`用于检索 AWS 资源上属性的值。

```
{ "Fn::GetAtt" : [ "resource name", "attribute name"] }
```

在 [Auto Scaling 生命周期挂钩](environment-resources.md)示例中：

```
Resources:
  lifecyclehook:
    Type: AWS::AutoScaling::LifecycleHook
    Properties:
      RoleARN: { "Fn::GetAtt" : [ "hookrole", "Arn"] }
```

有关更多信息，请参阅 [Fn:: GetAtt](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html)。

## Fn::Join
<a name="ebextensions-functions-join"></a>

使用 `Fn::Join` 可组合带有一个分隔符的字符串。这些字符串可以进行硬编码，也可以使用来自 `Fn::GetAtt` 或 `Ref` 的输出。

```
{ "Fn::Join" : [ "delimiter", [ "string1", "string2" ] ] }
```

有关更多信息，请参阅 [Fn::Join](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-join.html)。

## Fn:: GetOptionSetting
<a name="ebextensions-functions-getoptionsetting"></a>

使用 `Fn::GetOptionSetting` 可检索应用于环境的[配置选项](command-options.md)设置的值。

```
"Fn::GetOptionSetting":
  Namespace: "namespace"
  OptionName: "option name"
  DefaultValue: "default value"
```

在[存储私有密钥](https-storingprivatekeys.md)示例中：

```
Resources:
  AWSEBAutoScalingGroup:
    Metadata:
      AWS::CloudFormation::Authentication:
        S3Auth:
          type: "s3"
          buckets: ["elasticbeanstalk-us-west-2-123456789012"]
          roleName: 
            "Fn::GetOptionSetting": 
              Namespace: "aws:autoscaling:launchconfiguration"
              OptionName: "IamInstanceProfile"
              DefaultValue: "aws-elasticbeanstalk-ec2-role"
```

# 自定义资源示例
<a name="customize-environment-resources-examples"></a>

以下是可以用于自定义 Elastic Beanstalk 环境的一系列示例配置文件：
+ [DynamoDB CloudWatch、和 SNS](https://elasticbeanstalk.s3.amazonaws.com/extensions/DynamoDB-with-CloudWatch-Alarms.config)
+ [Elastic Load Balancin CloudWatch](https://elasticbeanstalk.s3.amazonaws.com/extensions/ELB-Alarms.config)
+ [ElastiCache](https://elasticbeanstalk.s3.amazonaws.com/extensions/ElastiCache.config)
+ [RDS 和 CloudWatch](https://elasticbeanstalk.s3.amazonaws.com/extensions/RDS-Alarms.config)
+ [SQS、SNS 和 CloudWatch](https://elasticbeanstalk.s3.amazonaws.com/extensions/SNS.config)

本页的子主题提供了一些在 Elastic Beanstalk 环境中添加和配置自定义资源的扩展示例。

**Topics**
+ [例如： ElastiCache](customize-environment-resources-elasticache.md)
+ [示例：SQS CloudWatch、和 SNS](customize-environment-resources-sqs.md)
+ [示例：DynamoDB CloudWatch、和 SNS](customize-environment-resources-dynamodb.md)

# 例如： ElastiCache
<a name="customize-environment-resources-elasticache"></a>

以下示例将亚马逊 ElastiCache 集群添加到 EC2-Classic 和 EC2-VPC（包括默认和自定义[亚马逊虚拟私有云](https://docs.aws.amazon.com/vpc/latest/userguide/)（亚马逊 VPC））平台。有关这些平台以及如何确定 EC2 支持您所在地区和 AWS 账户的平台的更多信息，请参阅[https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html)。然后请参阅本主题中适用于您的平台的部分。
+ [EC2-classic 平台](#customize-environment-resources-elasticache-classic)
+ [EC2-VPC (默认)](#customize-environment-resources-elasticache-defaultvpc)
+ [EC2-VPC (自定义)](#customize-environment-resources-elasticache-targetedvpc)

## EC2-classic 平台
<a name="customize-environment-resources-elasticache-classic"></a>

此示例将一个 Amazon ElastiCache 集群添加到一个环境中，其实例已启动到 EC2-Classic 平台。此示例中列出的所有属性是为每种资源类型必须设置的最低要求。你可以在示例中下载示[ElastiCache例](https://elasticbeanstalk.s3.amazonaws.com/extensions/ElastiCache.config)。

**注意**  
此示例创建了 AWS 资源，您可能需要为此付费。有关 AWS 定价的更多信息，请参阅[https://aws.amazon.com/pricing/](https://aws.amazon.com/pricing/)。有些服务属于 AWS 免费使用套餐的一部分。如果您是新客户，则可免费试用这些服务。请参阅[https://aws.amazon.com/free/](https://aws.amazon.com/free/)了解更多信息。

要使用此示例，请执行下列操作：

1. 在源包的顶级目录中创建 `[.ebextensions](ebextensions.md)` 目录。

1. 创建两个扩展名为 `.config` 的配置文件并将其放入您的 `.ebextensions` 目录。一个配置文件定义资源，另一个配置文件定义选项。

1. 将应用程序部署到 Elastic Beanstalk。

   YAML 依赖一致的缩进。当替换示例配置文件中的内容时，应匹配缩进级别，并且确保您的文本编辑器使用空格而不是字符来进行缩进。

创建定义资源的配置文件 (例如，`elasticache.config`)。在此示例中，我们通过指定 ElastiCache 群集资源的名称 (`MyElastiCache`)、声明其类型，然后配置群集的属性来创建群集。 ElastiCache 该示例引用了在此配置文件中创建和定义 ElastiCache 的安全组资源的名称。接下来，我们创建一个 ElastiCache 安全组。我们会定义这个资源的名称、声明它的类型和添加该安全组的描述。最后，我们将安全组的入口规则设置为仅允许来自 ElastiCache 安全组 (`MyCacheSecurityGroup`) 和 Elastic Beanstalk ElastiCache 安全组 () 内部的实例进行访问。`AWSEBSecurityGroup`参数名 `AWSEBSecurityGroup` 是 Elastic Beanstalk 提供的固定资源名称。您必须`AWSEBSecurityGroup`向 ElastiCache 安全组添加入口规则，这样您的 Elastic Beanstalk 应用程序才能连接到集群中的实例。 ElastiCache 

```
#This sample requires you to create a separate configuration file that defines the custom option settings for CacheCluster properties.
          
Resources:
  MyElastiCache:
    Type: AWS::ElastiCache::CacheCluster
    Properties:
      CacheNodeType: 
         Fn::GetOptionSetting:
             OptionName : CacheNodeType
             DefaultValue: cache.m1.small
      NumCacheNodes: 
           Fn::GetOptionSetting:
             OptionName : NumCacheNodes
             DefaultValue: 1
      Engine: 
           Fn::GetOptionSetting:
             OptionName : Engine
             DefaultValue: memcached
      CacheSecurityGroupNames:
        - Ref: MyCacheSecurityGroup
  MyCacheSecurityGroup:
    Type: AWS::ElastiCache::SecurityGroup
    Properties:
      Description: "Lock cache down to webserver access only"
  MyCacheSecurityGroupIngress:
    Type: AWS::ElastiCache::SecurityGroupIngress
    Properties:
      CacheSecurityGroupName: 
        Ref: MyCacheSecurityGroup
      EC2SecurityGroupName:
        Ref: AWSEBSecurityGroup
```

有关此示例配置文件中使用的资源的更多信息，请参阅以下参考：
+ [AWS::ElastiCache::CacheCluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html)
+ [AWS::ElastiCache::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-security-group.html)
+ [AWS::Elasti缓存：SecurityGroupIngress](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-security-group-ingress.html)

创建名为 `options.config` 的单独配置文件，并定义自定义选项设置。

```
option_settings:
  "aws:elasticbeanstalk:customoption":
     CacheNodeType : cache.m1.small
     NumCacheNodes : 1
     Engine : memcached
```

**这些行告诉 Elastic Beanstalk **CacheNodeType从配置文件（我们的示例中**CacheNodeType为 NumCacheNodes options.config）中获取、**和引擎属性的值， NumCacheNodes该**文件包含一个 option\$1settings 部分，其中有一个 aws: elasticbeanstalk: customoption 部分，其中包含包含要使用的实际值的名称-值对。**在以上示例中，这意味着 cache.m1.small、1 和 memcached 将用于这些值。有关 `Fn::GetOptionSetting` 的更多信息，请参阅 [函数](ebextensions-functions.md)。

## EC2-VPC (默认)
<a name="customize-environment-resources-elasticache-defaultvpc"></a>

此示例将 Amazon ElastiCache 集群添加到已启动到 EC2-VPC 平台的实例的环境中。具体来说，此部分中的信息适用于 EC2 在默认 VPC 中启动实例的情景。此示例中的所有属性是为每种资源类型必须设置的最低要求。有关默认的更多信息 VPCs，请参阅[您的默认 VPC 和子网](https://docs.aws.amazon.com/vpc/latest/userguide/default-vpc.html)。

**注意**  
此示例创建了 AWS 资源，您可能需要为此付费。有关 AWS 定价的更多信息，请参阅[https://aws.amazon.com/pricing/](https://aws.amazon.com/pricing/)。有些服务属于 AWS 免费使用套餐的一部分。如果您是新客户，则可免费试用这些服务。请参阅[https://aws.amazon.com/free/](https://aws.amazon.com/free/)了解更多信息。

要使用此示例，请执行下列操作：

1. 在源包的顶级目录中创建 `[.ebextensions](ebextensions.md)` 目录。

1. 创建两个扩展名为 `.config` 的配置文件并将其放入您的 `.ebextensions` 目录。一个配置文件定义资源，另一个配置文件定义选项。

1. 将应用程序部署到 Elastic Beanstalk。

   YAML 依赖一致的缩进。当替换示例配置文件中的内容时，应匹配缩进级别，并且确保您的文本编辑器使用空格而不是字符来进行缩进。

现在将资源配置文件命名为 `elasticache.config`。要创建 ElastiCache 群集，此示例指定 ElastiCache 群集资源的名称 (`MyElastiCache`)，声明其类型，然后配置群集的属性。该示例引用在此配置文件中创建和定义的安全组资源的 ID。

接下来，我们会创建 EC2 安全组。我们定义此资源的名称，声明其类型，添加描述，并为安全组设置传入规则以便仅允许从 Elastic Beanstalk 安全组 (`AWSEBSecurityGroup`) 中的实例进行访问。（参数名称是 Elastic Beanstalk 提供的固定资源名称。`AWSEBSecurityGroup` 您必须`AWSEBSecurityGroup`向 ElastiCache 安全组添加入口规则，这样您的 Elastic Beanstalk 应用程序才能连接到集群中的实例。） ElastiCache 

EC2 安全组的传入规则还定义缓存节点可以用于接受连接的 IP 协议和端口号。对于 Redis，默认端口号是 `6379`。

```
#This sample requires you to create a separate configuration file that defines the custom option settings for CacheCluster properties.

Resources:
  MyCacheSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Lock cache down to webserver access only"
      SecurityGroupIngress :
        - IpProtocol : "tcp"
          FromPort :
            Fn::GetOptionSetting:
              OptionName : "CachePort"
              DefaultValue: "6379"
          ToPort :
            Fn::GetOptionSetting:
              OptionName : "CachePort"
              DefaultValue: "6379"
          SourceSecurityGroupName:
            Ref: "AWSEBSecurityGroup"
  MyElastiCache:
    Type: "AWS::ElastiCache::CacheCluster"
    Properties:
      CacheNodeType:
        Fn::GetOptionSetting:
          OptionName : "CacheNodeType"
          DefaultValue : "cache.t2.micro"
      NumCacheNodes:
        Fn::GetOptionSetting:
          OptionName : "NumCacheNodes"
          DefaultValue : "1"
      Engine:
        Fn::GetOptionSetting:
          OptionName : "Engine"
          DefaultValue : "redis"
      VpcSecurityGroupIds:
        -
          Fn::GetAtt:
            - MyCacheSecurityGroup
            - GroupId

Outputs:
  ElastiCache:
    Description : "ID of ElastiCache Cache Cluster with Redis Engine"
    Value :
      Ref : "MyElastiCache"
```

有关此示例配置文件中使用的资源的更多信息，请参阅以下参考：
+ [AWS::ElastiCache::CacheCluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html)
+ [AWS::EC2::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html)

接下来，将选项配置文件命名为 `options.config`，然后定义自定义选项设置。

```
option_settings:
  "aws:elasticbeanstalk:customoption":
    CacheNodeType : cache.t2.micro
    NumCacheNodes : 1
    Engine : redis
    CachePort : 6379
```

这些行告知 Elastic Beanstalk 从配置文件（在我们的示例中为 `options.config`）中的 `CacheNodeType`、`NumCacheNodes`、`Engine` 和 `CachePort` 值获取 `CacheNodeType`、`NumCacheNodes`、`Engine` 和 `CachePort` 属性的值。该文件包含 `aws:elasticbeanstalk:customoption` 节 (在 `option_settings` 下)，其中含有要使用的实际值的名称/值对。在前面的示例中，会对这些值使用 `cache.t2.micro`、`1`、`redis` 和 `6379`。有关 `Fn::GetOptionSetting` 的更多信息，请参阅 [函数](ebextensions-functions.md)。

## EC2-VPC (自定义)
<a name="customize-environment-resources-elasticache-targetedvpc"></a>

如果您在 EC2-VPC 平台上创建自定义 VPC 并将其指定为 EC2 在其中启动实例的 VPC，则向您的环境中添加 Amazon ElastiCache 集群的过程与默认 VPC 的过程不同。主要区别在于您必须为 ElastiCache 集群创建子网组。此示例中的所有属性是为每种资源类型必须设置的最低要求。

**注意**  
此示例创建了 AWS 资源，您可能需要为此付费。有关 AWS 定价的更多信息，请参阅[https://aws.amazon.com/pricing/](https://aws.amazon.com/pricing/)。有些服务属于 AWS 免费使用套餐的一部分。如果您是新客户，则可免费试用这些服务。请参阅[https://aws.amazon.com/free/](https://aws.amazon.com/free/)了解更多信息。

要使用此示例，请执行下列操作：

1. 在源包的顶级目录中创建 `[.ebextensions](ebextensions.md)` 目录。

1. 创建两个扩展名为 `.config` 的配置文件并将其放入您的 `.ebextensions` 目录。一个配置文件定义资源，另一个配置文件定义选项。

1. 将应用程序部署到 Elastic Beanstalk。

   YAML 依赖一致的缩进。当替换示例配置文件中的内容时，应匹配缩进级别，并且确保您的文本编辑器使用空格而不是字符来进行缩进。

现在将资源配置文件命名为 `elasticache.config`。要创建 ElastiCache 群集，此示例指定 ElastiCache 群集资源的名称 (`MyElastiCache`)，声明其类型，然后配置群集的属性。示例中的属性引用了 ElastiCache 集群子网组的名称以及我们在此配置文件中创建和定义的安全组资源的 ID。

接下来，我们会创建 EC2 安全组。我们定义此资源的名称，声明其类型，添加描述和 VPC ID，并为安全组设置传入规则以便仅允许从 Elastic Beanstalk 安全组 (`AWSEBSecurityGroup`) 中的实例进行访问。（参数名称是 Elastic Beanstalk 提供的固定资源名称。`AWSEBSecurityGroup` 您必须`AWSEBSecurityGroup`向 ElastiCache 安全组添加入口规则，这样您的 Elastic Beanstalk 应用程序才能连接到集群中的实例。） ElastiCache 

EC2 安全组的传入规则还定义缓存节点可以用于接受连接的 IP 协议和端口号。对于 Redis，默认端口号是 `6379`。最后，此示例为 ElastiCache 群集创建了一个子网组。我们定义此资源的名称，声明其类型，并在子网组中添加子网的描述和 ID。

**注意**  
我们建议您为 ElastiCache 集群使用私有子网。有关具有私有子网的 VPC 的更多信息，请参阅 [https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Scenario2.html](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Scenario2.html)。

```
#This sample requires you to create a separate configuration file that defines the custom option settings for CacheCluster properties.

Resources:
  MyElastiCache:
    Type: "AWS::ElastiCache::CacheCluster"
    Properties:
      CacheNodeType:
        Fn::GetOptionSetting:
          OptionName : "CacheNodeType"
          DefaultValue : "cache.t2.micro"
      NumCacheNodes:
        Fn::GetOptionSetting:
          OptionName : "NumCacheNodes"
          DefaultValue : "1"
      Engine:
        Fn::GetOptionSetting:
          OptionName : "Engine"
          DefaultValue : "redis"
      CacheSubnetGroupName:
        Ref: "MyCacheSubnets"
      VpcSecurityGroupIds:
        - Ref: "MyCacheSecurityGroup"
  MyCacheSecurityGroup:
    Type: "AWS::EC2::SecurityGroup"
    Properties:
      GroupDescription: "Lock cache down to webserver access only"
      VpcId:
        Fn::GetOptionSetting:
          OptionName : "VpcId"
      SecurityGroupIngress :
        - IpProtocol : "tcp"
          FromPort :
            Fn::GetOptionSetting:
              OptionName : "CachePort"
              DefaultValue: "6379"
          ToPort :
            Fn::GetOptionSetting:
              OptionName : "CachePort"
              DefaultValue: "6379"
          SourceSecurityGroupId:
            Ref: "AWSEBSecurityGroup"
  MyCacheSubnets:
    Type: "AWS::ElastiCache::SubnetGroup"
    Properties:
      Description: "Subnets for ElastiCache"
      SubnetIds:
        Fn::GetOptionSetting:
          OptionName : "CacheSubnets"
Outputs:
  ElastiCache:
    Description : "ID of ElastiCache Cache Cluster with Redis Engine"
    Value :
      Ref : "MyElastiCache"
```

有关此示例配置文件中使用的资源的更多信息，请参阅以下参考：
+ [AWS::ElastiCache::CacheCluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html)
+ [AWS::EC2::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html)
+ [AWS::ElastiCache::SubnetGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-subnetgroup.html)

接下来，将选项配置文件命名为 `options.config`，然后定义自定义选项设置。

**注意**  
在以下示例中，将示例 `CacheSubnets` 和 `VpcId` 值替换为自己的子网和 VPC。

```
option_settings:
  "aws:elasticbeanstalk:customoption":
    CacheNodeType : cache.t2.micro
    NumCacheNodes : 1
    Engine : redis
    CachePort : 6379
    CacheSubnets:
      - subnet-1a1a1a1a
      - subnet-2b2b2b2b
      - subnet-3c3c3c3c
    VpcId: vpc-4d4d4d4d
```

这些行告知 Elastic Beanstalk 从配置文件（在我们的示例中为 `options.config`）中的 `CacheNodeType`、`NumCacheNodes`、`Engine`、`CachePort`、`CacheSubnets` 和 `VpcId` 值获取 `CacheNodeType`、`NumCacheNodes`、`Engine`、`CachePort`、`CacheSubnets` 和 `VpcId` 属性的值。该文件包含 `aws:elasticbeanstalk:customoption` 节 (在 `option_settings` 下)，其中含有具有示例值的名称/值对。在以上示例中，对这些值使用 `cache.t2.micro`、`1`、`redis`、`6379`、`subnet-1a1a1a1a`、`subnet-2b2b2b2b`、`subnet-3c3c3c3c` 和 `vpc-4d4d4d4d`。有关 `Fn::GetOptionSetting` 的更多信息，请参阅 [函数](ebextensions-functions.md)。

# 示例：SQS CloudWatch、和 SNS
<a name="customize-environment-resources-sqs"></a>

此示例给环境添加 Amazon SQS 队列以及有关队列深度的警报。此示例中显示的属性是必须具备的最低程度的属性，必须为每个资源进行设置。您可以在 [SQS、SNS 和](https://elasticbeanstalk.s3.amazonaws.com/extensions/SNS.config)上下载该示例。 CloudWatch

**注意**  
此示例创建了 AWS 资源，您可能需要为此付费。有关 AWS 定价的更多信息，请参阅[https://aws.amazon.com/pricing/](https://aws.amazon.com/pricing/)。有些服务属于 AWS 免费使用套餐的一部分。如果您是新客户，则可免费试用这些服务。请参阅[https://aws.amazon.com/free/](https://aws.amazon.com/free/)了解更多信息。

要使用此示例，请执行下列操作：

1. 在源包的顶级目录中创建 `[.ebextensions](ebextensions.md)` 目录。

1. 创建两个扩展名为 `.config` 的配置文件并将其放入您的 `.ebextensions` 目录。一个配置文件定义资源，另一个配置文件定义选项。

1. 将应用程序部署到 Elastic Beanstalk。

   YAML 依赖一致的缩进。当替换示例配置文件中的内容时，应匹配缩进级别，并且确保您的文本编辑器使用空格而不是字符来进行缩进。

创建定义资源的配置文件 (例如，sqs.config)。在此示例中，我们创建 SQS 队列并定义 `VisbilityTimeout` 资源中的 `MySQSQueue` 属性。下一步，我们创建 SNS `Topic`，并指定电子邮件在警报激发时发送到 `someone@example.com`。最后，如果队列超过 10 条消息，我们会创建 CloudWatch警报。在 `Dimensions` 属性中，我们指定维度的名称以及代表维度度量的值。我们使用 `Fn::GetAtt` 从 `QueueName` 中返回 `MySQSQueue` 的值。

```
#This sample requires you to create a separate configuration file to define the custom options for the SNS topic and SQS queue.
Resources:
  MySQSQueue:
    Type: AWS::SQS::Queue
    Properties: 
      VisibilityTimeout:
        Fn::GetOptionSetting:
          OptionName: VisibilityTimeout
          DefaultValue: 30
  AlarmTopic:
    Type: AWS::SNS::Topic
    Properties: 
      Subscription:
        - Endpoint:
            Fn::GetOptionSetting:
              OptionName: AlarmEmail
              DefaultValue: "nobody@amazon.com"
          Protocol: email
  QueueDepthAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmDescription: "Alarm if queue depth grows beyond 10 messages"
      Namespace: "AWS/SQS"
      MetricName: ApproximateNumberOfMessagesVisible
      Dimensions:
        - Name: QueueName
          Value : { "Fn::GetAtt" : [ "MySQSQueue", "QueueName"] }
      Statistic: Sum
      Period: 300
      EvaluationPeriods: 1
      Threshold: 10
      ComparisonOperator: GreaterThanThreshold
      AlarmActions:
        - Ref: AlarmTopic
      InsufficientDataActions:
        - Ref: AlarmTopic

Outputs :
  QueueURL: 
    Description : "URL of newly created SQS Queue"
    Value : { Ref : "MySQSQueue" }
  QueueARN :
    Description : "ARN of newly created SQS Queue"
    Value : { "Fn::GetAtt" : [ "MySQSQueue", "Arn"]}
  QueueName :
    Description : "Name newly created SQS Queue"
    Value : { "Fn::GetAtt" : [ "MySQSQueue", "QueueName"]}
```

有关此示例配置文件中使用的资源的更多信息，请参阅以下参考：
+ [AWS::SQS::Queue](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html)
+ [AWS::SNS::Topic](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-topic.html)
+ [AWS::CloudWatch::Alarm](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html)

创建名为 `options.config` 的单独配置文件，并定义自定义选项设置。

```
option_settings:
  "aws:elasticbeanstalk:customoption":
     VisibilityTimeout : 30
     AlarmEmail : "nobody@example.com"
```

**这些行告诉 Elastic Beanstalk **VisibilityTimeout 从配置文件（我们的示例中**VisibilityTimeout 为 options.config）中获取和**订阅端点属性的值，该**文件包含一个 option\$1settings 部分，其中有一个 aws: elasticbeanstalk: customoption 部分，其中包含包含要使用的实际值的名称-值对。**在以上示例中，这意味着 30 和“nobody@amazon.com”将用于这些值。有关 `Fn::GetOptionSetting` 的更多信息，请参阅 [函数](ebextensions-functions.md)。

# 示例：DynamoDB CloudWatch、和 SNS
<a name="customize-environment-resources-dynamodb"></a>

此配置文件将 DynamoDB 表设置为使用适用于 PHP 的 SDK 2 的基于 PHP 的应用程序的 AWS 会话处理程序。要使用此示例，您必须拥有 IAM 实例配置文件，该文件会添加到环境中的实例，并用来访问 DynamoDB 表。

 您可以在 [DynamoDB 会话支持示例](https://elasticbeanstalk.s3.amazonaws.com/extensions/PHP-DynamoDB-Session-Support.zip)中下载该示例，我们在本步骤会用到这个示例。此示例包含以下文件：
+ 示例应用程序 `index.php`
+ 一个配置文件`dynamodb.config`，用于创建和配置 DynamoDB 表 AWS 和其他资源，并在 Elastic Beanstalk 环境中托管应用程序的 EC2 实例上安装软件
+ 配置文件 `options.config`，该文件会使用此特定安装的特定设置覆盖 `dynamodb.config` 中的默认设置

**`index.php`**

```
<?php

// Include the SDK using the Composer autoloader
require '../vendor/autoload.php';

use Aws\DynamoDb\DynamoDbClient;

// Grab the session table name and region from the configuration file
list($tableName, $region) = file(__DIR__ . '/../sessiontable');
$tableName = rtrim($tableName);
$region = rtrim($region);

// Create a DynamoDB client and register the table as the session handler
$dynamodb = DynamoDbClient::factory(array('region' => $region));
$handler = $dynamodb->registerSessionHandler(array('table_name' => $tableName, 'hash_key' => 'username'));

// Grab the instance ID so we can display the EC2 instance that services the request
$instanceId = file_get_contents("http://169.254.169.254/latest/meta-data/instance-id");
?>
<h1>Elastic Beanstalk PHP Sessions Sample</h1>
<p>This sample application shows the integration of the Elastic Beanstalk PHP
container and the session support for DynamoDB from the AWS SDK for PHP 2.
Using DynamoDB session support, the application can be scaled out across
multiple web servers. For more details, see the
<a href="https://aws.amazon.com/php/">PHP Developer Center</a>.</p>

<form id="SimpleForm" name="SimpleForm" method="post" action="index.php">
<?php
echo 'Request serviced from instance ' . $instanceId . '<br/>';
echo '<br/>';

if (isset($_POST['continue'])) {
  session_start();
  $_SESSION['visits'] = $_SESSION['visits'] + 1;
  echo 'Welcome back ' . $_SESSION['username'] . '<br/>';
  echo 'This is visit number ' . $_SESSION['visits'] . '<br/>';
  session_write_close();
  echo '<br/>';
  echo '<input type="Submit" value="Refresh" name="continue" id="continue"/>';
  echo '<input type="Submit" value="Delete Session" name="killsession" id="killsession"/>';
} elseif (isset($_POST['killsession'])) {
  session_start();
  echo 'Goodbye ' . $_SESSION['username'] . '<br/>';
  session_destroy();
  echo 'Username: <input type="text" name="username" id="username" size="30"/><br/>';
  echo '<br/>';
  echo '<input type="Submit" value="New Session" name="newsession" id="newsession"/>';
} elseif (isset($_POST['newsession'])) {
  session_start();
  $_SESSION['username'] = $_POST['username'];
  $_SESSION['visits'] = 1;
  echo 'Welcome to a new session ' . $_SESSION['username'] . '<br/>';
  session_write_close();
  echo '<br/>';
  echo '<input type="Submit" value="Refresh" name="continue" id="continue"/>';
  echo '<input type="Submit" value="Delete Session" name="killsession" id="killsession"/>';
} else {
  echo 'To get started, enter a username.<br/>';
  echo '<br/>';
  echo 'Username: <input type="text" name="username" id="username" size="30"/><br/>';
  echo '<input type="Submit" value="New Session" name="newsession" id="newsession"/>';
}
?>
</form>
```

**`.ebextensions/dynamodb.config`**

```
Resources:
  SessionTable:
    Type: AWS::DynamoDB::Table
    Properties:
      KeySchema: 
        HashKeyElement:
          AttributeName:
            Fn::GetOptionSetting:
              OptionName : SessionHashKeyName
              DefaultValue: "username"
          AttributeType:
            Fn::GetOptionSetting:
              OptionName : SessionHashKeyType
              DefaultValue: "S"
      ProvisionedThroughput:
        ReadCapacityUnits:
          Fn::GetOptionSetting:
            OptionName : SessionReadCapacityUnits
            DefaultValue: 1
        WriteCapacityUnits:
          Fn::GetOptionSetting:
            OptionName : SessionWriteCapacityUnits
            DefaultValue: 1

  SessionWriteCapacityUnitsLimit:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmDescription: { "Fn::Join" : ["", [{ "Ref" : "AWSEBEnvironmentName" }, " write capacity limit on the session table." ]]}
      Namespace: "AWS/DynamoDB"
      MetricName: ConsumedWriteCapacityUnits
      Dimensions:
        - Name: TableName
          Value: { "Ref" : "SessionTable" }
      Statistic: Sum
      Period: 300
      EvaluationPeriods: 12
      Threshold:
          Fn::GetOptionSetting:
            OptionName : SessionWriteCapacityUnitsAlarmThreshold
            DefaultValue: 240
      ComparisonOperator: GreaterThanThreshold
      AlarmActions:
        - Ref: SessionAlarmTopic
      InsufficientDataActions:
        - Ref: SessionAlarmTopic

  SessionReadCapacityUnitsLimit:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmDescription: { "Fn::Join" : ["", [{ "Ref" : "AWSEBEnvironmentName" }, " read capacity limit on the session table." ]]}
      Namespace: "AWS/DynamoDB"
      MetricName: ConsumedReadCapacityUnits
      Dimensions:
        - Name: TableName
          Value: { "Ref" : "SessionTable" }
      Statistic: Sum
      Period: 300
      EvaluationPeriods: 12
      Threshold:
          Fn::GetOptionSetting:
            OptionName : SessionReadCapacityUnitsAlarmThreshold
            DefaultValue: 240
      ComparisonOperator: GreaterThanThreshold
      AlarmActions:
        - Ref: SessionAlarmTopic
      InsufficientDataActions:
        - Ref: SessionAlarmTopic

  SessionThrottledRequestsAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmDescription: { "Fn::Join" : ["", [{ "Ref" : "AWSEBEnvironmentName" }, ": requests are being throttled." ]]}
      Namespace: AWS/DynamoDB
      MetricName: ThrottledRequests
      Dimensions:
        - Name: TableName
          Value: { "Ref" : "SessionTable" }
      Statistic: Sum
      Period: 300
      EvaluationPeriods: 1
      Threshold: 
        Fn::GetOptionSetting:
          OptionName: SessionThrottledRequestsThreshold
          DefaultValue: 1
      ComparisonOperator: GreaterThanThreshold
      AlarmActions:
        - Ref: SessionAlarmTopic
      InsufficientDataActions:
        - Ref: SessionAlarmTopic

  SessionAlarmTopic:
    Type: AWS::SNS::Topic
    Properties:
      Subscription:
        - Endpoint:
            Fn::GetOptionSetting:
              OptionName: SessionAlarmEmail
              DefaultValue: "nobody@amazon.com"
          Protocol: email

files:
  "/var/app/sessiontable":
    mode: "000444"
    content: |
      `{"Ref" : "SessionTable"}`
      `{"Ref" : "AWS::Region"}`

  "/var/app/composer.json":
    mode: "000744"
    content:
      {
        "require": {
           "aws/aws-sdk-php": "*"
        }
      }

container_commands:
 "1-install-composer":
   command: "cd /var/app; curl -s http://getcomposer.org/installer | php"
 "2-install-dependencies":
   command: "cd /var/app; php composer.phar install"
 "3-cleanup-composer":
   command: "rm -Rf /var/app/composer.*"
```

在示例配置文件中，我们首先创建 DynamoDB 表，并配置该表的主密钥结构和容量单位，以便分配足够的资源提供所要求的吞吐量。接下来，我们为`WriteCapacity`和创建 CloudWatch 警报`ReadCapacity`。我们会创建 SNS 主题，该主题会在警报阈值被突破时将电子邮件发送到“nobody@amazon.com”。

在我们为环境创建和配置 AWS 资源之后，我们需要自定义 EC2 实例。我们使用`files`密钥将 DynamoDB 表的详细信息传递给我们环境中的 EC2 实例，并在文件中`composer.json`为适用于 AWS PHP 的 SDK 2 添加一个 “要求”。最后，我们会运行容器命令安装编辑器和必需的依赖项，然后删除安装程序。

**`.ebextensions/options.config`**

```
option_settings:
  "aws:elasticbeanstalk:customoption":
     SessionHashKeyName                      : username
     SessionHashKeyType                      : S
     SessionReadCapacityUnits                : 1
     SessionReadCapacityUnitsAlarmThreshold  : 240
     SessionWriteCapacityUnits               : 1 
     SessionWriteCapacityUnitsAlarmThreshold : 240
     SessionThrottledRequestsThreshold       : 1
     SessionAlarmEmail                       : me@example.com
```

将该 SessionAlarmEmail 值替换为您想要发送警报通知的电子邮件。`options.config` 文件包含 `dynamodb.config` 中用于定义的部分变量的值。例如，`dynamodb.config` 包含以下行：

```
Subscription:
  - Endpoint:
      Fn::GetOptionSetting:
        OptionName: SessionAlarmEmail
        DefaultValue: "nobody@amazon.com"
```

****这些行告诉 Elastic Beanstalk **SessionAlarmEmail**从配置`options.config`文件（在我们的示例应用程序中）中的值中获取 Endpoint 属性的值，该文件包含一个 option\$1settings 部分，其中有一个 aws: elasticbeanstalk: customoption 部分，其中包含包含要使用的实际值的名称-值对。****在上面的示例中，这意味着**SessionAlarmEmail**将分配该值`nobody@amazon.com`。

有关本示例中使用的 CloudFormation 资源的更多信息，请参阅以下参考资料：
+ [AWS::DynamoDB::Table](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html)
+ [AWS::CloudWatch::Alarm](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html)
+ [AWS::SNS::Topic](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-topic.html)