| « PreviousNext » | |
![]() ![]() ![]() | Did this page help you? Yes | No | Tell us about it... |
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 Amazon 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 if you have deployed your application using an instance profile, you can check the Server tab in the Edit Configuration window in the Elastic Beanstalk console. For instructions, see Instance Profiles. To learn more about instance profiles, see Granting Permissions to Users and Services Using IAM Roles. 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, and you may be charged for using these resources. 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.
Eb is a command line interface that enables you to deploy applications quickly and more easily using Git. 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
Install the following software onto your local computer:
Linux/Unix/MAC
Download and unzip the Elastic Beanstalk command line tools package at the AWS Sample Code & Libraries website.
Git 1.6.6 or later. To download Git, go to http://git-scm.com/.
Ruby version 1.8.7 or later. To view and download Ruby clients, go to http://www.ruby-lang.org/en/.
Python 2.7 or 3.0.
Windows
Git 1.6.6 or later. To download Git, go to http://git-scm.com/.
PowerShell 2.0.
Note
Windows 7 and Windows Server 2008 R2 come with PowerShell 2.0. If you are running an earlier version of Windows, you can download PowerShell 2.0. Visit http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx for more details.
Initialize your Git repository.
git init .
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, you can set your PATH to the location of eb. The following table shows an example for Linux/UNIX and Windows.
| On Linux and UNIX | On Windows |
|---|---|
$ export PATH=$PATH:
|
C:\> set PATH=%PATH%;
|
To configure AWS Elastic Beanstalk
From your directory where you created your local repository, type the following command.
eb init
When you are prompted for the AWS access key, type your access key. To get your access key information, go to Access Credentials.
Enter your AWS Access Key ID (current value is "AKIAIOSFODNN7EXAMPLE"):
When you are prompted for the AWS secret key, type your secret key. To get your secret key information, go to Access Credentials.
Enter your AWS Secret Access Key (current value is "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"):
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).
When you are prompted for the AWS Elastic Beanstalk application name, type the name of the application.
AWS Elastic Beanstalk auto-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 quotes.
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.
When you are prompted for the solution stack, type the number of the solution stack you want. For this example, we'll use 64bit Amazon Linux running PHP 5.4.
When you are prompted to create an Amazon RDS database, type y or
n. For this example, we'll type
n.
Create RDS instance? [y/n]: n
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.
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.
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:
Creates an application using the application name you specified.
Launches an environment using the environment name you specified that provisions the AWS resources to host the application.
Deploys the application into the newly created environment.
Use the start command to create and deploy a sample application.
To create the application
From your directory where you created your local repository, type the following command.
eb start
This process may take several minutes to complete. AWS Elastic Beanstalk will provide status updates during the process. If at any time you want to stop polling for status updates, press Ctrl+C. Once the environment status is Green, AWS Elastic Beanstalk will output a URL for 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
From your 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.
Copy and paste the URL into your web browser to view your 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
You can download the sample that we'll use in this step at DynamoDB Session Support Example.
To update the application
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>
Create an .ebextensions directory in the top-level directory of your
source bundle.
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:
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.
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.
Create an application version matching your local repository and deploy to the Elastic Beanstalk environment if specified.
git aws.push
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.