AWS Elastic Beanstalk
Developer Guide (API Version 2010-12-01)
Did this page help you?  Yes | No |  Tell us about it...
« PreviousNext »
View the PDF for this guide.Go to the AWS Discussion Forum for this product.Go to the Kindle Store to download this guide in Kindle format.

Example: DynamoDB, CloudWatch, and SNS

This section walks you through deploying a sample application to AWS Elastic Beanstalk using eb (an updated command line interface) and Git, and then updating your AWS Elastic Beanstalk to add an DynamoDB table to the Elastic Beanstalk environment. The configuration file sets up the DynamoDB table as a session handler for a PHP-based application using the AWS SDK for PHP 2. To use this example, you must have an IAM instance profile, which is added to the instance(s) in your environment and used to access the DynamoDB table. If you are unsure whether you have deployed your application using an instance profile, click Instances on the Configuration page in the Elastic Beanstalk console. For instructions, see Configuring Amazon EC2 Server Instances with AWS Elastic Beanstalk. To learn more about instance profiles, see Using AWS Elastic Beanstalk with AWS Identity and Access Management (IAM) and Using IAM Roles with AWS Elastic Beanstalk. To see an example creating a custom policy for DynamoDB using instance profiles, see Example: Granting Permissions to AWS Elastic Beanstalk Applications to Access DynamoDB.

Note

This example creates AWS resources, which you may be charged for. For more information about AWS pricing, go to http://aws.amazon.com/pricing/. Some services are part of the AWS Free Usage Tier. If you are a new customer, you may test drive these services for free. Go to http://aws.amazon.com/free/ for more information.

Step 1: Set Up Your Git Repository

Eb is a command line interface that you can use with Git to deploy applications quickly and more easily. Eb is available as part of the Elastic Beanstalk command line tools package. Follow the steps below to install eb and initialize your Git repository.

To install eb, its prerequisite software, and initialize your Git repository

  1. Install the following software onto your local computer:

    1. Linux/Unix/MAC

    2. Windows

  2. Initialize your Git repository.

    git init .

Step 2: Configure AWS Elastic Beanstalk

AWS Elastic Beanstalk needs the following information to deploy an application:

  • AWS access key ID

  • AWS secret key

  • Service region

  • Application name

  • Environment name

  • Solution stack

Use the init command, and AWS Elastic Beanstalk will prompt you to enter this information. If a default value is available, and you want to use it, press Enter.

Before you use eb, set your PATH to the location of eb. The following table shows an example for Linux/UNIX and Windows.

In Linux and UNIXIn Windows
$ export PATH=$PATH:<path to unzipped eb CLI package>/eb/linux/python2.7/

If you are using Python 3.0, the path will include python3 rather than python2.7.

C:\> set PATH=%PATH%;<path to unzipped eb CLI package>\eb\windows\

To configure AWS Elastic Beanstalk

  1. From the directory where you created your local repository, type the following command:

    eb init
  2. When you are prompted for the access key ID, type your access key ID. To get your access key ID, see How Do I Get Security Credentials? in the AWS General Reference.

    Enter your AWS Access Key ID (current value is "AKIAIOSFODNN7EXAMPLE"): 
  3. When you are prompted for the secret access key, type your secret access key. To get your secret access key, see How Do I Get Security Credentials? in the AWS General Reference.

    Enter your AWS Secret Access Key (current value is "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"): 
  4. When you are prompted for the AWS Elastic Beanstalk region, type the number of the region. For information about this product's regions, go to Regions and Endpoints in the Amazon Web Services General Reference. For this example, we'll use US East (Virginia).

  5. When you are prompted for the AWS Elastic Beanstalk application name, type the name of the application. AWS Elastic Beanstalk generates an application name based on the current directory name if an application name has not been previously configured. In this example, we use HelloWorld.

    Enter an AWS Elastic Beanstalk application name (auto-generated value is "windows"): HelloWorld

    Note

    If you have a space in your application name, make sure you do not use quotation marks.

  6. When you are prompted for the AWS Elastic Beanstalk environment name, type the name of the environment. AWS Elastic Beanstalk automatically creates an environment name based on your application name. If you want to accept the default, press Enter.

    Enter an AWS Elastic Beanstalk environment name (current value is "HelloWorld-env"): 

    Note

    If you have a space in your application name, make sure you do not have a space in your environment name.

  7. When you are prompted for the solution stack, type the number of the solution stack you want. For more information about solution stacks, see Supported Platforms. For this example, we'll use 64bit Amazon Linux running PHP 5.4.

  8. When you are prompted to create an Amazon RDS database, type y or n. For more information about using Amazon RDS, see Using AWS Elastic Beanstalk with Amazon RDS. For this example, we'll type n.

    Create RDS instance? [y/n]: n
  9. When you are prompted to enter your instance profile name, you can choose to create a default instance profile or use an existing instance profile. Using an instance profile enables IAM users and AWS services to gain access to temporary security credentials to make AWS API calls. Using instance profiles prevents you from having to store long-term security credentials on the EC2 instance. For more information about instance profiles, see Granting Permissions to Users and Services Using IAM Roles. For this example, we'll use Create a default instance profile.

    You should see a confirmation that your AWS Credential file was successfully updated.

After configuring AWS Elastic Beanstalk, you are ready to deploy a sample application.

If you want to update your AWS Elastic Beanstalk configuration, you can use the init command again. When prompted, you can update your configuration options. If you want to keep any previous settings, press the Enter key.

