

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 新增和自訂 Elastic Beanstalk 環境資源
<a name="environment-resources"></a>

您可以自訂包含在您 Elastic Beanstalk 環境中的環境資源。例如，您可以新增 Amazon SQS 佇列和監控佇列深度的警示，或是新增 Amazon ElastiCache 叢集。在部署應用程式版本的同時，您可以在原始碼套件中加入組態檔案，來輕鬆自訂您的環境。

您可以使用[組態檔案中](ebextensions.md)的 `Resources`金鑰，在您的環境中建立和自訂 AWS 資源。組態檔案中定義的資源會新增至用來啟動環境的 CloudFormation 範本。支援所有 CloudFormation [資源類型](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)。

**注意**  
每當您新增不是由 Elastic Beanstalk 管理的資源時，請務必將具有適當許可的使用者政策新增至您的 AWS Identity and Access Management (IAM) 使用者。Elastic Beanstalk 僅提供 Elastic Beanstalk 受管資源的許可的[受管使用者政策](AWSHowTo.iam.managed-policies.md)。

例如，下列的組態檔案在 Elastic Beanstalk 所建立的預設 Auto Scaling 群組中，加入了 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 EC2 Auto Scaling，以發佈訊息至 Amazon 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 使用者指南主題中找到。 [ AWS::SNS::Topic ](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::AutoScalingGroup](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-AWSElasticBeanstalk** [受管使用者政策](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 資料庫執行個體 (如適用)。

在負載平衡的環境中，您可以存取與負載平衡器相關的其他資源。Classic Load Balancer 有一個資源用於負載平衡器，及一個資源用於其連接的安全群組。應用程式和網路負載平衡器還有其他資源，可用於負載平衡器的預設接聽程式、接聽程式規則和目標群組。

**負載平衡環境**
+ `AWSEBLoadBalancer` ([AWS::ElasticLoadBalancing::LoadBalancer](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html)) – 您環境的 classic load balancer。
+ `AWSEBV2LoadBalancer` ([AWS::ElasticLoadBalancingV2::LoadBalancer](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html)) – 您環境的應用程式或 Network Load Balancer。
+ `AWSEBLoadBalancerSecurityGroup` ([AWS::EC2::SecurityGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html)) – Elastic Beanstalk 為負載平衡器建立的安全群組名稱，僅適用 [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC) 中。在預設 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)) – 將請求路由至一或多個登錄目標 (例如 Amazon EC2 執行個體) 的 Elastic Load Balancing 目標群組。

工作者環境具備用於 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>

我們已從 引入組態檔案金鑰`Resources`， CloudFormation 例如 `files`、 和 `packages`。Elastic Beanstalk 會將組態檔案的內容新增至支援您環境的 CloudFormation 範本，因此您可以使用其他 CloudFormation 區段在組態檔案中執行進階任務。