Step 3: Create an Application

Next, you need to create and deploy a sample application. For this step, you use a sample application that is already prepared. AWS Elastic Beanstalk uses the configuration information you specified in the previous step to do the following:

  • Create an application using the application name you specified.

  • Launch an environment using the environment name you specified that provisions the AWS resources to host the application.

  • Deploy the application into the newly created environment.

Use the start command to create and deploy a sample application.

To create the application

  • From the directory where you created your local repository, type the following command:

    eb start

It may take several minutes to complete this process. AWS Elastic Beanstalk provides status updates during the process. If at any time you want to stop polling for status updates, press Ctrl+C. When the environment status is Green, AWS Elastic Beanstalk outputs a URL for the application.

Step 4: View the Application

In the previous step, you created an application and deployed it to AWS Elastic Beanstalk. After the environment is ready and its status is Green, AWS Elastic Beanstalk provides a URL to view the application. In this step, you can check the status of the environment to make sure it is set to Green and then copy and paste the URL to view the application.

Use the status command to check the environment status, and then use the URL to view the application.

To view the application

  1. From the directory where you created your local repository, type the following command:

    eb status --verbose

    AWS Elastic Beanstalk displays the environment status. If the environment is set to Green, AWS Elastic Beanstalk displays the URL for the application. If you attached an RDS DB instance to your environment, your RDS DB information is displayed.

  2. Copy and paste the URL into your web browser to view your application.

Step 5: Update the Application

Next, we add the files for the sample application and configuration files that will set up AWS resources that the application depends on.

  • The sample application, index.php

  • A configuration file, dynamodb.config, to create and configure a DynamoDB table and other AWS resources as well as install software on the EC2 instances that host the application in an AWS Elastic Beanstalk environment

  • An options setting file, options.config, that overrides the defaults in dynamodb.config with specific settings for this particular installation

Note

Configuration files should conform to YAML or JSON formatting standards. For example, indentation is critical to the proper interpretation of YAML. For more information, go to http://www.yaml.org/start.html or http://www.json.org, respectively. For more information about using configuration files to deploy an application to AWS Elastic Beanstalk, see Using Configuration Files.

You can download the sample that we'll use in this step at DynamoDB Session Support Example.

To update the application

  1. In the directory where you created your local repository, use your favorite text editor to create an index.php file and paste the following PHP code.

    <?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="http://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>
    
  2. Create an .ebextensions directory in the top-level directory of your source bundle.

  3. Create a configuration file named dynamodb.config, paste the code in the listing below, and save the file in the .ebextensions top-level directory of your source bundle.

    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.*"
       			

    In the sample configuration file, we first create the DynamoDB table and configure the primary key structure for the table and the capacity units to allocate sufficient resources to provide the requested throughput. Next, we create CloudWatch alarms for WriteCapacity and ReadCapacity. We create an SNS topic that sends email to "nobody@amazon.com" if the alarm thresholds are breached.

    After we create and configure our AWS resources for our environment, we need to customize the EC2 instances. We use the files key to pass the details of the DynamoDB table to the EC2 instances in our environment as well as add a "require" in the composer.json file for the AWS SDK for PHP 2. Finally, we run container commands to install composer, the required dependencies, and then remove the installer. The example snippet looks like the following.

    For more information about the resources used in this example, see the following references:

  4. Create a configuration file named options.config. Replace <email here> with the email where you want alarm notifications sent, and save the file in the .ebextensions top-level directory of your source bundle.

     option_settings:
      "aws:elasticbeanstalk:customoption":
         SessionHashKeyName                      : username
         SessionHashKeyType                      : S
         SessionReadCapacityUnits                : 1
         SessionReadCapacityUnitsAlarmThreshold  : 240
         SessionWriteCapacityUnits               : 1 
         SessionWriteCapacityUnitsAlarmThreshold : 240
         SessionThrottledRequestsThreshold       : 1
         SessionAlarmEmail                       : <email here>
    
    

    After you've made your changes, your file should look like the following.

     option_settings:
      "aws:elasticbeanstalk:customoption":
         SessionHashKeyName                      : username
         SessionHashKeyType                      : S
         SessionReadCapacityUnits                : 1
         SessionReadCapacityUnitsAlarmThreshold  : 240
         SessionWriteCapacityUnits               : 1 
         SessionWriteCapacityUnitsAlarmThreshold : 240
         SessionThrottledRequestsThreshold       : 1
         SessionAlarmEmail                       : <email here>
    
    

    The options.config file contains the values used for some of the variables defined in dynamodb.config. For example, dynamodb.config contains the following lines.

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

    These lines that tell AWS Elastic Beanstalk to get the value for the Endpoint property from the SessionAlarmEmail value in a config file (options.config in our sample application) that contains an option_settings section with an aws:elasticbeanstalk:customoption section that contains a name-value pair that contains the actual value to use. In the example above, this means SessionAlarmEmail would be assigned the value nobody@amazon.com.

  5. Add your files to your local Git repository, and then commit your change.

    git add .
    git commit -m "eb configuration"

    Note

    For information about Git commands, go to Git - Fast Version Control System.

  6. Create an application version matching your local repository and deploy to the Elastic Beanstalk environment if specified.

    git aws.push
  7. Use the eb status --verbose command to check your environment status. When your environment is green and ready, refresh your web browser to view your updated application.