**Topics**
+ [Parameters](#ebextensions-otherkeys-parameters)
+ [輸出](#ebextensions-otherkeys-outputs)
+ [映射項目](#ebextensions-otherkeys-mappings)

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

參數可替代 Elastic Beanstalk 自己的[自訂選項](configuration-options-custom.md)，可用於定義您在組態檔案他處使用的值。如同自訂選項，您可使用參數在單一位置收集使用者可設定的值。與自訂選項不同，您無法使用 Elastic Beanstalk 的 API 來設定參數值，而且您可以在範本中定義的參數數量受到限制 CloudFormation。

您可能想要使用參數的一個原因是讓您的組態檔案成為 CloudFormation 範本的兩倍。如果您使用參數而非自訂選項，則可以使用組態檔案在 中建立 CloudFormation 與其堆疊相同的資源。例如，您的組態檔案可將 Amazon EFS 檔案系統新增至您的環境進行測試，然後使用相同檔案來建立未繫結至您環境生命週期的獨立檔案系統，供生產使用。

下列範例說明如何使用參數在組態檔案上方收集使用者可設定的值。

**Example [Loadbalancer-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 主題，並以 CloudFormation 名稱 將其 ARN 匯出至 `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 [Loadbalancer-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 Beanstalk 支援 CloudFormation 函數 (`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 Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC)、EC2 classic 或在自訂 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 Balancing 與 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>

下列範例將 Amazon ElastiCache 叢集新增至 EC2-Classic 和 EC2-VPC (預設和自訂 [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon 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 安全群組的輸入規則，僅允許 ElastiCache 安全群組 (`MyCacheSecurityGroup`) 和 Elastic Beanstalk 安全群組 (`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::ElastiCache: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 從組態檔案 （範例中的 options.config) 中取得 **CacheNodeType、NumCacheNodes 和 Engine** 屬性的值，其中包含具有 **aws：elasticbeanstalk：customoption** 區段的 option\$1settings 區段，其中包含要使用的實際值之名稱值對。 **CacheNodeType NumCacheNodes** 上述範例表示這些值為 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 啟動執行個體的情境。本範例的所有屬性都是最低要求的屬性，各個資源類型均必須設定。如需預設 VPC 的詳細資訊，請參閱[您的預設 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 叢集資源的名稱 (`MyElastiCache`)、宣告其類型，並設定叢集屬性，藉此建立 ElastiCache 叢集。本範例參考的安全群組資源 ID，均由我們於此組態檔案中建立並定義。

接著，我們建立 EC2 安全群組。我們定義此資源的名稱、宣告其類型、新增說明，並設定安全群組的輸入規則，僅允許 Elastic Beanstalk 安全群組 (`AWSEBSecurityGroup`) 內的執行個體進行存取。(參數名稱 `AWSEBSecurityGroup` 是 Elastic Beanstalk 提供的固定資源名稱。您必須將 `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 叢集資源的名稱 (`MyElastiCache`)、宣告其類型，並設定叢集屬性，藉此建立 ElastiCache 叢集。本範例屬性參考 ElastiCache 叢集的子網路群組名稱，以及由我們於此組態檔案建立並定義的安全群組資源 ID。

接著，我們建立 EC2 安全群組。我們定義此資源的名稱、宣告其類型、新增說明和 VPC ID，並設定安全群組的輸入規則，僅允許 Elastic Beanstalk 安全群組 (`AWSEBSecurityGroup`) 內的執行個體進行存取。(參數名稱 `AWSEBSecurityGroup` 是 Elastic Beanstalk 提供的固定資源名稱。您必須將 `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` 命名，並定義自訂選項設定。

**注意**  
在下列範例中，請使用您自己的子網路和 VPC，取代範例 `CacheSubnets` 和 `VpcId` 的值。

```
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 和 CloudWatch](https://elasticbeanstalk.s3.amazonaws.com/extensions/SNS.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 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。

建立組態檔案 (例如 sqs.config)，此檔案是用來定義資源。在此範例中，我們會建立 SQS 佇列，並定義 `VisbilityTimeout` 資源中的 `MySQSQueue` 屬性。然後，我們會建立 SNS `Topic`，並指定在警示觸發時，傳送電子郵件到 `someone@example.com`。最後，我們會建立 CloudWatch 警示，此警示會在佇列增加到超過 10 筆訊息時觸發。在 `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 從組態檔案 （範例中的 options.config) 中的 **VisibilityTimeout ** 和訂閱端點值取得 VisibilityTimeout 和訂閱端點屬性的值，該組態檔案包含具有 **aws：elasticbeanstalk：customoption** 區段的 option\$1settings 區段，其中包含包含要使用的實際值的名稱值對。 **VisibilityTimeout ** 在上列的範例中，這表示將會使用 30 和「nobody@amazon.com」來做為值。如需有關 `Fn::GetOptionSetting` 的詳細資訊，請參閱 [函數](ebextensions-functions.md)。

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

此組態檔案會使用適用於 PHP 2 的 AWS SDK，將 DynamoDB 資料表設定為 PHP 型應用程式的工作階段處理常式。欲使用此範例，您必須具備 IAM 執行個體描述檔，本描述檔會新增至您環境的執行個體，並可用於存取 DynamoDB 資料表。

 您可從 [DynamoDB 工作階段支援範例](https://elasticbeanstalk.s3.amazonaws.com/extensions/PHP-DynamoDB-Session-Support.zip)下載本步驟要使用的範本。本範本內含下列檔案：
+ 範例應用程式 `index.php`
+ 組態檔案 ，用於建立和設定 DynamoDB 資料表和其他 AWS 資源`dynamodb.config`，並在 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` 和 `ReadCapacity` 的 CloudWatch 警示。我們會建立 SNS 主題，若超過警示閾值，此主題會傳送電子郵件至「nobody@amazon.com」。

為環境建立和設定 AWS 資源之後，我們需要自訂 EC2 執行個體。我們使用 `files`金鑰將 DynamoDB 資料表的詳細資訊傳遞至環境中的 EC2 執行個體，並在適用於 PHP 2 的 AWS SDK 的 `composer.json` 檔案中新增「需要」。最後，我們執行容器命令來安裝 Composer 和所需依存項目，然後移除安裝程式。

**`.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 自組態檔案 (在我們的範例應用程式為 `options.config`) 中的 **SessionAlarmEmail** 值，取得 **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)