opsworks amazon

232
AWS OpsWorks User Guide API Version 2013-02-18

Upload: sysborg

Post on 03-Jan-2016

396 views

Category:

Documents


9 download

DESCRIPTION

amazon opsworks

TRANSCRIPT

Page 1: Opsworks amazon

AWS OpsWorksUser Guide

API Version 2013-02-18

Page 2: Opsworks amazon

Amazon Web Services

AWS OpsWorks User Guide

Page 3: Opsworks amazon

AWS OpsWorks: User GuideAmazon Web ServicesCopyright © 2013 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

All other trademarks not owned by Amazon are the property of their respective owners, who may or maynot be affiliated with, connected to, or sponsored by Amazon.

AWS OpsWorks User Guide

Page 4: Opsworks amazon

What is AWS OpsWorks? ....................................................................................................................... 1How Does AWS OpsWorks Work? ......................................................................................................... 3Getting Started Walkthroughs ................................................................................................................. 6Walkthrough: Deploy a Web App and Learn AWS OpsWorks Basics ..................................................... 6

Step 1. Create a stack and deploy an app ..................................................................................... 7Step 2. Update the server application to a new version that uses a database ............................ 22Step 3. Scale out by adding another server instance and a load balancer ................................. 35Step 4. Add a monitoring server .................................................................................................. 39Step 5. Clean up to avoid unwanted costs .................................................................................. 41What's Next? ............................................................................................................................... 42

Walkthrough: Deploying a PHP Application that Leverages the AWS SDK for PHP, Amazon S3,and Custom Metadata .......................................................................................................................... 43

Step 1. Create the Amazon S3 bucket and instance profile to use in your app ........................... 44Step 2. Create the stack and set it up to use the cookbook repository ....................................... 45Step 3. Add the PHP App Server and MySQL layers and give them custom recipes ................. 47Step 4. Add and start instances for the PHP App Server and MySQL layers .............................. 50Step 5. Add the app and deploy it ............................................................................................... 51Step 6. Try the app ...................................................................................................................... 51Step 7. Clean up to avoid unwanted costs .................................................................................. 52

Stacks ................................................................................................................................................... 53Create a New Stack .............................................................................................................................. 54Update a Stack ..................................................................................................................................... 56Clone a Stack ....................................................................................................................................... 57Run Stack Commands .......................................................................................................................... 58Use Custom JSON to Modify the Stack Configuration JSON ............................................................... 60Shut Down a Stack ............................................................................................................................... 61Layers ................................................................................................................................................... 64Layer Basics ......................................................................................................................................... 65

How to Create a Layer ................................................................................................................. 65How to Edit a Layer ..................................................................................................................... 66Using Auto Healing to Replace Failed Instances ........................................................................ 67How to Delete a Layer ................................................................................................................. 68

Load Balancer Layers ........................................................................................................................... 70Elastic Load Balancing ................................................................................................................ 70HAProxy Layer ............................................................................................................................ 73

MySQL Layer ........................................................................................................................................ 77Application and Web Server Layers ...................................................................................................... 77

Node.js App Server Layer ........................................................................................................... 78PHP App Server Layer ................................................................................................................ 78Rails App Server Layer ............................................................................................................... 78Static Web Server Layer .............................................................................................................. 79

Custom Layers ...................................................................................................................................... 79Other Layers ......................................................................................................................................... 87

Ganglia Layer .............................................................................................................................. 88Memcached ................................................................................................................................. 90

Instances .............................................................................................................................................. 91Adding an Instance to a Layer .............................................................................................................. 91Manually Starting, Stopping, and Rebooting 24/7 Instances ................................................................ 94Changing Instance Properties .............................................................................................................. 95Deleting Instances ................................................................................................................................ 96Managing Load with Time-based and Load-based Instances .............................................................. 98Using SSH to Communicate with an Instance .................................................................................... 103Apps ................................................................................................................................................... 109Adding Apps ....................................................................................................................................... 109Deploying Apps ................................................................................................................................... 113Using Deploy Keys .............................................................................................................................. 115Using Custom Domains ...................................................................................................................... 115Running Multiple Applications on an Application Server .................................................................... 117

API Version 2013-02-184

AWS OpsWorks User Guide

Page 5: Opsworks amazon

Using SSL ........................................................................................................................................... 117Cookbooks and Recipes ..................................................................................................................... 122Cookbook Repositories ...................................................................................................................... 123Cookbook Components ...................................................................................................................... 124

Attributes ................................................................................................................................... 124Templates .................................................................................................................................. 126Recipes ..................................................................................................................................... 128

Installing Custom Cookbooks ............................................................................................................. 130Updating Custom Cookbooks ............................................................................................................. 132Executing Recipes .............................................................................................................................. 133

AWS OpsWorks Lifecycle Events .............................................................................................. 133Automatically Running Recipes ................................................................................................. 134Manually Running Recipes ........................................................................................................ 136

Customizing AWS OpsWorks ............................................................................................................. 138Customizing AWS OpsWorks Configuration by Overriding Attributes ................................................ 139

Attribute Precedence ................................................................................................................. 140Overriding Attributes Using Custom JSON ............................................................................... 141Overriding AWS OpsWorks Attributes Using Custom Cookbook Attributes .............................. 143

Extending AWS OpsWorks Configuration Files Using Custom Templates ......................................... 144Extending a Built-in Layer ................................................................................................................... 144

Using Recipes to Run Scripts ................................................................................................... 145Using Chef Deployment Hooks ................................................................................................. 145Running Cron Jobs .................................................................................................................... 146Installing and Configuring Packages ......................................................................................... 147

Stack Configuration and Deployment JSON ....................................................................................... 147Troubleshooting .................................................................................................................................. 153Monitoring ........................................................................................................................................... 154Security and Permissions ................................................................................................................... 158Granting Users Permissions to Work with AWS OpsWorks ................................................................ 159

Setting an IAM User's Public SSH Key ...................................................................................... 161Setting Permissions When Creating a Stack ...................................................................................... 162Specifying Permissions for Apps Running on EC2 instances ............................................................. 163Appendix A: AWS OpsWorks Layer Reference .................................................................................. 165HAProxy Layer .................................................................................................................................... 165MySQL Layer ...................................................................................................................................... 167Web Server Layers ............................................................................................................................. 168

Node.js App Server Layer ......................................................................................................... 168PHP App Server Layer .............................................................................................................. 169Rails App Server Layer ............................................................................................................. 170Static Web Server Layer ............................................................................................................ 172

Custom Layer ..................................................................................................................................... 173Other Layers ....................................................................................................................................... 174

Ganglia Layer ............................................................................................................................ 174Memcached Layer ..................................................................................................................... 175

Appendix B: Instance Agent CLI ......................................................................................................... 177agent_report ...................................................................................................................................... 178get_json .............................................................................................................................................. 178instance_report ................................................................................................................................... 181list_commands .................................................................................................................................... 182run_command ..................................................................................................................................... 182show_log ............................................................................................................................................ 183stack_state ......................................................................................................................................... 184Appendix C: SDKs and Command Line Tools ..................................................................................... 187Appendix D: AWS OpsWorks Attribute Reference .............................................................................. 189Stack Configuration and Deployment JSON Attributes ....................................................................... 190

opsworks Attributes ................................................................................................................... 191applications Attributes ...................................................................................................... 191instance Attributes ........................................................................................................... 191

API Version 2013-02-185

AWS OpsWorks User Guide

Page 6: Opsworks amazon

layers Attributes ............................................................................................................... 193rails_stack Attributes ........................................................................................................ 196Other Top-level opsworks Attributes ................................................................................. 196

opsworks_custom_cookbooks Attributes .................................................................................. 197dependencies Attributes ............................................................................................................ 198ganglia Attributes ....................................................................................................................... 198mysql Attributes ......................................................................................................................... 198passenger Attributes ................................................................................................................. 199opsworks_bundler Attributes ..................................................................................................... 199deploy Attributes ........................................................................................................................ 199Other Top-Level Attributes ......................................................................................................... 203

Built-in Recipe Attributes .................................................................................................................... 204apache2 Attributes .................................................................................................................... 205haproxy Attributes ..................................................................................................................... 210memached Attributes ................................................................................................................ 213mysql Attributes ......................................................................................................................... 214nginx Attributes .......................................................................................................................... 218passenger_apache2 Attributes .................................................................................................. 221ruby Attributes ........................................................................................................................... 223unicorn Attributes ...................................................................................................................... 223

History ................................................................................................................................................ 226

API Version 2013-02-186

AWS OpsWorks User Guide

Page 7: Opsworks amazon

What is AWS OpsWorks?

AWS OpsWorks is an application management service that provides an integrated experience foroverseeing the complete application lifecycle. With AWS OpsWorks, you can provision AWS resources,supervise their configuration, deploy applications to those resources, and monitor their health.

AWS OpsWorks uses automation to simplify operations.You create blueprints that define your instanceand its software configuration, including installation scripts and initialization tasks.You can automatescaling out your instances and determine the configuration of like instances all at once instead of one ata time.You can then specify how to deploy, scale, and maintain your applications.You can let AWSOpsWorks perform many operational tasks for you or add your own custom actions.

AWS OpsWorks supports a wide variety of application architectures. It can work with any software thathas a scripted installation. Because AWS OpsWorks uses the Opscode Chef framework, you can useexisting recipes or leverage hundreds of community-built configurations.

In AWS OpsWorks, you start by creating a stack, which is a container for all the Amazon EC2 instancesand other resources that you want to manage together. Within a stack, you define layers that describehow to provision and configure instances. A stack can have multiple layers.Within a layer, you can specify,for example, packages to install, Amazon EC2 security groups to add, and Elastic IP addresses to assign.This structure gives you the flexibility to define different instance configurations.

After you add a layer, you pre-provision the instances that you will launch by using the layer's configurationdescription.You can pre-provision your instances either as on-demand instances that you can manuallystart and stop or as auto-scaled instances that AWS OpsWorks runs for you according to a schedule ora load threshold.

AWS OpsWorks also helps you manage your own applications with apps.You define an app by specifyingwhat layer it applies to, the code to run, and some basic configuration.You then deploy the app to theinstances on the layer.

AWS OpsWorks uses its own Chef recipes to configure the instances on a stack. Chef Solo runs on everyinstance, and AWS OpsWorks sends commands to each instance to run recipes that set up, configure,and shut down the instance.You can extend these actions with your own custom recipes.You can alsorun your custom recipes on a specific instance or on all instances in your stack.

To help you monitor and debug your instance configurations and app deployments, AWS OpsWorksprovides detailed logs and performance and health monitoring with Amazon CloudWatch metrics and theGanglia monitoring system.

With AWS OpsWorks, you can automate configuration, deployment, auto scaling, monitoring, and more.

API Version 2013-02-181

AWS OpsWorks User Guide

Page 8: Opsworks amazon

The following video walks you through the example presented in this guide: Getting Started with AWSOpsWorks

Use these links to start learning and using AWS OpsWorks:

• Read a brief summary of AWS application management services, including a side-by-side comparisonof AWS OpsWorks with the other services.

• Learn about how AWS OpsWorks works (p. 3). An understanding of some basic concepts and theessentials of what this service does will make using AWS OpsWorks easier.

• Test drive AWS OpsWorks by following Walkthrough: Deploy a Web App and Learn AWS OpsWorksBasics (p. 6), or check out the walkthrough video on this page.

• Chef cookbooks are the way that you customize how AWS OpsWorks manages your instances. Learnmore about how to use Chef with AWS OpsWorks (p. 122).

• When you are up to speed on the basics, see the rest of this guide to learn more about Stacks (p. 53),Layers (p. 64), Instances (p. 198), and Apps (p. 198).

• If you are a developer, see the AWS OpsWorks API reference and the following AWS SDKs:

• AWS SDK for Java

• AWS SDK for .NET

• AWS SDK for PHP 2

• AWS SDK for Ruby

• AWS SDK for Node.js

• Now that you are using AWS OpsWorks, learn how to give access to other users and manage theinstance profile on your instances (p. 158).

API Version 2013-02-182

AWS OpsWorks User Guide

Page 9: Opsworks amazon

How Does AWS OpsWorks Work?

The basic unit of AWS OpsWorks is the stack. An AWS OpsWorks stack is basically a container for a setof Amazon EC2 instances (with related resources such as Amazon EBS volumes, and Elastic IP addresses)that have a common purpose or should be logically be managed as a group. For example, a stack thatsupports a PHP application could consist of a group of PHP application servers with a backend databaseserver running behind a load balancer. Incorporating these into a stack simplifies the process of creatingand managing the instances, deploying applications to PHP application servers, monitoring performance,and so on.

Each stack contains one or more layers, which are blueprints that AWS OpsWorks uses to configureAmazon EC2 instances for a particular purpose. For example, a PHP App Server layer configures instancesto function as PHP application servers. Stacks and layers make it easy to launch Amazon EC2 instanceswith the exact configuration that you want, and ensure that the instances work together correctly.

Using LayersAfter you create a stack, you define the stack's functionality by adding one or more layers. AWS OpsWorksincludes the following built-in layers:

• Application servers: Rails App Server, PHP App Server, Node.js App Server, Static Web Server

• Database master: MySQL

• Load balancer: HAProxy and Elastic Load Balancing

• Monitoring master: Ganglia

• Memory object cache: Memcached

If the built-in layers don't quite meet your requirements, you can customize or extend them by modifyingthe default configuration, installing additional packages, attaching Amazon EBS volumes, assigning ElasticIP addresses, and anything else you want. If that's not enough, you can create fully custom layers forcomplete control over configuring the layer's instances, deploying applications, and more.

API Version 2013-02-183

AWS OpsWorks User GuideUsing Layers

Page 10: Opsworks amazon

Using InstancesAfter you create a layer, you add one or more instances that conform to the layer's specifications.Youcan also specify an IAM profile that governs how the layer's instances access AWS resources such asAmazon S3.

When you add an instance to a layer, you are creating a specification; there is no Amazon EC2 instanceuntil you start it. When you stop an instance, AWS OpsWorks terminates the associated Amazon EC2instance, but the instance remains. Restarting a stopped instance creates and configures a new AmazonEC2 instance.

The way an instance starts depends on its scaling type.

• 24/7 instances are started manually and run until you terminate them.

• Load-based instances are started and stopped by AWS OpsWorks based on the associated layer'sload; they allow your stack to automatically adjust the number of online instances based on currentload.

If the load exceeds a user-specified Up threshold, AWS OpsWorks starts additional load-based instances.If the load falls below a user-specified Down threshold, AWS OpsWorks stops some load-basedinstances.

• Time-based instances run on a specified daily and weekly schedule; they allow your stack to adjustthe number of instances to accommodate predictable usage patterns.

AWS OpsWorks starts a time-based instance at the beginning of each user-specified On period andstops the instance at the end of the period.

For example, if your stack includes a PHP App Server and you want to manually start and stop theinstances, add an appropriate number of 24/7 instances to the layer and start them. If demand increases,you can add more instances or stop some if demand flags.. If you don't want to monitor the load andmanually adjust the number of instances, you can use an appropriate combination of 24/7, time-based,and load-based instances and then let OpsWorks handle the task for you.

Using Lifecycle EventsAWS OpsWorks interacts with a layer's instances at key points in its lifecycle, called lifecycle events.Every layer has a set of built-in recipes for each lifecycle event that, for example, install and configure anapplication server or deploy applications to the server.You can attach custom recipes to a layer's lifecycleevents to customize configurations, install additional packages, and so on. AWS OpsWorks has fivelifecycle events:

• Setup–Triggered at instance boot and runs only at that time. Add a recipe to a layer's setup event toinstall and configure software and services initially on the layer's instances. For example, you couldinstall and configure a software package such as MongoDB.

• Configure–Triggered when a new instance comes online or an existing instance goes offline. Add arecipe a layer's configure event to reconfigure services, for example, to include the IP addresses ofnew instances.

• Deploy–Triggered when you deploy an app. Add a recipe to a layer's deploy event to customize appdeployment. For example, if a PHP application needs to connect to a database, you could attach arecipe to your MySQL layer's deploy event that creates the appropriate tables for your application.You could attach another recipe to your PHP App Server layer's deploy event to update the serverconfiguration so that it can access the MySQL tables.

API Version 2013-02-184

AWS OpsWorks User GuideUsing Instances

Page 11: Opsworks amazon

• Undeploy–Triggered when you delete an app. Add a recipe to a layers undeploy event to performcleanup tasks when an app is deleted.

• Shutdown–Triggered when an instance is stopped before shutdown. Add a recipe to a layer's shutdownevent to perform cleanup tasks or notify external endpoints.

When a lifecycle event of an instance occurs, AWS OpsWorks runs each layer's built-in recipes first andthen any custom recipes you assigned to the particular layer and event.You can also manually runspecified recipes at any time on any or all of a stack's instances, typically to perform a task that doesn'tmap to a lifecycle event, such as backing up an instance.

Using AppsThe AWS OpsWorks application server layers support platforms such as Ruby on Rails and PHP. AnOpsWorks app represents an application that runs on an application server. The application code andany related files are is stored in a repository. An app is basically a specification that provides the informationneeded to access the repository, identifies which layer to install the app on, and includes basic configurationdata such as the virtual host configuration.

When you start an instance, AWS OpsWorks automatically installs the apps that belong to the associatedlayer. AWS OpsWorks may also install apps as part of a lifecycle event:

• The deploy event occurs, for example, when you deploy a new app to existing instances and runsrecipes that download and install the instance's apps from the repository.

• The undeploy event occurs when you delete an app and runs recipes that uninstall the app and performany required cleanup.

The built-in deploy recipes are sufficient many apps.You can customize app deployment by addingcustom recipes to the deploy and undeploy event for the appropriate layer. For example, you can attacha custom recipe to the appropriate layer's deploy event to create a required config file. If you need to docleanup tasks when you delete an app, you can attach a custom recipe to the undeploy event.

Using Logging and MonitoringAWS OpsWorks provides several features to help you monitor and debug your applications and instanceconfiguration:

• Cloudwatch monitoring, summarized on the OpsWorks Monitoring page.

• A Ganglia master layer that collects and displays detailed monitoring data for the instances in yourstack

• Rich app deployment logs

• An event log that lists all events in your stack

Getting StartedNow that you know a little bit about AWS OpsWorks and how it works, it's time to go through the GettingStarted Walkthroughs (p. 6), which show you how to create some working stacks.

API Version 2013-02-185

AWS OpsWorks User GuideUsing Apps

Page 12: Opsworks amazon

Getting Started Walkthroughs

The walkthroughs in this section lead you through the following scenarios and explain how AWS OpsWorksworks at each step.

Deploying a web application. (p. 6) This walkthrough first deploys a simple PHP application and thendeploys a new version of the application that uses a database. As you walk through this example, you'lllearn about AWS OpsWorks basics, as well as how to use Chef recipes to customize your applicationdeployment.You'll also try out an HAProxy load balancer and a Ganglia monitoring server.

Deploying a PHP application that leverages the AWS SDK for PHP, Amazon Simple Storage Service,and custom metadata. (p. 43) This walkthrough deploys a PHP application that uses a database andan Amazon S3 bucket to store its data. As you walk through this example, you'll learn how to use Chefto run scripts that install and configure software and how to pass metadata to your scripts by using customJSON in AWS OpsWorks.You'll also manage the permissions for the instance profile that is used on yourPHP application server in order to give appropriate access to the S3 bucket that you want to use with thesample application.

Walkthrough: Deploy a Web App and Learn AWSOpsWorks Basics

In this walkthrough, we go through the key tasks that you need to know to use AWS OpsWorks.

Step 1. (p. 7) Create a simple application server stack. In this step, you create a stack, add an applicationserver layer, launch a single instance for that layer, add an app that defines an application, and thendeploy the app to your instance.

Step 2. (p. 22) Deploy version 2 of the application. In this step, you create a more sophisticated versionof your application that uses a database server. The updated application requires some additionalconfiguration on both the application server and the database server. To make these changes, you startby updating your app definition. Next, you add a database layer to your stack, add a cookbook thatcontains recipes for configuring instances to run your app, assign the recipes to the application serverand database layers' lifecycle events, and then deploy the app.

Step 3. (p. 35) Scale out your application by adding a second instance to the application server layerand then adding an HAProxy load balancer layer to the stack to distribute traffic to the application servers.

Step 4. (p. 39) Add a Ganglia layer and take a brief tour of the monitoring capabilities of AWS OpsWorks.

API Version 2013-02-186

AWS OpsWorks User GuideWalkthrough: Deploy a Web App and Learn AWS

OpsWorks Basics

Page 13: Opsworks amazon

Step 5. (p. 41) Clean up the resources you created so that you don't incur unwanted charges when you'refinished with your stack and its instances.

Step 1. Create a stack and deploy an appA stack is the largest unit of management in AWS OpsWorks. Within a stack, you define layers, whichare blueprints for launching and configuring instances. Layers are a way to define a group of instancesthat have the same or similar configuration and that you want to manage together as a group.

In Step 1, you'll sign up for an Amazon Web Services account, create a stack that you will use througheach step to try out the AWS OpsWorks key features, add a layer, launch an instance, deploy a simpleapp, and monitor its deployment.

1. Sign up for AWS

If you already have an AWS account, you are automatically signed up for AWS OpsWorks. However,if you are using IAM user credentials to log into AWS, make sure that they grant permissions to useOpsWorks. For details, see Granting Users Permissions to Work with AWS OpsWorks (p. 198).

If you are new to AWS, follow these steps to open an AWS account:

To sign up for AWS

1. Go to http://aws.amazon.com, and then click Sign Up.

2. Follow the on-screen instructions.

Part of the sign-up procedure involves receiving a phone call and entering a PIN using the phonekeypad.

The procedure creates an access key and secret key that you can use them to log in to OpsWorksfor this walkthrough. However, a more robust way to manage user access is to create IAM users.For details, see Granting Users Permissions to Work with AWS OpsWorks (p. 198).

2. Log in to OpsWorks

The procedure depends on whether log in with your account's access and secret keys or as an IAMuser.

• If you logging in with your account's access and secret keys, navigate your browser to the AWSOpsWorks console at https://console.aws.amazon.com/opsworks/ and use your keys to log in.

• If you are logging in as an IAM user, you will receive an Access Alias URL, user name, and passwordfrom your administrator.

Navigate your browser to the Access Alias URL and log in with the user name and password.Afterward you might need to switch to AWS OpsWorks console by opening the Services dropdownat the upper left corner and selecting OpsWorks.

3. Create a Stack

You start an AWS OpsWorks project by creating a new stack, which acts as a container for yourinstances and handles some of the management tasks.

a. If you're on the Welcome to AWS OpsWorks page, click Add your first Stack; otherwise, fromthe AWS OpsWorks dashboard, click Add stack.

API Version 2013-02-187

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 14: Opsworks amazon

b. On the Add stack page, click Advanced >> to show all the options and then use the followingsettings:

NameType a name for your new stack. For this example, we use MyStack. A stack name cancontain any alphabetic character (a–z, A–Z), any number (0–9), or hyphens (-).

Default operating systemSelect the operating system that will be used by default for the instances in your stack. Forthis example, accept the default value of Amazon Linux.

RegionSelect the AWS region where you want AWS OpsWorks to create resources for your stack,such as Amazon EC2 instances and EBS volumes. For this exercise, select US East (N.Virginia).

Default Availability ZoneSelect the default AWS Availability Zone for your stack.Your stack's instances will be createdin this zone unless you specify otherwise when you create the instance. For this exercise,select us-east-1a. For more information, see Regions and Availability Zones.

Default SSH keyIf you want to log in to your instance by using SSH, use this drop-down list to specify oneof your account's Amazon EC2 SSH key pairs. AWS OpsWorks installs the public key onevery instance in the stack, and you can use the corresponding private key with an SSHclient to access your instances. If you select the default Do not use a default SSH key,

API Version 2013-02-188

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 15: Opsworks amazon

you can specify a key pair later when you create instances. For more information on AmazonEC2 key pairs, see Getting a Key Pair.

Hostname themeSelect the naming scheme that AWS OpsWorks will use to name the instances that youcreate. For this example, accept the default value, which is Layer Dependent. AWSOpsWorks then uses the layer's short name—php-app for a PHP App Server layer—togenerate hostnames like php-app1, php-app2, and so on.

Stack colorSelect the stack's color to make it easier to identify the stack on the console. For this exercise,accept the default value.

IAM roleWhen you use AWS OpsWorks to manage Amazon EC2 instances, AWS OpsWorks needsto be able to use the Amazon EC2 service on your behalf to perform the appropriate actions.The IAM role is an IAM (AWS Identity and Access Management) role that allows AWSOpsWorks to work with other dependent AWS resources on your behalf. If your accounthas an existing AWS OpsWorks role, you can select it from the list. Otherwise, select NewIAM Role to let AWS OpsWorks create this role for you, and ensure that it has the correctpermissions.

• If your account has an existing AWS OpsWorks role, you can select it from the list.

• Otherwise, select New IAM Role to let AWS OpsWorks create this role for you, andensure that it has the correct permissions.

For more information on IAM, see What is IAM?.

Default IAM Instance ProfileThe IAM instance profile controls whether and how your instances can access other AWSresources, such as Amazon S3 buckets. For this exercise, accept the default value.

Use custom Chef CookbooksSet this field to Yes to use custom Chef cookbooks to customize your stack. Use the defaultsetting of No for now. We'll come back to it later.

Custom Chef JSONSpecify custom JSON to override standard AWS OpsWorks configuration settings. For thiswalkthrough, accept the default value.

API Version 2013-02-189

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 16: Opsworks amazon

c. Click Add Stack.

When you first create a stack, you make general settings that AWS OpsWorks uses to manageyour stack, such as the defaults it will use to launch instances (operating system, hostnametemplate, region, Availability Zone, SSH key).

Let's create a layer now.

4. Add a PHP App ServerLayer

Before you add instances to your stack, you must first create a layer. Layers are the way AWSOpsWorks lets you specify the shared configuration of a set of instances. For example, this setcreates a PHP App Server layer to contain instances that function as PHP application servers.Whenyou change the configuration of a layer, the changes are consistently applied to all the instances forthat layer. Consequently, you'll usually want instances in the same layer to have the sameconfiguration.

a. On the page for your stack, under Add your first layer, click Add a layer.

API Version 2013-02-1810

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 17: Opsworks amazon

b. For Layer type box, select PHP App Server, and then click Add layer.

c. On the Layers page, in the list of layers for your stack, click PHP App Server to display thelayer's settings.

When you first add a layer, it has no running instances. When you click Edit, you can adjustlayer settings to add capabilities to the instances you'll add later. These capabilities includecustom Chef recipes, Elastic IP addresses, and EBS volumes. For more information, seeLayers (p. 64). We'll see how changes to a layer's settings affect its instances later, in Step 2of this walkthrough. But let's start with one instance first.

API Version 2013-02-1811

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 18: Opsworks amazon

5. Add an Instance

Add an instance for the PHP layer.

a. In the navigation pane, click Instances. Under PHP App Server, click Add an instance.

When you add an instance, you specify the layer that you will use as the blueprint for the instance.The instance also gets some of its default settings from the stack settings. For example, AWSOpsWorks gives the instance a hostname that is based on the theme you chose for the stack.In this walkthrough, you kept the Hostname theme as Layer Dependent, so AWS OpsWorksgave this instance the name php-app1 because of its role as a PHP App Server.You canoverride the stack defaults for the instance, but for now we're going to keep it simple and acceptthe defaults. While we're here, let's look at a few important settings.

b. Under Add instance, click Advanced >>.

The Hostname is the identifier for this instance within AWS OpsWorks. AWS OpsWorks alsoadds the instance's hostname to the hosts file of every instance in the stack. In fact, AWSOpsWorks adds two entries: one that maps the internal IP address to the host name (for example,10.235.67.199 php-app1) and another that maps the external IP address to the host name. Thename that maps to the external address has –ext appended to it (for example, 54.247.46.155php-app1-ext). The hosts file makes it convenient for applications or users who use an SSHconnection to an instance to connect to other instances in the stack by using their host names.

You'll recognize most of the settings on the Add instance page from the default settings youaccepted for the stack (Availability Zone, SSH key, and Operating system). If you knowAmazon EC2, you'll also recognize Size as an instance type, which defines the compute capacityand hourly cost for an Amazon EC2 instance.You set the instance type when you add theinstance.You can also change the instance type later by editing the instance settings, but onlywhen the instance is stopped or offline. For more information on instance types, see InstanceFamilies and Types.

Another important setting is Scaling type. When you add an instance to a layer, you are onlyproviding a specification. AWS OpsWorks uses that specification to create a running AmazonEC2 instance by various means. The scaling type determines how the instance is managed:

• A 24/7 instance (the default) is one that you manually start and stop.

• A time-based instance runs only on the days and times that you specify.

• A load-based instance runs when a specified Up threshold is passed and is stopped whena specified Down threshold is passed.

AWS OpsWorks takes care of starting and stopping time-based and load-based instances. Formore information, see Managing Load with Time-based and Load-based Instances (p. 198).

API Version 2013-02-1812

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 19: Opsworks amazon

c. In the Add instance section, accept the default values, and then click Add instance.

As noted in the previous step, you don't get a running Amazon EC2 instance until you start it.In the case of a 24/7 instance, the EC2 instance isn't started until you tell AWS OpsWorks tostart it. After that it continues to run until you tell AWS OpsWorks to stop it. On the Instancespage, in the list of instances, the Status for the instance is shown as stopped (in grey), whichmeans that the instance is not currently running. Possible statuses for an instance are as follows:

• stopped (grey)—The instance is not currently running.

• online (green)—The instance is running.

• launching (blue)—The instance is in the process of being started, configured, or terminated.

• error (red)—An error occurred while the instance was being launched.

• setup_failed (red)—Setup failed.

The circle and list on the Instances page summarize the states of all your instances.

API Version 2013-02-1813

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 20: Opsworks amazon

d. Under PHP App Server, in the row that corresponds to your instance, click start in the Actionscolumn.

While the instance is being launched, you'll see the Status change to the following:

requestedAWS OpsWorks has successfully called the Amazon EC2 service to run the instance forthe layer.

pendingAWS OpsWorks is waiting for the Amazon EC2 instance to start.

bootingThe Amazon EC2 instance is booting. When booting is complete, AWS OpsWorks installsthe AWS OpsWorks agent on the instance and does some additional configuration, dependingon options that you may have set for your layer. (We didn't specify any in this example.) Ifyou specified additional EBS volumes or Elastic IP addresses, AWS OpsWorks would attachthose volumes or assign those Elastic IP addresses at this point.

running_setupThe AWS OpsWorks agent is running the following Chef recipes:

• AWS OpsWorks runs a set of built-in system setup Chef recipes that perform basicconfiguration for the layer.These recipes also install any dependencies that were specifiedfor the layer, such as application servers, and configure RAID arrays if you specified RAIDwhen adding EBS volumes for the layer. In our example, we added no dependencies orEBS volumes, so AWS OpsWorks didn't have to do anything beyond installing andconfiguring the PHP application server.

• Custom recipes that were specified for the Setup event for the layer. Again, we didn'tspecify custom recipes for our example. If you did, the agent would run them at this point.

• AWS OpsWorks runs built-in Deploy recipes to deploy all apps that have already beendeployed to other instances on this layer. We haven't specified any apps yet, and there'sonly one instance, so AWS OpsWorks doesn't run the Deploy recipes.

• Custom recipes that were specified for the layer's Deploy event.You can use the Deployevent to perform any custom configuration when you deploy your apps. Again, we didn'tspecify any custom recipes for our example. If you had, the agent would run them at thispoint.

OnlineWhen the instance is running and has successfully run the setup recipes, AWS OpsWorkstriggers a Configure event for all instances in the stack, including the instance that justfinished its setup. They then run configuration recipes, which can make any configurationchanges needed to accommodate the new instance.

API Version 2013-02-1814

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 21: Opsworks amazon

When your instance is up and running, the page should look like picture below.You'll notice thatitems in the Actions column have changed: in particular, stop replaces start and delete.Youuse stop to terminate the instance.

e. Under Hostname, click php-app1 to view the instance's details page.

On the Instance page, you'll see basic information about your instance. If you know AmazonEC2, you'll see familiar information about instances, such as EC2 Instance ID, DNS name, andAvailability Zone.

As discussed earlier, one of the powerful features of AWS OpsWorks is the ability to run Chefrecipes on an instance when key events occur. AWS OpsWorks retains a log for each of theseevents so that you can see exactly what happened. Let's take a look at one.

API Version 2013-02-1815

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 22: Opsworks amazon

f. Scroll down to Logs.

For our example, you'll see two deployment logs: one for the setup command and another forthe configure command. As discussed earlier, a Setup event is triggered when an instance isfirst started and prompts the AWS OpsWorks agent to run the setup command. The Configureevent is triggered every time a stack's configuration changes and prompts the agent to run theconfigure command.

g. In the row for the Setup event, click show.

API Version 2013-02-1816

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 23: Opsworks amazon

A new browser tab opens to display the output of the log. In line 4, you'll see the AWS OpsWorksagent set the run list for Chef with the recipes it uses to configure the instance for the first time,such as setting up the SSH keys and SSH users. The logs are a convenient way to see thedetails of what happened during an event.

h. When you're done viewing the log, close the log window.

Now that we have an instance of an application server running, let's deploy a simple PHP app to thatPHP App Server.

6. Create and Deploy an App

An app represents code you want to deploy to your servers. That code is stored in a repository, suchas Git or Subversion. AWS OpsWorks provides a simple way to get code from your repository andplace it on your instances: Create an app and then deploy it to the appropriate instances.

To create an app, you specify the following:

• The app type, such as PHP or Node.js, which determines the layer the app is intended for. Whenyou deploy an app, AWS OpsWorks deploys the code for that app to all instances of the associatedlayer.

• The location of the code's repository, such as Git or Subversion repository, an Amazon S3 bucket,or an HTTP endpoint.

• Optional configuration, such as virtual host configuration and SSL settings.

Now that you know a little bit about apps, let's try it out with a simple PHP app. Here's the GitHublocation that contains the app that you are going to deploy:https://github.com/amazonwebservices/opsworks-demo-php-simple-app. If you're familiar with GitHub,you'll notice that the link goes to a specific branch of the repository. In the first step, we'll use thecode from the version1 branch. (Later on, we'll use the code from the version2 branch to deploy amore complex app.) If you look inside the version1 branch, you'll see that it's a simple PHP pagewith an assets directory containing css and javascript files that are used to make the page look nice.

a. In the navigation pane, click Apps. On the Apps page, click Add an app.

b. On the App page for your new app, set the following values:

API Version 2013-02-1817

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 24: Opsworks amazon

NameType a name for the app. For this exercise, we'll call it SimplePHPApp. AWS OpsWorkswill turn this name into the short name simplephpapp. The short name is the identifier thatAWS OpsWorks uses to refer to the app in recipes and in the configuration JSON.The shortname is also used as the name for the directory where your app files are installed. Forexample, if you add a MySQL layer and it has a running instance, AWS OpsWorksautomatically creates a database for your app on that instance using your app's short nameas the database name.

App typeSelect PHP. Each app server layer handles a particular app type, so this setting determineswhich layer the app is targeted for. When you deploy the app, AWS OpsWorks deploys itto the layer's instances by using a set of Deploy recipes that are specific to the layer. InStep 2 of this walkthrough, you'll learn how to add your own custom Deploy recipes to theset.

Document rootLeave this box blank, because the index.php file is at the root. If the document root werea different location, you would specify it here.

Repository typeAWS OpsWorks supports a number of repositories: Git and Subversion (SVN), as well asbundles (ZIP or tarball) stored in Amazon S3 buckets and on HTTP servers. For this example,click Git.

Repository URLFor this example, usegit://github.com/amazonwebservices/opsworks-demo-php-simple-app.git.You'll notice that our URL is a Git repository. Because our repository is public, you cansimply navigate to the repository URL and view the files that you'll deploy. In this step ofthe walkthrough, we'll deploy from the version1 branch.

Deploy SSH keyLeave this blank. If you use a private Git repository, AWS OpsWorks would use the deploySSH key to access it. For information about permissions for repositories, see Security andPermissions (p. 198).

Branch/RevisionType version1. If you visit our example Git repository, you'll see that there are threebranches: master, version1, and version2.We are going to deploy version1, which is a basicPHP application that is a simple HTML page. Later, in Step 2 of this walkthrough, you'lldeploy version2, which is a slightly more sophisticated application that reads and writes toa table in a MySQL database.

Domain nameLeave this box blank. If you were mapping domain names to the root of the applicationserver, you would specify those domains here.

Enable SSLLeave this set to No. If you were adding support for SSL for this app, you would specify thecertificate information here.

API Version 2013-02-1818

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 25: Opsworks amazon

c. When all the settings are as you want them, click Add app.

When you first add a new app, it isn't deployed yet to the instances for the layer.You have toexplicitly deploy the app only once, which deploys it the layer's current online instances. AWSOpsWorks automatically deploys the app to any new instances for the layer.

d. To deploy SimplePHPApp to the instance in PHP App Server layer, under Actions, click deploy.

On the Deploy app page, the Command list box shows all the commands you can run on yourapplication: deploy, start web server, stop web server, restart web server, and undeploy.In this walkthrough, you'll use deploy, which copies the files from the app's repository to thetargeted instances and then configures the app. For information about the app deploymentcommands, see Deploying Apps (p. 198).

By default, all online instances are selected as the deploy command's target. AWS OpsWorksinstalls the code from the app's repository only on the instances that belong to layer that isassociated with the app's type. However, instances that belong to other layers might need tomodify their configuration in response to the deployment. Including those instances in the deploycommand notifies them to run their deploy recipes, which make any needed configuration

API Version 2013-02-1819

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 26: Opsworks amazon

changes.We'll try this feature in Step 2 of this walkthrough. If you want to specify which instanceto run the deploy command on, click Advanced >> under Instances at the bottom of the pageand select the appropriate instances.

e. Keep the other settings at their defaults, and then click Deploy. When deployment is complete,the Deployment page displays a Status of successful, and the row for php-app1 contains agreen check mark.

You'll recall that when you added an instance to the layer, AWS OpsWorks logged informationabout Setup and Configure events for that instance. AWS OpsWorks does the same for appdeployments.

f. Click show to see the deployment log for the app.

The following illustration shows a part of a typical php-app1 log.The log lists what AWS OpsWorkshas done to deploy the app, such as unpackaging the ZIP file, creating a simplephpapp directory,creating a versioned subdirectory (e.g., simplephpapp/releases/20120922011343), and symlinkingthe latest version to current. If you had attached a recipe to the Deploy event, you would alsosee the logging information for that recipe here.

API Version 2013-02-1820

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 27: Opsworks amazon

g. When you're finished with the log, close it.

At this point, you're probably wondering if your app really deployed and where your application'sbits ended up. To view instance properties, go to the Instances page and click the php-app1public IP.

h. In the Public DNS row, click the DNS address.

You should see the following page in your browser.

API Version 2013-02-1821

AWS OpsWorks User GuideStep 1. Create a stack and deploy an app

Page 28: Opsworks amazon

i. If you are curious, you can use an SSH client to log in to your instance. For details, see UsingSSH to Communicate with an Instance (p. 198).

In the command window, change directories to /srv/www/simplephpapp and list its contents.You'll see three directories:current, releases, and shared. If you list the current directory'scontents, you can see the files that were retrieved from the app's Git repository and placed onthe instance. If you list the releases directory, you'll see one or more deployment directories,one for each deployment, whose names are numbers like 20120922011343. This is the timeand date stamp from the time you deployed the application.You should have only one suchfolder in releases now, because you've deployed only once.

The current directory represents the application that is served to clients. It is symlinked to themost recent deployment directory . If you deploy a new application version, the new version'sdeployment directory name would have a later date stamp and AWS OpsWorks would symlinkthat directory to current.

Congratulations! You've created your first stack, added your first layer, created an instance for that layer,defined an app and deployed it to the instance, and taken a look at some of AWS OpsWorks's handiwork.

Go on to the next step (p. 22) to deploy a more sophisticated app, add a database layer, and configureyour app and database to work together.

If you're done trying out AWS OpsWorks, skip to Step 5 (p. 41) to clean up your stack so that you don'tincur any unnecessary charges.

Step 2. Update the server application to a newversion that uses a databaseIn Step 1 (p. 7), you created a stack, added a PHP App Server layer, added an instance to that layerand started it, and then deployed a simple PHP application to the instance. In Step 2, you're going tobuild on that experience by deploying a new version of the application that uses a database server.You'llconfigure both the application server and the database for the new application.

With our first app, we deployed a simple PHP file (index.php) and some CSS and JavaScript files thatdidn't require any additional configuration.

As you saw in Step 1, AWS OpsWorks can define a set of files in a repository as an app and then deploythe app to instances in a layer. If you connect over SSH to your PHP App Server instance and run dpkg(Ubuntu) or rpm (Amazon Linux), you'll see that AWS OpsWorks installs a number of packages thatsupport the PHP App Server layer (for example, php-db and php-html-common). Our application in Step1 did not depend on any additional packages. If it had, we could have specified those packages asdependencies for the PHP App Server layer. Dependent packages are installed at boot time or you can

API Version 2013-02-1822

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 29: Opsworks amazon

use a stack command (p. 58) to update them manually. Simple app deployment can be a good option ifyour application doesn't require configuration beyond just deploying the applications files.

In many cases, you'll want to do more than just deploy files and packages.You'll want to create or modifyconfiguration files, install software, or set up tables and permissions in a database. AWS OpsWorks usesthe power of Opscode Chef recipes to describe how resources on an instance should be configured. InChef, recipes are stored in cookbooks that also typically contain other supporting files:

• Attribute files contain default values such as database table names, that can be used by recipes.

• Template files contain templates that recipes can use to generate files such as configuration files.Theytypically contain placeholders that are replaced at run time with the correct values.

For more information about Chef, see Opscode.

AWS OpsWorks uses recipes from its own cookbooks (https://github.com/aws/opsworks-cookbooks.git)to set the base configuration of its built-in layers, such as PHP and MySQL Master. To see these recipes,go to an individual layer page and click Show >> under Built-in Chef recipes.

AWS OpsWorks runs these recipes when it runs the associated command. For example, AWS OpsWorksruns the recipes for the Setup command when it starts a new instance.You can add your own recipe toa command from your own custom cookbooks, and AWS OpsWorks will run your recipe after its ownrecipes have finished running. For a particular layer, you can specify your own recipes for each commandthat AWS OpsWorks runs during an instance's lifecycle (Setup, Configure, Deploy, Undeploy, Shutdown).

Probably the most commonly used commands are setup (to manage the initial configuration of the instance)and deploy (to configure an app when you deploy its files). In Step 2, we'll add recipes for the deployaction for the PHP App Server and MySQL layers so that we can configure the PHP application and setup the database it will use.

Here's what you'll be doing in Step 2:

1. Update SimplePHPApp to use version2 of our sample application.

2. Add a database layer to your stack.

API Version 2013-02-1823

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 30: Opsworks amazon

3. Point the stack to a repository that contains a cookbook with recipes that will configure your instancesto run a simple PHP database application.

4. Add recipes from the cookbook to the PHP App Server and MySQL layers.

5. Deploy the app.

Let's deploy and configure some servers.

1. Log in to OpsWorks

In the AWS OpsWorks console, make sure that the MyStack page is displayed.

You should see the stack you created in Step 1 as well as the PHP App Server layer as well as theSimplePHPApp, listed on the right.

2. Update SimplePHPApp

Update the SimplePHPApp application to use the version2 branch of the application’s Git repository.

AWS OpsWorks makes it easy to deploy new versions of an application. One of the simplest waysis having branches or revisions in your repository that represent different versions you potentiallywant to deploy. In Step 1 (p. 7), you deployed the application from the version1 branch. Now, you'regoing to update SimplePHPApp to use version2.

a. In the left column, click Apps.

b. In the SimplePHPApp row, click edit.

c. Keep the same Repository type and Repository URL values that you used for version1, butfor Document root, type web.

In Step 1, you left this field blank because index.php was at the root. In our version2 application,index.php is in the web subdirectory so you're letting AWS OpsWorks know that requests forthis app's root document should be routed to the web subdirectory.

d. For Branch/Revision, delete version1 and type version2.

API Version 2013-02-1824

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 31: Opsworks amazon

e. Click Save.

When you click Save, you are only updating the information for SimplePHPApp; you are notredeploying the app.You won't do that until later because our version2 application needs adatabase. So let's add one.

3. Add a Database Layer

The new version of SimplePHPApp depends on a backend database, so you need to add a MySQLlayer to the stack. A MySQL layer serves as a blueprint for creating MySQL database server instances.

a. In the left navigation pane, click Layers.

b. On the Layers page, click + Layer.

c. On the Add Layer page, for Layer type, select MySQL and click Add Layer.

API Version 2013-02-1825

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 32: Opsworks amazon

4. Add an Instance to the MySQL Layer

A MySQL instance supports a MySQL database server.

a. In the MySQL row, click Add an instance.

b. On the Instances page, under MySQL at the bottom, click Add an instance.

c. Keep the defaults in the Add Instance section and click Add instance.

d. In the Actions column, click start to start the instance and wait for the Status to change toonline.

You have all the servers that you need for the version2 application up and running: a MySQLdatabase server and your original PHP App Server. Now let’s tell AWS OpsWorks how to setthem up.

5. Implement a Custom Cookbook

Pick or create a cookbook and modify it appropriately for your application deployment.

When you use recipes from a cookbook, those recipes work together with the stack configurationJSON (p. 147) that AWS OpsWorks pushes down to every instance. For example, if you have aMySQL instance, AWS OpsWorks creates a database for every application that you create in yourstack. AWS OpsWorks places information about the database in the stack configuration JSON. Thisinformation includes the database name, the user name and password used to access the database,and the IP address of the database server. If you are a Chef Server user, the stack configurationJSON is conceptually similar to a data bag.

TipAWS OpsWorks lets you easily add your own data to the stack configuration JSON andoverride the default data. For more information, see Use Custom JSON to Modify the StackConfiguration JSON (p. 60).

Your recipe can use information from the stack configuration JSON to configure the database foryour application by using Chef node syntax. For example, the stack configuration JSON includes adeploy node that contains information about the deployment. The part that contains informationabout each of the stack's apps looks something like the following:

{ ... "deploy": { "simplephpapp": { "migrate": false,

API Version 2013-02-1826

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 33: Opsworks amazon

"domains": [ "simplephp" ], "scm": { "repository": "git://github.com/amazonwebservices/opsworks-demo-php-simple-app.git", "password": null, "ssh_key": null, "revision": null, "user": null, "scm_type": "git" }, "database": { "reconnect": true, "password": null, "username": "root", "host": null, "database": "simplephpapp" }, "deploy_to": "/srv/www/simplephp", } }}

In particular, the deploy node includes a node for each app, named with the app's short name, thatcontains related information. This example has a single app node, simplephpapp, that containsinformation about the app's database, Git repository, and so on.You can use Chef node syntax torefer to the stack configuration values in your recipes. For example, the following code tells Chef toinsert the value of the username node:

#{[:simplephpapp][:database][:username]}

It resolves to "root".

For our example application, we need a database so we will use the database created by AWSOpsWorks for the app. In our cookbook, the dbsetup.rb recipe creates a table in the app's database.You'll add this recipe to the MySQL layer's Deploy event and AWS OpsWorks will run it on the layer'sinstances when you deploy the app.

The following example shows the dbsetup.rb recipe.

node[:deploy].each do |app_name, deploy| execute "mysql-create-table" do command "/usr/bin/mysql -u#{deploy[:database][:username]} -p#{deploy[:data base][:password]} #{deploy[:database][:database]} -e'CREATE TABLE #{node[:phpapp][:dbtable]}( id INT UNSIGNED NOT NULL AUTO_INCREMENT, author VARCHAR(63) NOT NULL, message TEXT, PRIMARY KEY (id) )'" not_if "/usr/bin/mysql -u#{deploy[:database][:username]} -p#{deploy[:data base][:password]} #{deploy[:database][:database]} -e'SHOW TABLES' | grep #{node[:phpapp][:dbtable]}" action :run

API Version 2013-02-1827

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 34: Opsworks amazon

endend

This recipe iterates over the contents of the deploy node and processes each app node. The nodename for each app is represented by the deploy variable. For the simplephp app node, deployresolves to [:simplephp]. The loop contains an execute resource that runs a mysql commandto create a table. When you deploy the app, AWS OpsWorks runs the recipe to create a table onevery MySQL instance in the stack, one in this case.

The recipe inserts values into the command string from the stack configuration JSON, using thesyntax discussed earlier. The full command string resolves to the following based on the stackconfiguration JSON example:

"/usr/bin/mysql -uroot -pujn12pw simplephpapp -e'CREATE TABLE #{node[:phpapp][:dbtable]}( id INT UNSIGNED NOT NULL AUTO_INCREMENT, author VARCHAR(63) NOT NULL, message TEXT, PRIMARY KEY (id))'"

You’ll notice that the following directive is not resolved from the stack configuration JSON:

#{node[:phpapp][:dbtable]}

The stack configuration JSON is only one source of attributes. A cookbook can contain defaultattributes that can also be used in the cookbook's recipes by using the same node syntax. In ourcookbook, we have a simple one-line file in the cookbook's attribute directory, default.rb, thatcontains:

default[:phpapp][:dbtable] = 'urler'

The [:phpapp][:dbtable] attribute represents the name of the table to create in the database.Our example application will read and write to this table. Here is the fully resolved command wewould run on the database instance:

"/usr/bin/mysql -uroot -pujn12pw simplephpapp -e'CREATE TABLE urler( id INT UNSIGNED NOT NULL AUTO_INCREMENT, author VARCHAR(63) NOT NULL, message TEXT, PRIMARY KEY (id))'"

This command creates a table with the specified fields using the credentials and database namespecified by the stack configuration JSON and the table name specified by default.rb.

API Version 2013-02-1828

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 35: Opsworks amazon

You’ll notice that AWS OpsWorks identifies the app using its short name rather than the name youspecified earlier.You can see the short name that AWS OpsWorks generates for your app in theapp's properties. When you use the node values for an app, you must refer to the app using its shortname.

The execute resource has two additional directives. The not_if directive tells Chef that it shouldrun the specified mysql command to get the list of tables in the app database. If Chef finds theapplication's table ([:phpapp][:dbtable]) in the result, it will not run the command to add theapplication’s table. The action directive tells Chef that it should execute the command if theappropriate conditions are met (that is, when the not_if condition is not satisfied).

Now that you understand how the dbsetup.rb recipe uses the stack configuration JSON to run amysql command to configure the database for the example application, let’s look at appsetup.rb,which sets up the connection that the application uses to access the database.

The application has two PHP files:app.php and index.php.index.php simply loads the app.phpfile , which is in the src directory. The app.php file includes another PHP file, db-connect.php.You'll notice that the version2 branch of the Git repository does not contain a file with that name.This file is generated by appsetup.rb, which generates that file from a template. The recipe'stemplate resource contains the instructions for how to evaluate the template file and place thegenerated file on the instance.

Here’s appsetup.rb file:

node[:deploy].each do |app_name, deploy| script "install_composer" do interpreter "bash" user "root" cwd "#{deploy[:deploy_to]}/current" code <<-EOH curl -s https://getcomposer.org/installer | php php composer.phar install EOH end

template "#{deploy[:deploy_to]}/current/db-connect.php" do source "db-connect.php.erb" mode 0660 group deploy[:group]

if platform?("ubuntu") owner "www-data" elsif platform?("amazon") owner "apache" end

variables( :host => (deploy[:database][:host] rescue nil), :user => (deploy[:database][:username] rescue nil), :password => (deploy[:database][:password] rescue nil), :db => (deploy[:database][:database] rescue nil), :table => (node[:phpapp][:dbtable] rescue nil) )

only_if do File.directory?("#{deploy[:deploy_to]}/current") end

API Version 2013-02-1829

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 36: Opsworks amazon

endend

Here’s how it works. Like the dbsetup recipe, appsetup.rb iterates over the app nodes and getsthe app information from the stack configuration JSON.

The script resource does the following:

• It specifies a bash script to run on the instance.

• The interpreter attribute specifies the script interpreter that will run the script.

• The cwd attribute specifies the current working directory that the script will use. In this case, it'sthe directory where the app is installed.

• The code attribute contains the code for the script, with <<-EOH marking the beginning of the scriptand EOH marking the end.

• The curl attribute downloads Composer—a dependency manager for PHP applications.

• Finally, the script runs Composer's install command to install the dependencies for the sampleapplication to the app's root directory.

Using the example stack configuration JSON, this directory resolves to/srv/www/simplephpapp/current.

The node reference that follows template specifies the location and name of the file to be generated.Using the example stack configuration JSON, the file path resolves to/srv/www/simplephpapp/current/db-connect.php.

The source parameter specifies the template used to generate the file. Templates are placed in thecookbook's templates/default directory and have an .erb extension appended to the file name.Here’s what db-connect.php.erb looks like:

<?php define('DB_NAME', '<%= @db%>'); define('DB_USER', '<%= @user%>'); define('DB_PASSWORD', '<%= @password%>'); define('DB_HOST', '<%= @host%>'); define('DB_TABLE', '<%= @table%>');?>

You’ll notice that the variable names between <%= and => match the variables defined in the variablesparameter in the template resource. When Chef processes the template, it replaces the <%= =>directives with the value of the appropriate variables in the template resource. Just like thedbsetup.rb file, the values of these variables come from node values in the stack configurationJSON and the attribute.rb file. Using our example stack configuration JSON, the appsetup.rbrecipe would generate the following db-connect.php file:

<?php define('DB_NAME', 'simplephpapp'); define('DB_USER', 'root'); define('DB_PASSWORD', 'ujn12pw'); define('DB_HOST', '10.10.10.10'); define('DB_TABLE', 'urler');?>

API Version 2013-02-1830

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 37: Opsworks amazon

The recipe's mode parameter specifies the permissions on the file (read/write for the user group andowner). The node[:deploy][:group] parameter specifies the user group for the file.

You’ll notice that the recipe uses a conditional statement to set the file owner:

if platform?("ubuntu") owner "www-data"elsif platform?("amazon") owner "apache"end

The Apache web server needs to be able to read the db-connect.php file so that it can include itin the app.php file. The template picks the appropriate Apache server user for the Ubuntu andAmazon Linux platforms.

The only_if directive tells Chef to evaluate this template only if the specified directory exists.

Now that you have a good idea of the role that the recipes play in the deployment of the exampleapplication. Let's add the cookbook to the stack and start using it.

6. Add the Custom Coobook to the Stack

Add a custom cookbook so that you can configure the example application.

For each stack, you can have a repository that contains one or more cookbooks.You specify thecookbook repository by giving AWS OpsWorks its location.You have a couple of choices:

• The location of a Git or Subversion repository. If the repository is private, you specify the credentialsthat AWS OpsWorks uses to get the cookbooks from the repository. Optionally, you can alsospecify a particular branch or revision in the repository.

• An archive, such as a .zip file, stored in Amazon S3 or on a web server. If the file requirespermissions to read it, you specify the credentials that AWS OpsWorks needs to download thearchive. For Amazon S3, this is the access key and secret key of an account or an IAM user thathas access to the archive file. For HTTP and HTTPS, this is a user name and password.

Specify the cookbook repository for the example application:

a. Click Stack in the left column to go to the page for your stack (MyStack). Click Stack settings.Then click Edit.

b. Set Use custom Chef Cookbooks to Yes. For Repository type, select Git. For RepositoryURL specifygit://github.com/amazonwebservices/opsworks-example-cookbooks.git. ClickSave.

API Version 2013-02-1831

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 38: Opsworks amazon

7. Assign Recipes to Lifecycle Events

Add recipes to the deploy actions of the MySQL and PHP App Server layers.

Recipes in your cookbook won’t get run until you add them to commands for a layer. Optionally, youcan also explicitly run a recipe on specific instances or even all instances in your stack. For moreinformation, see Cookbooks and Recipes (p. 198).

For this example application deployment, you want to have AWS OpsWorks run the dbsetup.rbrecipe on the MySQL instance to create the table and run the appsetup.rb recipe on the PHP AppServer. For the console, you use cookbook_name::recipe_name to identify Chef recipes, whererecipe_name does not include the .rb extension. For example, you refer to dbsetup.rb asphpapp::dbsetup.Let's do that now.

a. In the left navigation pane, click Layers. In the Actions column for MySQL, click edit.

b. In the Custom Chef recipes section, type phpapp::dbsetup for Deploy. Then click the +icon.

API Version 2013-02-1832

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 39: Opsworks amazon

c. Click Save.

d. In the left navigation pane, click Layers. In the Actions column for PHP App Server, click edit.

e. In the Custom Chef recipes section, type phpapp::appsetup for Deploy. Then click the +icon.

f. Click Save.

Now all the layers are created with their instances launched, the app is updated to use version2, andthe layers have custom recipes for the deploy action that will configure the instances to run theversion2 application.You’re ready to deploy the app.

8. Deploy the App

Deploy the example application to the PHP App Server instance.

a. In the left navigation pane, click Apps.

b. Click deploy in the Actions column for SimplePHPApp.

API Version 2013-02-1833

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 40: Opsworks amazon

c. Keep the defaults and click Deploy.

By default, all instances will be targeted for the deployment. AWS OpsWorks will place the codefor the updated app on the PHP App Server and run the deploy command, which executes theappsetup.rb recipe on that instance. AWS OpsWorks will also run the deploy command onthe MySQL instance to execute the dbsetup.rb recipe.

When the deployment has been successfully completed, the Status will be listed as successfulon the Deployment page.

9. Run the Application

You can now run the application.

a. On the Deployment page, click php-app1 and click the DNS address in the Public DNS row.

You should see the following page in your browser.

API Version 2013-02-1834

AWS OpsWorks User GuideStep 2. Update the server application to a new version

that uses a database

Page 41: Opsworks amazon

b. Click Share Your Thought and type something like Hello world! for Your Thought and yourname for Your Name.Then click the Submit Your Thought to add the message to the database.

c. Click Go Back to view all the messages in the database.

Yay! You’ve just completed a successful deployment of an application that uses multiple layers configuredto run by custom Chef recipes.

Step 3. Scale out by adding another serverinstance and a load balancerSo far, you’ve created two layers but you have only a single instance running for each layer. A powerfulfeature of layers is the ability to easily and quickly add instances that have a configuration specificallydefined for the layer.

API Version 2013-02-1835

AWS OpsWorks User GuideStep 3. Scale out by adding another server instance and

a load balancer

Page 42: Opsworks amazon

In Step 3, you’ll add one more instance to the PHP App Server layer and see how easy it is to deploynew instances of a layer. In this step, you’ll add another 24/7 instance. However, AWS OpsWorks alsohas auto-scaling instance types that run only during a specified time period (time-based) or when a loadthreshold has been crossed (load-based). For more information on the auto-scaling features of layers,see Managing Load with Time-based and Load-based Instances (p. 198).

You’ll also add an HAProxy load balancer to distribute traffic to your two PHP App Server instances. InAWS OpsWorks, a load balancer is simply another layer. When you launch an instance for the HAProxylayer, AWS OpsWorks starts an instance running HAProxy. By default, AWS OpsWorks configuresHAProxy to distribute traffic to all instances of all application server layers. In our example, we have onlyPHP App Servers; however, if we had instances of another application server layer (such as Rails AppServer or Static Web Server) or a custom layer, HAProxy would be distributed to those instances as well.To adjust the traffic routing for HAProxy, you can use a custom recipe to specify the exact configurationyou want.

Let's scale out the app.

1. Add a Load Balancer Layer

On the page for your stack (MyStack), click Layers in the left column. On the Layers page, click +Layer. For Layer type, select HAProxy, which is a blueprint for creating HAProxy load balancerinstances. Make a note of the password for Statistics password; you’ll use it later. Then click Addlayer.

HAProxy Statistics enables you to view load balancer statistics using the Statistics URL path onthe HAProxy instance. When you go to that URL, you’ll be prompted for a user name andpassword—the Statistics user name and Statistics password will allow you access.

2. Add an Instance to the HAProxy Layer

Add an instance for the HAProxy layer: On the Layers page, in the HAProxy row, click Add aninstance. On the Instances page, under HAProxy, click Add an instance. Keep the defaults andclick Add instance. The HAProxy layer's short name is lb, so the instance will be named lb1.

3. Start the Instance

In the instance's Actions column, click start to start the instance.

4. Run SimplePHPApp

When the instance has started, you can view your application in the your browser. In the row for thelb1 instance, click the IP address in the Public IP column. This sends an HTTP request to the loadbalancer's IP address, which routes the request to php-app1, which runs the SimplePHPApp. Thenrefresh your browser a few times.

API Version 2013-02-1836

AWS OpsWorks User GuideStep 3. Scale out by adding another server instance and

a load balancer

Page 43: Opsworks amazon

Now that you’ve generated some traffic through your load balancer, let’s see how it got routed.

5. View the Load Balancer Statistics

HAProxy provides a useful statistics page that shows the load balancer traffic as well as the healthof instances that it is routing traffic to. Let’s see how our load balancer is doing.

a. If you don't remember your statistics user name and password, go back to the browser tab foryour AWS OpsWorks console, and open the Layers page. Click HAProxy and then click Edit.For Statistics password, click Reset now. Assign a new password and make a note of it andyour Statistics user name from Settings.

b. Go back to the browser tab containing your app's web page that was served up by your loadbalancer.

c. In the browser address bar, append /haproxy?stats to the IP address and press Enter.

To access the statistics, you will be prompted for a user name and password.

d. When prompted, enter the statistics user name and password and click OK.

The statistics report shows the php-app1 as green (active and running) in the php_app_serverstable. Since we have only one application server, the load balancer always routes the trafficthere. Because we did not enable SSL on our instances, the php_app_servers_ssl table showsred rows. HAProxy determines the health of the instances by sending an HTTP request to aspecified URL on the instance.You can specify the URL and HTTP request method used forthe health check in the HA Proxy settings for the layer. By default, the URL is the root of theweb server (/) and the HTTP method is OPTIONS.

A load balancer routing traffic to one instance is not terribly interesting so let’s add anotherinstance.

6. Add an Instance to the PHP App Server

In the browser tab for your AWS OpsWorks console, click Instances in the left navigation pane.Under PHP App Server, click + Instance. Keep the default settings, and click Add instance.

The instance php-app2 appears in the Hostname column of PHP App Server.

API Version 2013-02-1837

AWS OpsWorks User GuideStep 3. Scale out by adding another server instance and

a load balancer

Page 44: Opsworks amazon

7. Start the Instance

In the Actions column for php-app2, click Start.

8. View the Load Balancer Statistics

Use the example application and then view the statistics for the load balancer.

Let’s generate a little more traffic to our load balanced application and see how the load balancer ishandling it.

a. View your application in the your browser: In the row for lb1, click the IP address in the PublicIP column. If necessary, switch to the browser tab with the sample application. Then refresh thepage 10 times or more so we have a sufficient number of requests for the HAPRoxy statisticsreport.

b. View the statistics for the load balancer: Switch to the browser window or tab where you wereviewing the HAProxy statistics before and refresh the browser window.

In the report's php_app_servers table, you’ll see your two servers (php-app1 and php-app2)displayed in green (meaning that they are up and running). Most likely, you’ll also see sometraffic routed to both instances by looking at the Sessions Total column. The example screenbelow has four sessions for php-app1 and one for php-app2.

You may be wondering how the load balancer knew to add php-app2 to its configuration. Whenyou added the second PHP App Server, AWS OpsWorks sent a configure command to all theinstances in your stack. On the instances that receive the command, the agent runs Chef Solousing the recipes for the configure command as the run_list.When the haproxy::configurerecipe runs, the recipe detects new application servers from the configuration JSON that AWSOpsWorks sends to every instance when there is a configuration change.The recipe then updatesthe HAProxy configuration appropriately.

If you terminated an application server instance, AWS OpsWorks sends a configure commandto all instances and the haproxy::configure recipe would detect that an application serverinstance has disappeared and update the HAProxy configuration appropriately by removing theinstance from its list of target instances.

API Version 2013-02-1838

AWS OpsWorks User GuideStep 3. Scale out by adding another server instance and

a load balancer

Page 45: Opsworks amazon

AWS OpsWorks uses the Configure event to communicate changes to the stack, its layers, orits instances. The recipes for each built-in layer type have logic that helps configure an instanceof a particular layer type appropriately. In this case, the configure recipes for HAProxy layer hadthe logic to determine that an application server instance was added and updated the loadbalancer config to include it. If you like to see the details, go tohttps://github.com/aws/opsworks-cookbooks.git and examine the haproxy::configure recipe, inparticular.

NoteIf you have multiple application server layers in your stack (for example, a Rails AppServer layer and a PHP App Server layer), the HAProxy instance would add both layers'instances to the list of instances to route to. To route traffic to a particular layer'sinstances, you need to create a custom recipe to configure the load balancer that way.

Congratulations! You’ve learned how to turn a single-instance application into a scaled-out application.

Step 4. Add a monitoring serverIn the first three steps, you saw the rich logs that AWS OpsWorks provides for Setup and Deploy eventsas well as the load balancer traffic statistics provided by HAProxy. Just like EC2 instances you manageyourself, the AWS OpsWorks instances have their metrics available in Amazon CloudWatch so that youcan monitor the metrics for those instances or set alarms based on them.

AWS OpsWorks gives you additional monitoring capabilities with Ganglia. For more information aboutGanglia, go to http://ganglia.info. AWS OpsWorks has a Ganglia monitoring agent on each instance thatit manages. When you add a Ganglia layer and start an instance of that layer, the Ganglia agents on theAWS OpsWorks instances report metrics to the Ganglia instance.You can view the monitoring metricsfor your instances by going to the monitoring page of the Ganglia instance.The monitoring page is securedusing the user name and password from the Ganglia layer settings.

Let's try it out.

1. Add a Monitoring Server Layer

On the page for your stack (MyStack), click Layers in the left navigation pane. On the Layers page,click + Layer. For Layer type, select Ganglia, which provides a blueprint for Ganglia monitoringserver instances. Make a note of the password for Ganglia password; you’ll use it later. Keep thedefaults for the other settings, and click Add layer.

2. Add an Instance to the Ganglia Layer

Add an instance for the Ganglia Monitoring Master layer and start it.

API Version 2013-02-1839

AWS OpsWorks User GuideStep 4. Add a monitoring server

Page 46: Opsworks amazon

a. On the Layers page, in the Ganglia row, click Add an instance. On the Instances page, underGanglia, click Add an instance. Keep the defaults and click Add instance.

b. In the Actions column for the new Ganglia instance (monitoring-master1), click start and waitfor the Status to change to online.

3. View the Monitoring Metrics

View the metrics for your stack.

a. Open the Ganglia monitoring page: In the monitoring-master1 row, click the IP address in thePublic IP column.

To access the monitoring metrics, you will be prompted for a user name and password.

b. If you don't remember your Ganglia user name and password, open the Ganglia layer's pageand get the Ganglia password and Ganglia user name under Settings.

c. Enter the Ganglia user name and password into the dialog box that is prompting you forcredentials, and click OK.

d. View the monitoring metrics for the instances in your stack.

API Version 2013-02-1840

AWS OpsWorks User GuideStep 4. Add a monitoring server

Page 47: Opsworks amazon

Step 5. Clean up to avoid unwanted costsWhen you created layers and launched instances within your stack, you began using AWS resources forwhich you are charged based on your usage. If you are done with your stack, you should stop your stackand free its resources so that you do not incur any unwanted charges. If you don’t need the stack anymore,you can also delete the stack.

Before you can delete your stack, you need to delete all the resources within the stack.

1. On the Instances page, click Stop all instances. When prompted to confirm, click Yes, stop.

AWS OpsWorks terminates all instances so no further Amazon EC2 instance charges will be incurred.

2. Delete the instances.

a. Scroll to the PHP App Server layer. In the row for the first instance (it should be namedphp-app1), click delete and then click Yes, delete.

When AWS OpsWorks asks you to confirm the deletion, you’ll see the dependent resources(such as EBS volumes and Elastic IP addresses) that the instance was using and you will beable to choose whether to keep them. If you want to keep them, clear the check boxes for theresources you want to keep. For this walkthrough, keep them checked so that you completelyclean up the resources that you used.

API Version 2013-02-1841

AWS OpsWorks User GuideStep 5. Clean up to avoid unwanted costs

Page 48: Opsworks amazon

b. Repeat the previous step for the second PHP App Server instance (php-app2), the HAProxyinstance (lb1), MySQL instance (db-master-1), and Ganglia instance (monitoring-master1).

3. Delete the layers.

a. In the left navigation pane, click Layers. On the Layers page, in the Actions column for PHPApp Server, click delete and then click Yes, delete.

b. Repeat the previous step for MySQL, HAProxy, and Ganglia.

4. Delete your app. In the left navigation pane, click Apps. On the Apps page, in the Actions columnfor SimplePHPApp, click delete and then click Yes, delete.

Your stack should now have no layers and no apps.

5. Delete the stack. In the left navigation pane, click Stack. Click Delete stack and then click Yes,delete.

Your stack is now deleted and removed from the stacks list.

What's Next?In this walkthrough, you were able to do the following:

• Create a stack.

• Add layers and launch instances for those layers.

• Deploy two versions of an app.

API Version 2013-02-1842

AWS OpsWorks User GuideWhat's Next?

Page 49: Opsworks amazon

• Use recipes from a custom Chef cookbook to configure an app during its deployment.

• Scale out your application server layer by adding another instance of a server and place them behinda load balancer.

• Set up monitoring for the instances in your stack with Ganglia.

You should now have a basic understanding of how to use AWS OpsWorks stacks and layers to managegroups of Amazon EC2 instances. AWS OpsWorks has additional features that make it simpler to manageand scale out your stack:

• Automatic scaling (p. 98)

• Creating and using custom layers (p. 79)

• Using IAM (p. 158) to give users permissions to manage and use AWS OpsWorks resources

• Auto healing (p. 67) to automatically detect failed instances and restart them

Walkthrough: Deploying a PHP Application thatLeverages the AWS SDK for PHP, Amazon S3,and Custom Metadata

A common architecture for building a web application with AWS products includes a set of applicationservers running your application, a database that the application uses to store relational data, and anAmazon S3 bucket to store large items such as images or other media files.This walkthrough demonstratesthis approach.

This walkthrough guides you through several useful tasks:

• Create a stack for a PHP web application, called PhotoApp, that enables users to post an image alongwith a caption and lets site visitors see all the posted images.

• Create instances in the PHP App Server and MySQL layers for PhotoApp to use. Add recipes tocustomize the Setup event of the PHP App Server layer to install the AWS SDK for PHP. Then addrecipes to the Deploy event for the MySQL layer to add the necessary table to the PhotoApp databaseand for the PHP App Server layer to connect to the database so it can read and write to the table.

• Set up an Amazon S3 bucket for PhotoApp to use and create an instance profile that has the appropriateprivileges to list the objects in the bucket and upload new objects.

• Assign the instance profile to your PHP App Server layer, enabling PhotoApp to read and upload imagefiles when it’s running on your PHP App Server instance.

• Use an AWS CloudFormation template to set up the bucket and instance profile.

• Use the custom JSON feature to pass metadata (the bucket name) to the app deploy recipe so thatPhotoApp will know the location of the bucket to use.

Let's get started.

NoteWe're assuming you have tried the basics in AWS OpsWorks and are signed up for AWSOpsWorks and AWS. If you have signed up for other AWS services, you are automatically signedup for all services so you can skip this step. If you haven't, go to http://aws.amazon.com/opsworksand sign up.Also, be aware that this walkthrough dives deep in key areas. If you haven't used OpsWorksbefore and want a thorough walkthrough of the basic AWS OpsWorks features, you should checkout the Walkthrough: Deploy a Web App and Learn AWS OpsWorks Basics (p. 6) first.

API Version 2013-02-1843

AWS OpsWorks User GuideWalkthrough: Deploying a PHP Application that

Leverages the AWS SDK for PHP, Amazon S3, andCustom Metadata

Page 50: Opsworks amazon

Step 1. Create the Amazon S3 bucket and instanceprofile to use in your appBefore you create a stack and deploy an app, you typically create or configure resources that the stackand app require to run. For this step, you deploy an app that, once it is running, lists, reads, and writesobjects to an Amazon S3 bucket. Additionally, the PHP App Server that hosts the app needs an IAMinstance profile that the app can use to have that level of privilege to access the bucket. In this step, youuse AWS CloudFormation—a simple way to create AWS resources by using a template—to create thebucket and instance profile.

1. Copy the following AWS CloudFormation template to a text file and save it as appserver.template.

{ "AWSTemplateFormatVersion" : "2010-09-09", "Resources" : { "AppServerRootRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "ec2.amazonaws.com" ] }, "Action": [ "sts:AssumeRole" ] } ] }, "Path": "/" } }, "AppServerRolePolicies": { "Type": "AWS::IAM::Policy", "Properties": { "PolicyName": "AppServerS3Perms", "PolicyDocument": { "Statement": [ { "Effect": "Allow", "Action": "s3:*", "Resource": { "Fn::Join" : ["", [ "arn:aws:s3:::", { "Ref" : "AppBucket" } , "/*" ] ] } } ] }, "Roles": [ { "Ref": "AppServerRootRole" } ] } }, "AppServerInstanceProfile": { "Type": "AWS::IAM::InstanceProfile", "Properties": { "Path": "/", "Roles": [ { "Ref": "AppServerRootRole" } ] } }, "AppBucket" : { "Type" : "AWS::S3::Bucket"

API Version 2013-02-1844

AWS OpsWorks User GuideStep 1. Create the Amazon S3 bucket and instance

profile to use in your app

Page 51: Opsworks amazon

} }, "Outputs" : { "BucketName" : { "Value" : { "Ref" : "AppBucket" } }, "InstanceProfileName" : { "Value" : { "Ref" : "AppServerInstanceProfile" } } }}

In a nutshell, the template is a JSON file that defines the AWS resources you want to create. Betteryet, it lets you configure your AWS resources in relation to the other resources you're creating in thetemplate. This template creates the S3 bucket and the instance profile. The instance profile containsa policy that gives permissions to the bucket created. The Outputs section of the template lets youview the actual name of the bucket and instance profile after the resources have been created.You'lluse these output values to help set up your stack and app.

NoteAs you use AWS CloudFormation, you'll see that it also has stacks. Don't be confused.CloudFormation stacks are different from AWS OpsWorks stacks.

2. Sign in to the AWS Management Console and open the AWS CloudFormation console athttps://console.aws.amazon.com/cloudformation/.

3. Click Create Stack.

4. In the Stack Name box, type AppServer.

5. Click Upload a Template File, click Browse, specify the template file you created in the first step,and then click Continue.

6. On the Specify Parameters page, select I acknowledge that this template may create IAMresources box. Click Continue until you reach the last page of the wizard. Then click Close.

7. On the AWS CloudFormation console, select the stack AppServer in the list.

8. Wait a few minutes and click Refresh in the upper right corner.You may have to click Refresh afew times until Status changes to CREATE_COMPLETE.

9. In the pane below the list, click the Outputs tab.

10. Copy the values for BucketName and InstanceProfileName and paste them somewhere convenient;you will use them in later steps.

You now have an Amazon S3 bucket and an instance profile to use for PhotoApp.

Step 2. Create the stack and set it up to use thecookbook repositoryWhen you first create a stack, you set some basic properties for the stack such as the defaults used forlayers and instances.You can also specify the repository containing the cookbooks you use to helpconfigure the instances in your stack. For PhotoApp, you use the photoapp cookbook in the AWS OpsWorksexample Git repository: https://github.com/amazonwebservices/opsworks-example-cookbooks.git. Let'screate the stack and set it up to use this cookbook repository.

1. Log in to the AWS OpsWorks console (https://console.aws.amazon.com/opsworks/home).

2. If you're on the first run page, click Add your first Stack. Otherwise, from the Select Stack menu,click Add stack. On the Add Stack page, click Advanced >>, and set the following values:

API Version 2013-02-1845

AWS OpsWorks User GuideStep 2. Create the stack and set it up to use the

cookbook repository

Page 52: Opsworks amazon

NameType a name for your new stack: PhotoSite.

Default IAM Instance ProfileKeep the default. This should be aws-opsworks-ec2-role. This setting lets you specify aninstance profile that will be associated with the instances that are launched in the PhotoSitestack. The instance profile identifies an IAM role that provides credentials used in the instance.The aws-opsworks-ec2-role instance profile has no privileges to access any of your AWSresources. Usually, you'll want this as your default so that instances have no privileges to startwith. In this walkthrough, the MySQL instance that we create does not have any applicationsthat require direct access to AWS resources; however, the PHP App Server instance does requireaccess to an Amazon S3 bucket.To give PHP App Server instances those privileges, you specifythe instance profile you created in Step 1 on the PHP App Server layer.You'll keep the defaultaws-opsworks-ec2-role for the MySQL layer.

Default SSH keyFrom Existing Keys, select an EC2 key pair that you can use to access the instances in thestack via SSH so that you can debug on your instances if you need to.You use this setting tospecify a key pair that AWS OpsWorks will set up, by default, on every instance in the stack sothat users with the private portion of the key can access instances using SSH.You can alsoassign SSH keys to individual IAM users that they can use to access instances. For information,see Setting an IAM User's Public SSH Key (p. 198). In this step, you just need to pick an SSHkey pair that you can use.

Custom Chef JSONType the following JSON, but replace yourbucketname with the bucket you created in Step 1.

{"photobucket" : "yourbucketname"}

The bucket name generated by AWS CloudFormation looks something like this:appserver-appbucket-1jfpv65rkho5e. If that were your bucket name, your JSON would bethis:

{"photobucket" : "appserver-appbucket-1jfpv65rkho5e"}

For each lifecycle event, AWS OpsWorks sends a stack configuration JSON to every instancein the PhotoSite stackAWS OpsWorks incorporates your custom JSON into the stack configurationJSON as a top-level node. The appsetup.rb recipe used to configure the PHP App Serverinstances reads this node from the stack configuration JSON and sets a PHP variable thatPhotoApp uses to get the name of the bucket to use to upload the photos. We cover theappsetup.rb in more detail in Step 3.

Note that you also have the option of specifying custom JSON with an app deployment. In thiswalkthrough, you are putting the custom JSON in the stack because it will be passed to everyinstance and persists until you delete or change it in the stack settings. (The location of thebucket is something that usually should stay the same through most of the lifetime of the app.)The attributes can therefore be used by a recipe tied to any event on any instance. For appdeployment, you typically use custom JSON to specify data you want to use during the executionof the Deploy command but do not want to persist (for example, sensitive data such aspasswords).

You could also use custom deployment JSON for testing. For example, suppose you wanted tochange the Amazon S3bucket for PhotoApp and test the change on a single instance.You coulddeploy the app so that it targets a single instance and use custom JSON to specify a new bucket.The custom deployment JSON then overrides the original custom JSON photobucket attributewith the new Amazon S3 bucket. When you are ready to switch all the instances in the layer tothe new bucket, you can change the custom JSON for the stack and deploy the app again to allinstances.

API Version 2013-02-1846

AWS OpsWorks User GuideStep 2. Create the stack and set it up to use the

cookbook repository

Page 53: Opsworks amazon

Stack colorPick a color that helps you identify this stack in the list of stacks. This can be helpful if you havemany stacks.

3. Set Use custom Chef cookbooks to Yes. For Repository type, select Git, and for RepositoryURL, specify git://github.com/amazonwebservices/opsworks-example-cookbooks.git.Then click Save.

4. Keep the rest of the defaults and click Add stack to create the stack.

When you first create a stack, you select general settings that AWS OpsWorks uses to manage yourstack, such as the defaults used when launching instances (operating system, hostname template,region, Availability Zone, SSH key). It makes sense to pick good defaults that match what you wantto use in your stack: For example, you may want to use Amazon Linux or Ubuntu as the operatingsystem for all instances in the stack.You should consider having least privilege defaults, such as ausing an SSH key that is accessible only to those people who require it.

Step 3. Add the PHP App Server and MySQL layersand give them custom recipesAfter you create the stack, you add layers and adjust their settings for apps that need any additionalconfiguration, such as extra volumes or custom recipes for particular lifecycle events. In this step, youadd custom recipes to the Deploy event of each layer so that the MySQL instances have a table createdfor the app and the PHP App Server instances are configured to use both that database and the bucketyou specified in the stack's custom JSON. Let's do that now.

1. On the PhotoSite page, click Add a layer.

API Version 2013-02-1847

AWS OpsWorks User GuideStep 3. Add the PHP App Server and MySQL layers and

give them custom recipes

Page 54: Opsworks amazon

2. On the Add Layer page, select PHP App Server for Layer type. Then click Add layer.

When the layer is ready, AWS OpsWorks displays the stack's Layers page.

On the Layers page, in the PHP App Server row, click edit in the Actions column.

3. In the Custom Chef recipes section, type photoapp::appsetup for Deploy and click the + icon.

The appsetup.rb recipe is essentially the same as the one we used in Step 2 (p. 22) of Walkthrough:Deploy a Web App and Learn AWS OpsWorks Basics (p. 6). For a discussion of how the processingof the db-connect.php.erb template works, go to that section (p. 29). The main difference is thefollowing script resource. (We cover another important in Step 3.)

script "install_composer" do interpreter "bash" user "root" cwd "#{node[:deploy][:myphotoapp][:deploy_to]}/current" code <<-EOH curl -s https://getcomposer.org/installer | php php composer.phar install EOHend

API Version 2013-02-1848

AWS OpsWorks User GuideStep 3. Add the PHP App Server and MySQL layers and

give them custom recipes

Page 55: Opsworks amazon

The script resource does the following:

• It enables you to specify a script to run.

• The interpreter attribute specifies the script interpreter that will run the script.

• The cwd attribute specifies the current working directory that the script will use. In this case, it'sthe directory where the app is installed.

• The code attribute contains the code for the script, with <<-EOH marking the beginning of the scriptand EOH marking the end.

• The script then uses curl to download Composer and runs Composer's install command toinstall the dependencies for the sample application.

Composer uses the composer.json file at the root of the application directory to read the list ofdependencies it should install; One of the dependencies is the AWS SDK for PHP 2, which the sampleapplication uses to read and write to the bucket.You can view the composer.json file athttps://github.com/amazonwebservices/opsworks-demo-php-photo-share-app.git to see all the otherdependencies it installs.

As discussed in Step 2, the appsetup recipe adds another variable, s3bucket, that the templateresource uses to define S3_BUCKET in the db-connect.php.erb template.

variables( :host => (deploy[:database][:host] rescue nil), :user => (deploy[:database][:username] rescue nil), :password => (deploy[:database][:password] rescue nil), :db => (deploy[:database][:database] rescue nil), :table => (node[:photoapp][:dbtable] rescue nil), :s3bucket => (node[:photobucket] rescue nil) )

4. In the IAM instance profile section, click the Layer profile list and select the instance profile youcreated in Step 1.

As discussed in Step 2, you set the instance profile only for the PHP App Server layer because thePHP App Server instances are the only ones that need access to the bucket. For the MySQL instance,you keep the default, which has no access to AWS resources.

5. Click Save.

6. Click Layers in the left column. On the Layers page, click + Layer.

7. On the Add Layer page, select MySQL for Layer Type. Then click Add layer.

API Version 2013-02-1849

AWS OpsWorks User GuideStep 3. Add the PHP App Server and MySQL layers and

give them custom recipes

Page 56: Opsworks amazon

8. In the MySQL row, click edit in the Actions column.

9. In the Custom Chef recipes section, type photoapp::dbsetup in the Deploy field and click the+ icon.

The dbsetup.rb recipe is essentially the same as the one we used in Step 2 (p. 22) of Walkthrough:Deploy a Web App and Learn AWS OpsWorks Basics (p. 6). For a discussion of how that recipeworks, go to that section (p. 27). The only difference is the schema of the table, which has id, url,and caption columns to support PhotoApp. The url column is used to store the URL for the locationof the photo (where the file stored in the Amazon S3 bucket).

node[:deploy].each do |app_name, deploy| execute "mysql-create-table" do command "/usr/bin/mysql -u#{deploy[:database][:username]} -p#{deploy[:data base][:password]} #{deploy[:database][:database]} -e'CREATE TABLE #{node[:photoapp][:dbtable]}( id INT UNSIGNED NOT NULL AUTO_INCREMENT, url VARCHAR(255) NOT NULL, caption VARCHAR(255), PRIMARY KEY (id) )'" not_if "/usr/bin/mysql -u#{deploy[:database][:username]} -p#{deploy[:data base][:password]} #{deploy[:database][:database]} -e'SHOW TABLES' | grep #{node[:photoapp][:dbtable]}" action :run endend

10. Click Save.

You may have noticed that you did not change the Layer Instance Profile setting. A MySQL instancedoesn't require direct access to any AWS resources, so the instances added for the layer use thedefault instance profile set for the stack. In this step, you kept the stack default as the instance profileoriginally created by AWS OpsWorks, and that instance profile has no privileges for AWS resources.

Step 4. Add and start instances for the PHP AppServer and MySQL layersYou've set up the layers, so now you can create and configure the instances that you need to run PhotoApp.In this step, you add one instance of each layer.

1. In the left column, click Instances.

TipIf you don't see navigation in the left column, either make your browser window larger oruse the Navigation menu on the upper left to navigate to the pages for your stack.

2. In the PHP App Server section, click Add an Instance. Keep the default values and click AddInstance to add the instance to the layer.

3. In the row for your new instance, click start in the Actions column.

4. Repeat the two previous steps to start an instance for the MySQL layer, and wait for the status ofboth instances to change to online.

API Version 2013-02-1850

AWS OpsWorks User GuideStep 4. Add and start instances for the PHP App Server

and MySQL layers

Page 57: Opsworks amazon

Step 5. Add the app and deploy itYou've set up the stack and its layers and started an instance for each layer. Now you need to add theapp and deploy it.

1. Create the app.

a. Click Apps in the left column to display the Apps page. Then click Add an app.

b. Set the following values for the app:

NameType the name for the app: PhotoApp.

App typeSelect PHP.

Document rootType web.

Repository typeSelect Git.

Repository URLTypegit://github.com/amazonwebservices/opsworks-demo-php-photo-share-app.git.

Branch/RevisionLeave this blank.You'll be using the master branch of the repository.

c. Keep the defaults for the other settings and click Add app.

2. Deploy the app.

a. Under Actions, click deploy to deploy PhotoApp to the instance in PHP App Server layer.

By default, all running instances are selected as the target of the command. However, the codefrom the app's repository is installed only on instances of the layer specified as the app's type.AWS OpsWorks sends a deploy command to any other instances that are selected and anycustom deploy recipes specified for the layers of those instances will be run by the agent onthose instances (we exercise this feature in Step 2).

b. Keep the other settings as their defaults and click Deploy.

When the deployment is complete, the Deployment page will display a Status of successful,and the row for php-app1 will display a green check mark.

Step 6.Try the appYou've set everything up and deployed the app. Now let's run it.

1. In the left column, click Instances and click the Public IP in the row for php-app1.

2. Click Add a Photo.You should see the following page in your browser.

API Version 2013-02-1851

AWS OpsWorks User GuideStep 5. Add the app and deploy it

Page 58: Opsworks amazon

3. Click Choose File to select an image file to upload, and type something appropriate for the Caption.Then click Add Photo.

4. Click Go Back to view your photo and caption in the list of all photos submitted.

Congratulations! You've created a stack that hosts a sample application, PhotoApp, and uses the AWSSDK for PHP and Amazon S3 running on instances of PHP App Server and MySQL layers.You alsolearned about useful features such as custom recipes that use scripts and templates, custom JSONmetadata that enables you to pass whatever data you need to your custom recipes, and instance profilesto give instances for a particular layer only the access that they need.

Step 7. Clean up to avoid unwanted costsRemember that when you create layers and launch instances within your stack, you begin using AWSresources and are charged based on your usage. If you are done with your stack, you should stop yourstack and free its resources so that you do not incur any unwanted charges. If you don’t need the stackanymore, you can also delete it. If you don't require the instance profile and bucket you created with AWSCloudFormation, you should delete the AppServer stack you created in Step 1.

1. To delete your instances, layers, apps, and the stack, follow steps similar to those described in Step5. Clean up to avoid unwanted costs (p. 41).

2. To delete the AppServer AWS CloudFormation stack and its resources, follow these steps.

a. Use the Services menu on the upper left to navigate to the AWS CloudFormation console.

b. Select the check box beside AppServer.

c. Click Delete Stack.

d. In the confirmation message that appears, click Yes, Delete.

The status for AppServer changes to DELETE_IN_PROGRESS. To monitor progress, click Refreshperiodically. When AWS CloudFormation completes the deletion of the stack, it removes the stackfrom the list.

API Version 2013-02-1852

AWS OpsWorks User GuideStep 7. Clean up to avoid unwanted costs

Page 59: Opsworks amazon

Stacks

The stack is the top-level AWS OpsWorks entity. It represents a set of instances that you want to managecollectively, typically because they have a common purpose such as serving PHP applications. In additionto serving as a container, a stack handles tasks that apply to the group of instances as a whole, such asmanaging applications and cookbooks.

For example, a stack whose purpose is to serve PHP applications might look something like the following:

• A set of PHP application server instances, each of which handles a portion of the incoming traffic.

• A load balancer instance, which takes incoming traffic and distributes it across the PHP applicationservers.

• A database instance, which serves as a back-end data store for the PHP application servers.

A common practice is to have multiple stacks that represent different environments. A typical set of stacksconsists of:

• A development stack to be used by developers to add features, fix bugs, and perform other developmentand maintenance tasks.

• A staging stack to verify updates or fixes before exposing them publicly.

• A production stack, which is the public-facing version that handles incoming requests from users.

This section describes the basics of working with stacks.

Topics

• Create a New Stack (p. 54)

• Update a Stack (p. 56)

• Clone a Stack (p. 57)

• Run Stack Commands (p. 58)

• Use Custom JSON to Modify the Stack Configuration JSON (p. 60)

• Shut Down a Stack (p. 61)

API Version 2013-02-1853

AWS OpsWorks User Guide

Page 60: Opsworks amazon

Create a New StackTo create a stack

1. On the AWS OpsWorks dashboard, click Add stack.

2. On the Add Stack page, configure the stack settings:

Name[Required] A designation used to identify the stack in the AWS OpsWorks console.

Default operating system[Optional] The operating system that is installed by default on each instance: Amazon Linux orUbuntu. The default is Amazon Linux.

Region[Optional] The default AWS region where the instances will be launched.

Default Availability Zone[Optional] The default AWS Availability Zone where the instances will be launched.

Default SSH key[Optional] The default Secure Shell (SSH) cryptographic key that instances will use to authenticatean SSH connection. The default value is none.

Hostname theme[Optional] A string that is used to generate a default hostname for each instance. The defaultvalue is Layer Dependent, which uses the short name of the instance's layer and appends aunique number to each instance. For example, the role-dependent Load Balancer theme rootis "lb". The first instance you add to the layer is named "lb1", the second "lb2", and so on.

Stack color[Optional] The hue used to represent the stack on the AWS OpsWorks console.You can usedifferent colors for different stacks to help distinguish, for example, among development, staging,and production stacks.

API Version 2013-02-1854

AWS OpsWorks User GuideCreate a New Stack

Page 61: Opsworks amazon

3. To set the advanced options, click Advanced >>, which displays the following:

IAM Role[Optional] The stack's AWS Identity and Access Management (IAM) role, which AWS OpsWorksuses to interact with AWS on your behalf.You should use a role that was created by AWSOpsWorks to ensure that it has all the required permissions. If you don't have an existing AWSOpsWorks role, select New IAM Role to have AWS OpsWorks create a new IAM role for you.For more information, see Setting Permissions When Creating a Stack (p. 198).

Default IAM Instance Profile[Optional] The default role to be associated with the stack's Amazon EC2 instances. If you wantto specify permissions that are needed by apps running on EC2 instances (for example, if yourapps access Amazon S3 buckets), you should choose an existing instance profile (role) that hasthe right permissions. Otherwise, you should select New IAM Instance Profile to let AWSOpsWorks create the instance profile for you.

Use custom Chef CookbooksSelecting Yes lets you use custom Chef cookbooks to customize the behavior of your layers.The default setting is No. For more information, see Cookbooks and Recipes (p. 198).

If you select Yes, as shown in the example, Add Stack displays several additional options:

Repository typeThe custom cookbook repository type.

Repository URLThe custom cookbook repository URL.

Deploy SSH key[Optional] An SSH key that instances can use to access a private Git repository.The defaultvalue is none. For more information, see Using Deploy Keys (p. 198).

Branch RevisionThe cookbook version.

API Version 2013-02-1855

AWS OpsWorks User GuideCreate a New Stack

Page 62: Opsworks amazon

For more information on cookbooks, see Installing Custom Cookbooks (p. 198).

Custom Chef JSON[Optional] Lets you specify custom JSON, which is incorporated into the stack configurationJSON object that is passed to instances and used by recipes. For more information, see UseCustom JSON to Modify the Stack Configuration JSON (p. 60).

4. When all the settings are as you want them, click Add stack.

NoteYou can override most default settings when you create instances.

Update a StackAfter you have created a stack, you can update the configuration at any time.

To edit a stack

1. On the Stack page, click Stack settings, and then click Edit.

2. On the Settings page, make the changes that you want.The settings are the same as those discussedin Create a New Stack (p. 54). Refer to that topic for details. However, note the following:

• You can modify any of the settings except the region.

• If you change any of the default instance settings, such as Hostname theme or Default SSH key,the new values apply only to any new instances you create, not to existing instances.

• Changing the Name changes the name that is displayed by the console; it does not change theunderlying short name that AWS OpsWorks uses to identify the stack.

API Version 2013-02-1856

AWS OpsWorks User GuideUpdate a Stack

Page 63: Opsworks amazon

3. When all the settings are as you want them, click Save.

Clone a StackIt is sometimes useful to create multiple copies of a stack. For example, you might want to run the samestack in multiple AWS regions, or you might use an existing stack as a starting point for a new stack. Thesimplest approach is to clone the source stack.

To clone a stack

1. On the AWS OpsWorks dashboard, in the box for the stack that you want to clone, click Actions,and then select clone.

2. On the Clone stack page, modify any configuration settings that you want. Initially, the settings forthe cloned stack are identical to those for the source stack except that the word "copy" is appendedto the stack name. For information about these settings, see Create a New Stack (p. 54). There arealso two additional optional settings:

PermissionsIf the all permissions check box is selected (the default), the source stack permissions areapplied to the cloned stack.

AppsLists apps that are deployed on the source stack. For each app listed, if the corresponding checkbox is selected (the default), the app will be deployed to the cloned stack.

API Version 2013-02-1857

AWS OpsWorks User GuideClone a Stack

Page 64: Opsworks amazon

3. When all the settings are as you want them, click Clone stack.

When you click Clone stack, AWS OpsWorks creates a new stack that consists of the source stack'slayers and optionally its apps and permissions. The layers have the same configuration as the originals,subject to any modifications that you made.However, cloning does not create any instances.You mustadd an appropriate set of instances to each layer of the cloned stack and then start them. As with anystack, you can perform normal management tasks on a cloned stack, such as adding, deleting, or modifyinglayers or adding and deploying apps.

To make the cloned stack operational, start the instances. AWS OpsWorks sets up and configures eachinstance according to its layer membership. It also deploys any applications, just as it does with a newstack.

Run Stack CommandsAWS OpsWorks supports several commands that you can use on a stack to perform the followingoperations:

Install dependenciesInstalls all packages or Ruby gems.

Update dependenciesUpdates all packages or gems.

Update cookbooksDeploys an updated set of custom Chef cookbooks from the repository to the instances.

Execute recipesExecutes a specified set of recipes.

To run a stack command

1. On the AWS OpsWorks dashboard, click the stack that you want.

API Version 2013-02-1858

AWS OpsWorks User GuideRun Stack Commands

Page 65: Opsworks amazon

2. On the stack page, click Run command.

3. On the Run command page, under Settings, click the Command drop-down list and select thecommand that you want to run.

You can specify the following:

CommentAny custom remarks you care to add.

Recipes to executeThis field appears if you select the execute recipes command. Enter the recipes to be executedusing the standard cookbook::recipe format, separated by commas.

Custom Chef JSONA custom JSON object, to be incorporated into the stack configuration JSON. For moreinformation, see Use Custom JSON to Modify the Stack Configuration JSON (p. 60).

InstancesThe instances on which to execute the command. By default, all layers and all running instancesare selected.To run the command only on layers and/or instances that you choose, at the bottomof the page, select the check boxes that correspond to the layers and instances where you wantthe command to run.

API Version 2013-02-1859

AWS OpsWorks User GuideRun Stack Commands

Page 66: Opsworks amazon

4. When all the settings are as you want them, click Deploy to run the command.

NoteYou might see execute_recipes instances on the Deployment and Commands page that youdid not run. This is usually the result of a permissions change, such as granting or removingSSH permissions for a user. When you make such a change, AWS OpsWorks usesexecute_recipes to update permissions on the instances.

Use Custom JSON to Modify the StackConfiguration JSON

For several AWS OpsWorks actions, you can specify custom JSON, which is incorporated into the stackconfiguration JSON object that is passed to instances and used by recipes. The most common use ofcustom JSON is to override the default AWS OpsWorks configuration settings in the stack configurationJSON or the built-in cookbooks with stack-specific values.You can also use custom JSON to add customelements to the stack configuration JSON, which can then be accessed by your custom recipes.

You use custom JSON in one of two ways:

• When you create, update, or clone a stack.

The custom JSON is incorporated into the stack configuration JSON and passed to instances for allsubsequent events.

• When you run a deployment or stack command.

The custom JSON is incorporated into the stack configuration JSON and passed to instances only forthat event.

A custom JSON object must be valid JSON and formatted as follows:

{ "att1": "value1", "att2": "value2" ...}

For example, suppose that you want to change some default Apache configuration settings. They aredefined in the built-in apache2 cookbook's apache.rb file, which you can view athttps://github.com/aws/opsworks-cookbooks. Simply take the following steps:

1. On the stack page, click Stack Settings and then click Edit.

2. In the Custom Chef JSON box, add an appropriate object. In this example, the object modifies twoApache configuration settings, the keep-alive timeout and the log rotate schedule.

API Version 2013-02-1860

AWS OpsWorks User GuideUse Custom JSON to Modify the Stack Configuration

JSON

Page 67: Opsworks amazon

For all subsequent lifecycle events, AWS OpsWorks passes the instance's updated stack configurationJSON with the custom Apache configuration values overriding the defaults. Recipes can retrieve customvalues by using standard Chef node syntax, which maps directly to the hierarchy in the JSON object. Forexample, recipes can retrieve the new keepalivetimeout value by using the following:

node[:apache][:keepalivetimeout]

If you want to do string interpolation, enclose the node value in curly brackets, as follows.

#{node[:apache][:keepalivetimeout]}

Custom JSON is not limited to overriding standard values; you can also specify values for arbitrary JSONattributes. This approach can be a useful way to pass data to your custom recipes. AWS OpsWorks addsthose attributes to the stack configuration JSON, and your custom recipes can retrieve the values byusing standard Chef syntax.

Shut Down a StackIf you no longer need a stack, you can shut it down.

API Version 2013-02-1861

AWS OpsWorks User GuideShut Down a Stack

Page 68: Opsworks amazon

To shut down a stack

1. On the AWS OpsWorks dashboard, click the stack that you want to shut down.

2. In the navigation pane, click Instances.

3. On the Instances page, click Stop all Instances.

4. After the instances have stopped, for each instance in the layer, click delete in the Actions column.When prompted to confirm, click Yes, Delete.

5. When all the instances are deleted, in the navigation pane, click Layers.

6. On the Layers page, for each layer in the stack, click delete. When a confirmation prompt appears,click Yes, Delete.

7. When all the layers are deleted, in the navigation pane, click Apps.

8. On the Apps page, for each app in the stack, click delete in the Actions column. When promptedto confirm, click Yes, Delete.

API Version 2013-02-1862

AWS OpsWorks User GuideShut Down a Stack

Page 69: Opsworks amazon

9. When all the apps are deleted, in the navigation pane, click Stack.

10. On the stack page, click Delete stack. When prompted to confirm, click Yes, Delete.

API Version 2013-02-1863

AWS OpsWorks User GuideShut Down a Stack

Page 70: Opsworks amazon

Layers

A layer is essentially a blueprint for an Amazon EC2 instance. It defines which packages and applicationsare installed, how they are configured, and so on. For example, an instance that is a member of a PHPApp Server layer has an Apache2 server with mod_php installed, and usually at least one PHP application.

Every stack has at least one and usually several layers, which determine the stack's functionality. Forexample, a stack with a PHP App Server layer can serve PHP applications, a stack with a load balancerlayer can distribute incoming traffic across its application servers, and so on.

As you work with layers, keep these characteristics in mind:

• Each layer in a stack must have at least one instance and can optionally have multiple instances.

For example, a PHP App Server layer typically has multiple instances but a Ganglia layer typically hasonly one.

• Each instance in a stack must be a member of at least one layer.

You cannot configure an instance directly, except for some basic settings such as the SSH key andhostname.You must create and configure an appropriate layer, and add the instance to the layer.

Instances can optionally be a member of multiple layers. In that case, AWS OpsWorks runs the recipesto install and configure packages, deploy applications, and so on for each of the instance's layers. However,an instance's layers must be compatible with each other. For example, the HAProxy layer is not compatiblewith the Static Web Server layer because they both bind to port 80. An instance can be a member of onlyone of those layers. For more information, see Appendix A: AWS OpsWorks Layer Reference (p. 198).

By assigning an instance to multiple layers, you could, for example do the following:

• Reduce expenses by hosting the database server and the load balancer on a single instance.

Assign an instance to both the HAProxy and MySQL layers.

• Use one of your application servers for administration.

Create a custom administrative layer and add one of the application server instances to that layer. Theadministrative layer's recipes configure that application server instance to perform administrative tasks,and install any additional required software. The other application server instances are just applicationservers.

API Version 2013-02-1864

AWS OpsWorks User Guide

Page 71: Opsworks amazon

AWS OpsWorks includes a set of standard layers that address common use cases such as serving PHPapplications or static HTML pages.You can use these layers as they are or customize them (p. 138) byimplementing custom Chef recipes and assigning them to the appropriate lifecycle events. If none of thestandard layers meet your requirements, even with customization, AWS OpsWorks includes a customlayer, which you can use to handle a wide variety of scenarios. Each stack can have at most one of eachstandard layer, but you can implement any number of custom layers.

This section describes how to create each AWS OpsWorks layer. For more information about availablelayers, including standard recipes, compatibility with other layers, and so on, see Appendix A: AWSOpsWorks Layer Reference (p. 198).

Topics

• Layer Basics (p. 65)

• Load Balancer Layers (p. 70)

• MySQL Layer (p. 77)

• Application and Web Server Layers (p. 77)

• Custom Layers (p. 79)

• Other Layers (p. 87)

Layer BasicsThis section describes how to perform operations that are common to all layers.

Topics

• How to Create a Layer (p. 65)

• How to Edit a Layer (p. 66)

• Using Auto Healing to Replace Failed Instances (p. 67)

• How to Delete a Layer (p. 68)

How to Create a LayerWhen you create a new stack, you see the following page:

To add the first layer

1. Click Add a Layer.

2. On the Add Layer page, select the appropriate layer, which displays the layer's configuration options.

3. Configure the layer appropriately and click Add Layer to add it to the stack. The following sectionsdescribe how to configure the various layers.

4. Add instances to the layer and start them.

API Version 2013-02-1865

AWS OpsWorks User GuideLayer Basics

Page 72: Opsworks amazon

NoteIf an instance is a member of multiple layers, you must add it to all of them before you startthe instance.You cannot add an online instance to a layer.

To add more layers, open the Layers page and click + Layer to open the Add Layer page.

When you start an instance, AWS OpsWorks automatically runs default setup and configuration recipesfor each of the instance's layers to install and configure the appropriate packages and deploy theappropriate applications.You can customize a layer's setup and configuration process in a variety ofways, such as by assigning custom recipes to the appropriate lifecycle events. AWS OpsWorks runscustom recipes after the standard recipes for each event. For more information, see Cookbooks andRecipes (p. 198).

The following layer-specific sections describe how handle Steps 2 and 3 for the various AWS OpsWorkslayers. For more information how to add instances, see Adding an Instance to a Layer (p. 198).

How to Edit a LayerAfter you create a layer, some properties (such as AWS region) are immutable, but you can change mostof the layer configuration at any time. Editing the layer also provides access to configuration settings thatare not available when you create the layer.

To edit a layer

1. In the left column, click Layers.

2. On the Layers page, click a layer to open the details page, which shows the current configuration.

3. On the upper right, click Edit.

4. On the Edit page, change desired settings. Then click Save.

API Version 2013-02-1866

AWS OpsWorks User GuideHow to Edit a Layer

Page 73: Opsworks amazon

You can edit the following standard settings for all layers:

Custom Chef recipesYou can assign custom Chef recipes to the layer's lifecycle events.

Additional EBS volumesYou can add or remove Amazon Elastic Block Store volumes. However, note the following:

• If you add a volume, every new instance gets the new volume but AWS OpsWorks does not updatethe existing instances.

• If you remove a volume, it applies only to new instances; the existing instances retain their volumes.

Elastic IPsYou can enable or disable whether Elastic IP addresses are automatically assigned to instances.

OS packagesYou can specify additional OS packages to be installed on new instances.To install the new packageson existing instances, run the update_packages command (p. 58).

Auto healingYou can enable or disable auto healing for the layer's instances, which is immediately effective forall instances.

Some layers have additional layer-specific settings that you can edit; these appear at the top of the page.For example, the MySQL Layer page lets you modify the MySQL root password and specify whether toinclude the password in the stack configuration JSON for all of the stack's instances.

Using Auto Healing to Replace Failed InstancesEvery instance has an agent that polls AWS OpsWorks. If auto healing is enabled for a layer and anagent on one of the layer's Amazon EC2 instances disconnects or times out and does not reconnectwithin a short time period (typically 3-5 minutes), AWS OpsWorks automatically "heals" the instance. Todo this, AWS OpsWorks first terminates the Amazon EC2 instance to make sure it is shut down. Thenstarts a new Amazon EC2 instance with the same hostname, mounted Amazon EBS volumes, layers,and configuration.

If the instances have attached Amazon EBS volumes, auto healing affects them as follows:

• If an instance auto heals, AWS OpsWorks reattaches the old volumes and attaches any new volumesthat were added after the instance was started.

API Version 2013-02-1867

AWS OpsWorks User GuideUsing Auto Healing to Replace Failed Instances

Page 74: Opsworks amazon

• If a layer specifies an attached volume and you delete it from an instance by using the Amazon EC2console, an auto healed instance gets the volume back but not the data.

ImportantIf you have auto healing enabled, be sure to do the following:

• Use AWS OpsWorks to stop instances. If you stop an instance manually (that is, by using theAmazon EC2 console or tools, or typing halt-p now on the console), AWS OpsWorks autoheals the instance.

• If your instance gathers data that you want to keep, make sure to store it on Amazon EBSvolumes. Auto healing terminates failed instances so any data not stored on Amazon EBSvolumes is lost.

To enable or disable auto healing for a layer

1. On the Layers page, click the layer of interest to open the details page. Then click Edit to edit thelayer settings.

2. For Auto healing enabled, use the toggle button to turn auto healing on or off.

How to Delete a LayerIf you no longer need a layer, you can delete it from your stack.

To delete a layer

1. In the left column, click Instances.

2. On the Instances page, under the name of the layer you want to delete, click stop in the Actionscolumn for each instance.. Click Yes, stop when prompted.

API Version 2013-02-1868

AWS OpsWorks User GuideHow to Delete a Layer

Page 75: Opsworks amazon

3. After each instance has stopped, click delete for each to remove it from the layer. Click Yes, deletewhen prompted.

4. In the left column, click Layers.

5. On the Layers page, click delete in the Actions column for the layer.

API Version 2013-02-1869

AWS OpsWorks User GuideHow to Delete a Layer

Page 76: Opsworks amazon

Load Balancer LayersA stack typically requires multiple application server instances to effectively handle incoming applicationrequests.You can improve an application's availability, performance, and scalability by adding a loadbalancer to your stack. A load balancer exposes a single public IP address to represent the application,receives all incoming requests, distributes them evenly to the stack's application server instances, receivesthe responses, and returns them to the caller.

AWS OpsWorks includes two built-in ways to balance your application's load.

Elastic Load BalancingElastic Load Balancing is an AWS service that automatically distributes incoming application trafficacross multiple Amazon EC2 instances. Such a layer has several advantages:

• Automatically scales request handling capacity in response to incoming application traffic

• Stores SSL certificates by using IAM credentials, allowing you to control who can see your privatekeys

• Spans multiple Availability Zones for reliability but provides a single DNS name for simplicity,eliminating the need for techniques such as round robin DNS to provide availability at the loadbalancer tier

• Uses Amazon CloudWatch to report metrics such as request count and request latency

• Supports SSL termination at the Load Balancer by default, including offloading SSL decryptionfrom application instances, centralized SSL certificate management, and encryption to back-endinstances with optional public key authentication

For more information, see Elastic Load Balancing Developer Guide.

HAProxyThe HAProxy layer uses Chef recipes to install HAProxy on EC2 instances that you run and control.It gives you deep control over the load balancer's functionality, including the ability to customize theconfiguration by overriding attributes, modifying configuration files, and so on. However, the greateramount of control is accompanied by higher degree of responsibility for issues such as capacitymanagement and configuration for availability. For more information, see HAProxy.

It can sometimes be useful to use both load balancers. For example, you could use an Elastic LoadBalancing load balancer to distribute traffic to a set of HAProxy instances in different Availability Zones,each of which distributes its traffic to a set of application servers.

Topics

• Elastic Load Balancing (p. 70)

• HAProxy Layer (p. 73)

Elastic Load BalancingElastic Load Balancing works somewhat differently than other built-in layers. Instead of creating a layerand adding instances to it, you attach an Elastic Load Balancing load balancer to one of your existinglayers.You can attach an Elastic Load Balancing instance to any layer, but it is most commonly attachedto application server layers. AWS OpsWorks then registers the layer's instances with the service, whichautomatically distributes incoming application traffic across the layer's instances. In addition, Elastic LoadBalancing does the following:

• Detects unhealthy Amazon EC2 instances and reroutes traffic to the remaining healthy instances untilthe unhealthy instances have been restored

• Automatically scales request handling capacity in response to incoming traffic

API Version 2013-02-1870

AWS OpsWorks User GuideLoad Balancer Layers

Page 77: Opsworks amazon

If you have an existing stack whose IAM service role does not grant permissions for Elastic Load Balancing,you must first have an administrator update the role's policy, so that it can interact with Elastic LoadBalancing on your behalf. The Stack page display the following message, and you can click Update tohave AWS OpsWorks update the policy.

You can also update your service role policies manually, by using the IAM console.The following exampleshows the default policy for the service role, including Elastic Load Balancing:

{"Statement": [{"Action": ["ec2:*", "iam:PassRole", "cloudwatch:GetMetricStatistics", "elasticloadbalancing:*"], "Effect": "Allow", "Resource": ["*"] }]}

To use Elastic Load Balancing with your stack, you must first create one or more load balancers by usingthe Elastic Load Balancing console, CLI, or API. Be sure to specify a health check ping path that isappropriate for your application. The default ping path is /index.html. If your application does not useindex.html, you must specify an appropriate path or the health check will fail. For example, the SimplePHPapplication used in Walkthrough: Deploy a Web App and Learn AWS OpsWorks Basics (p. 6) does notuse index.html, and the ping path for that app is /. For more information, see Elastic Load Balancing.

Each Elastic Load Balancing instance can handle only one layer, so you must create a separate instancefor each layer that you want to balance.

ImportantYou must create a separate Elastic Load Balancing load balancer for each layer in each stackthat you want to balance and use it only for that purpose. It is possible to register Amazon EC2instances with the load balancer that are not managed by AWS OpsWorks. However, if you doso, the results will be unpredictable. A recommended practice is to assign a distinctive name toeach Elastic Load Balancing load balancer that you plan to use with AWS OpsWorks, such asMyStack1-ELB-RailsLayer, to avoid using an instance for more than one purpose.

To attach an Elastic Load Balancing load balancer to a layer

1. If you have not yet done so, use the Elastic Load Balancing console, API, or CLI to create a loadbalancer. For more information, see Elastic Load Balancing.

2. Create the layer that you want to have balanced. For more information, see How to Create aLayer (p. 65).

3. In the left column, click Layers.

4. On the Layers page, click Add an ELB.

API Version 2013-02-1871

AWS OpsWorks User GuideElastic Load Balancing

Page 78: Opsworks amazon

5. On the layer's details page, under Elastic Load Balancing, select the load balancer that you wantto attach to the layer and click Save.

AWS OpsWorks automatically registers the layer's instance's when they come online and deregistersinstances when they go offline. OpsWorks also automatically activates and deactivates the instances'Availability Zones.

You can examine a load balancer's properties by going to the Instances page and clicking the appropriateload balancer name.

The ELB page shows the load balancer's basic properties, including its DNS name and the health statusof the associated instances. A green check indicates a healthy instance.You can click on the name toconnect to a server, through the load balancer.

API Version 2013-02-1872

AWS OpsWorks User GuideElastic Load Balancing

Page 79: Opsworks amazon

HAProxy LayerThe AWS OpsWorks HAProxy layer uses HAProxy—a reliable high-performance TCP/HTTP loadbalancer—which is particularly useful for web sites that must crawl under very high loads while requiringpersistence or Layer 7 processing. One small instance is usually sufficient to handle all application servertraffic.

NoteStacks are limited to a single region. To distribute your application across multiple regions, youmust create a separate stack for each region.

To create a HAProxy layer

1. In the left column, click Layers.

2. On the Layers page, click Add a Layer or + Layer. For Layer type, select HAProxy.

The layer has the following configuration settings, all of which are optional.

• HAProxy statistics–Whether the layer collects and displays statistics. The default value is On.

• Statistics URL–The statistics page's URL path.The complete URL is http://DNSNameStatisticsPath,where DNSName is the associated instance's DNS name. The default StatisticsPath value is/haproxy?stats, which corresponds to something like:http://ec2-54-245-151-7.us-west-2.compute.amazonaws.com/haproxy?stats.

• Statistics user name–The statistics page's user name, which you must provide to view the statisticspage. The default value is "opsworks".

• Statistics password–A statistics page password, which you must provide to view the statistics page.The default value is a randomly generated string.

• Health check URL–The health check URL suffix. HAProxy uses this URL to periodically call an HTTPmethod on each application server instance to determine whether the instance is functioning. If thehealth check fails, HAProxy stops routing traffic to the instance until it is restarted, either manually orthrough auto healing (p. 67).The default value for the URL suffix is "/", which corresponds to the serverinstance's home page: http://DNSName/.

• Health check method–An HTTP method to be used to check whether instances are functioning. Thedefault value is OPTIONS and you can also specify GET or HEAD. For more information, see httpchk.

API Version 2013-02-1873

AWS OpsWorks User GuideHAProxy Layer

Page 80: Opsworks amazon

NoteRecord the password for later use; AWS OpsWorks does not allow you to view the passwordafter you create the layer. However, you can reset the password by going to the layer's Editpage and clicking Reset now.

How the HAProxy Layer WorksBy default, HAProxy does the following:

• Listens for requests on the HTTP and HTTPS ports.

You can configure HAProxy to listen on only the HTTP or HTTPS port by overriding the Chef configurationtemplate, haproxy.cfg.erb.

• Routes incoming traffic to instances that are members of any application server layer.

By default, AWS OpsWorks configures HAProxy to distribute traffic to instances that are members ofany application server layer.You could, for example, have a stack with both Rails App Server and PHPApp Server layers, and an HAProxy master distributes traffic to the instances in both layers.You canconfigure the default routing by using a custom recipe.

• Routes traffic across multiple Availability Zones.

API Version 2013-02-1874

AWS OpsWorks User GuideHAProxy Layer

Page 81: Opsworks amazon

If one Availability Zone goes down, the load balancer routes incoming traffic to instances in other zonesso your application continues to run without interruption. For this reason, a recommended practice isto distribute your application servers across multiple Availability Zones.

• Periodically runs the specified health check method on each application server instance to assess itshealth.

If the method does not return within a specified timeout period, the instance is presumed to have failedand HAProxy stops routing requests to the instance. AWS OpsWorks also provides a way to automaticallyreplace failed instances. For more information, see Using Auto Healing to Replace FailedInstances (p. 198).You can change the health check method when you create the layer.

• Collects statistics and optionally displays them on a web page.

ImportantFor health check to work correctly with the default OPTIONS method, your app must return a2xx or 3xx status code.

By default, when you add an instance to a HAProxy layer, AWS OpsWorks assigns it an Elastic IP addressto represent the application, which is public to the world. Because the HAProxy instance's Elastic IPaddress is the application's only publicly exposed URL, you don't have to create and manage publicdomain names for the underlying application server instances.You can obtain the address by going tothe Instances page and examining the instance's public IP address, as shown below. An address thatis followed by (EIP) is an Elastic IP address. For more information on Elastic IP addresses, see ElasticIP Addresses (EIP).

When you stop an HAProxy instance, AWS OpsWorks retains the Elastic IP address and reassigns it tothe instance when you restart it. If you delete an HAProxy instance, by default, AWS OpsWorks deletesthe instance's IP address. To retain the address, clear the Delete instance's Elastic IP option, as shownin the following illustration.

API Version 2013-02-1875

AWS OpsWorks User GuideHAProxy Layer

Page 82: Opsworks amazon

This option affects what happens when you add a new instance to the layer to replace a deleted instance:

• If you retained the deleted instance's Elastic IP address, AWS OpsWorks assigns the address to thenew instance.

• Otherwise, AWS OpsWorks assigns a new Elastic IP address to the instance and you must updateyour DNS registrar settings to map to the new address.

When application server instances come on line or go off line—either manually or as a consequence ofauto scaling (p. 98) or auto healing (p. 67)—the load balancer configuration must be updated to routetraffic to the current set of online instances. This task is handled automatically by the layer's built-inrecipes:

• When new instances come on line, AWS OpsWorks triggers a Configure lifecycle event (p. 133). TheHAProxy layer's built-in Configure recipes update the load balancer configuration so that it also distributesrequests to any new application server instances.

• When instances go off line or an instance fails a health check, AWS OpsWorks also triggers a Configurelifecycle event. The HAProxy Configure recipes update the load balancer configuration to route trafficto only the remaining online instances.

Finally, you can also use a custom domain with the HAProxy layer. For more information, see UsingCustom Domains (p. 198).

Statistics PageIf you have enabled the statistics page, the HAProxy displays a page containing a variety of metrics atthe specified URL.

To view HAProxy statistics

1. On the Layers page, click HAProxy to open the layer's details page.

2. Obtain the HAProxy instance's Public DNS name from the instance's Details page and append thestatistics URL to it. For example:http://ec2-54-245-102-172.us-west-2.compute.amazonaws.com/haproxy?stats.

3. Paste the URL from the previous step into your browser and use the user name and password thatyou specified when you created the layer to open the statistics page, which is shown below.

API Version 2013-02-1876

AWS OpsWorks User GuideHAProxy Layer

Page 83: Opsworks amazon

MySQL LayerA MySQL layer provides a blueprint for instances that function as a MySQL database master. A built-inrecipe creates a database for each application in the application server layers. For example, if you deploya PHP application “myapp,” the recipe creates a “myapp” database.

The MySQL layer has the following configuration settings.

MySQL root user password[Required] The root user password.

Set root user password on every instance[Optional] Whether the root user password is included in the stack configuration JSON that is passedto every instance in the stack. The default setting is Yes.

If you set this value to No, AWS OpsWorks passes the root password only to application serverinstances.

Application and Web Server LayersAWS OpsWorks supports several different application servers, where "application" includes static webpages.

Four simple steps get you started using application server layers:

1. Create a layer and add one of the four available App Server layer types.

2. Add one or more instances to the layer.

3. Create apps and deploy them to the instances. For more information, see Apps (p. 198).

4. If the layer has multiple instances, you can optionally add a load balancer, which distributes incomingtraffic across the instances. For more information, see HAProxy Layer (p. 198).

Topics

• Node.js App Server Layer (p. 78)

• PHP App Server Layer (p. 78)

• Rails App Server Layer (p. 78)

• Static Web Server Layer (p. 79)

API Version 2013-02-1877

AWS OpsWorks User GuideMySQL Layer

Page 84: Opsworks amazon

Node.js App Server LayerThe Node.js App Server layer provides a blueprint for instances that function as JavaScript applicationservers. This layer is based on Node.js and has no standard configuration options.

PHP App Server LayerThe PHP App Server layer provides a blueprint for instances that function as PHP application servers.The PHP App Server layer is based on Apache2 with mod_php and has no standard configuration options.

Rails App Server LayerThe Rails App Server layer provides a blueprint for instances that function as Ruby on Rails applicationservers. The layer features the following configuration options, all of which are optional.

Ruby VersionThe default value is 1.9.3.

Rails StackThe default Rails stack is Apache2 with Phusion Passenger.You can also use Nginx with Unicorn.

Rubygems VersionThe default Rubygems version is 1.8.24.

Passenger VersionIf you have specified Apache2/Passenger, you must specify the Passenger version.The default valueis 3.0.17.

Install and Manage BundlerLets you choose whether to install and manage Bundler. The default value is Yes.

Bundler versionThe default Bundler version is 1.0.10.

API Version 2013-02-1878

AWS OpsWorks User GuideNode.js App Server Layer

Page 85: Opsworks amazon

Static Web Server LayerThe Static Web Server layer provides a template for instances to serve static HTML pages, which caninclude client-side scripting.This layer is based on Nginx and does not include any configuration settings.

Custom LayersIf the standard layers such as Rails App Server don't suit your requirements, even with customization,you can create a fully customized layer. A stack can have any number of such layers.

For example, you can extend the set of built-in layers by implementing a custom layer to support a packagesuch as Redis, which does not have built-in support.You could then use that layer as a blueprint forcreating Redis server instances.

It can be useful to combine custom and built-in layers. For example, suppose you want to use a PHPapplication server as an administrator.You implement a custom Chef recipe that configures a server asan administrator. However, if you assign the recipe to the PHP App Server layer's Configure event, youwill configure every instance as an administrator even though you usually want only one. To configurejust one server as an administrator, you could do the following:

• Create a custom layer.

• Implement a recipe to configure a server as an administrator and assign it to the layer's Setup event.

• Make one instance a member of both the PHP App Server and Custom layers.

When you start that instance, the PHP App Server Setup recipes configure the instance as a PHPapplication server and the custom layer's Setup recipe configures the server as an administrator. Theother server instances belong only to the PHP App Server layer, so they are configured as ordinaryservers.

API Version 2013-02-1879

AWS OpsWorks User GuideStatic Web Server Layer

Page 86: Opsworks amazon

To help you implement a custom layer, the following discussion walks you through the basics of creatinga custom Redis layer. Different packages will have different requirements, but the examples illustrate thetypes of issues that your recipes must handle.You may want to start from recipes for Chef Solo that areprovided by the Chef community at http://community.opscode.com/cookbooks.

NoteThis example assumes that you have already created a Rails App Server layer to work with theRedis server. For more information on how to create a Rails App Server layer, see Rails AppServer Layer (p. 198). Implementing the Redis server as a separate custom layer is useful forthe purposes of explaining how to implement custom layers. However, Redis is compatible withRails, so you could also use custom recipes to add Redis server functionality to a Rails AppServer layer.

Create a Custom Redis LayerYou create a custom layer like any other layer, by clicking Add Layer or +Layer on the Layers page andselecting Custom for Layer type.

The Custom option has two configuration options, both of which are required:

NameThe layer's name identifies the layer in the AWS OpsWorks console. This example uses "RedisServer" as the layer's name.

Short nameThe layer's short name is used internally by AWS OpsWorks and by recipes. This example uses"redis" as the layer's short name.

Set Up the Redis ServerYou must use one or more Chef recipes, which are Ruby applications, to handle the details of setting upand configuring layers, deploying applications, installing packages, creating configuration files, addingusers, and so on. AWS OpsWorks does not include any recipes to set up a Redis server, so you mustimplement custom recipes to perform the task.

Recipes are packaged in cookbooks, which are stored in a repository. Each stack can be associated withone custom cookbook repository. For details on how to enable and install custom cookbooks, see InstallingCustom Cookbooks (p. 198).You can see some OpsWorks example cookbooks athttps://github.com/amazonwebservices/opsworks-example-cookbooks.git.

To implement a set of cookbooks, use the following basic folder structure. Required names are shownin Roman type, with user-defined names shown in italics.

API Version 2013-02-1880

AWS OpsWorks User GuideCreate a Custom Redis Layer

Page 87: Opsworks amazon

A cookbook has three required folders:

• attributes contains the cookbook's default settings. For example, the Rails application attributesspecify characteristics such as the Rails version, the application server stack, and so on.The attributesspecify default values, which recipes can overwrite as needed.

• recipes contains recipes. Each recipe usually handles a relatively small, focused task, such asinstalling a package.

• templates stores templates for configuration files.You can also use it for any other files that you wantto install on the instance but that aren't part of the instance setup or not suited for your use case, suchas updated init scripts. The standard practice is that if you expect to change a configuration file on aninstance even slightly, you should create a template.

AttributesAttributes represent instance data, such as the location of various files. Recipes use attributes to set upand configure packages, among other things.The standard practice is to create an attribute for any valuethat is used by more than one recipe or that you might want to override later. Attributes are stored in .rbfiles in the attributes folder. AWS OpsWorks cookbooks commonly store their attributes in default.rb.The following excerpt shows part of the contents of default.rb for a custom Redis layer:

default[:redis][:bind_address] = '0.0.0.0'default[:redis][:port] = 6379default[:redis][:timeout] = 0default[:redis][:version] = '2.4.4'default[:redis][:cli][:version] = redis[:version]default[:redis][:prefix] = '/usr/local'default[:redis][:user] = 'redis'default[:redis][:datadir] = '/var/lib/redis'default[:redis][:log_level] = 'notice'default[:redis][:log_file] = '/var/log/redis/redis.log'default[:redis][:pid_file] = '/var/run/redis.pid'default[:redis][:dump_file] = 'dump.rdb'default[:redis][:appendonly] = 'yes'default[:redis][:aofile] = 'appendonly.aof'default[:redis][:appendfsync] = 'everysec'default[:redis][:no_appendfsync_on_rewrite] = 'no'default[:redis][:auto_aof_rewrite_percentage] = '150'default[:redis][:auto_aof_rewrite_min_size] = '512mb'

An attributes file is essentially a hash table that assigns a value such as the location of log files or theserver's port number to a Chef node. As described later, recipes can use the node to represent thecorresponding value when setting up or configuring a layer.

API Version 2013-02-1881

AWS OpsWorks User GuideSet Up the Redis Server

Page 88: Opsworks amazon

The prefix defines the attribute's precedence. This example uses only default attributes, which have thelowest precedence and can be overridden by higher precedence attributes. For more information, seeAttributes.

Setup RecipesAfter an instance boots, AWS OpsWorks runs the layer's setup recipes. The standard practice is forrecipes to be narrowly focused and to use multiple recipes to accomplish lengthy or complex tasks. Forexample, setup recipes for an application server would do something like the following:

1. Obtain the server package from a remote server.

2. Untar the package.

3. Run make on the package to generate binaries.

4. Configure some directories.

5. Install the server.

6. Configure the server.

This section describes a setup recipe, server.rb, that installs and configures the Redis server package.

The following code installs the Redis package:

remote_file "/tmp/redis-#{node[:redis][:version]}.tar.gz" do source "http://redis.googlecode.com/files/redis-#{node[:redis][:ver sion]}.tar.gz"end

execute "tar xvfz /tmp/redis-#{node[:redis][:version]}.tar.gz" do cwd "/tmp"end

execute "make" do cwd "/tmp/redis-#{node[:redis][:version]}"end

The above example performs three tasks:

1. Obtains the Redis package from the remote server.

2. Untars the package.

3. Runs make on the package to generate binaries.

Chef depends on a set of activities, called resources. This recipe uses the remote_file resource toobtain a file from a remote server specified by source. It then uses the execute resource to executespecified commands in a directory specified by the cwd resource. The resources use various attributesto represent specific values. For example, node[:redis][:version] represents the Redis version,'2.4.4'. For more information about resources, see the Chef documentation.

The next part of server.rb configures some directories and then installs the Redis server.

user "redis" do shell "/bin/zsh" action :create

API Version 2013-02-1882

AWS OpsWorks User GuideSet Up the Redis Server

Page 89: Opsworks amazon

end

directory ::File.dirname(node[:redis][:swapfile]) do action :create recursive true owner node[:redis][:user] group node[:redis][:user] mode '0755'end

directory node[:redis][:datadir] do action :create recursive true owner node[:redis][:user] group 'users' mode '0755'end

directory File.dirname(node[:redis][:log_file]) do action :create owner node[:redis][:user] group 'root' mode '0755'end

enclosed_node = noderuby_block "Install binaries" do block do %w{redis-server redis-cli redis-benchmark redis-check-aof redis-check-dump}.each do |binary| FileUtils.install "/tmp/redis-#{enclosed_node[:redis][:version]}/src/#{bin ary}", "#{enclosed_node[:redis][:prefix]}/bin", :mode => 0755

FileUtils.chown enclosed_node[:redis][:user], 'users', "#{enclosed_node[:re dis][:prefix]}/bin/#{binary}" end endend

This example accomplishes three things:

1. Sets up a user, "redis".

2. Creates and configures several directories.

3. Installs the Redis binaries.

NoteThese steps are idempotent in Chef. This means, for example, that running the recipe againdoes not create a second user. Chef figures out that the user already exists and skips the step.

The final part of server.rb creates an init script and a configuration file:

template "/etc/init.d/redis-server" do source "redis.init.erb" owner "root"

API Version 2013-02-1883

AWS OpsWorks User GuideSet Up the Redis Server

Page 90: Opsworks amazon

group "root" mode "0755"end

include_recipe "redis::service"

service "redis-server" do action :enableend

execute "ensure correct permissions" do command "chown -R #{node[:redis][:user]} #{node[:redis][:datadir]} #{node[:redis][:log_file]}" ignore_failure true # newley created dirsend

template "/etc/redis.conf" do source "redis.conf.erb" owner "root" group "root" mode "0644" notifies :restart, resources(:service => "redis-server"), :immediatelyend

This code does the following:

1. Uses a template resource to create an init script.

A template is basically a file with a set of placeholders.Templates are discussed in the following section.The template resource runs the template through an interpreter and executes the embedded code.For example, redis.init.erb produces an init script.

2. Uses a service resource to characterize the Redis service. The included recipe, service.rb, runsa related service resource.

The service resource abstracts some of the underlying workings of the system it is running on. Inthis case, it maps to the Ubuntu init system. To make effective use of the Chef approach to managinginfrastructure, your cookbooks should be idempotent. That means if you run a cookbook's recipesmultiple times, the resulting system configuration is always the same, and the operation doesn't changeanything that doesn't need to be changed. The service resource is called at this point in the recipeso the following step can tell the service to restart after it writes the configuration script, for a new orexisting instance.

3. Uses a template resource to create a Redis configuration file.

Stack Configuration JSONWhen AWS OpsWorks runs a recipe, it passes the recipe a JSON object that contains the current stackconfiguration. Although this example doesn't do so, your recipe can also use the data from this JSONobject as well as the attributes files.You can refer to this data using the same syntax that you use forattributes.

TemplatesTemplates are files that contain explicit values, which are fixed, as well as placeholders for someconfigurable values. The following is an excerpt from the template for the Redis configuration file.

API Version 2013-02-1884

AWS OpsWorks User GuideSet Up the Redis Server

Page 91: Opsworks amazon

#Basicdaemonize yespidfile <%= node[:redis][:pid_file] %>port <%= node[:redis][:port] %>bind <%= node[:redis][:bind_address] %>timeout <%= node[:redis][:timeout] %>loglevel <%= node[:redis][:log_level] %>logfile <%= node[:redis][:log_file] %>databases 1

#Databaserdbcompression yesdbfilename <%= node[:redis][:dump_file] %>dir <%= node[:redis][:datadir] %>

#Append-onlyappendonly <%= node[:redis][:appendonly] %>appendfilename <%= node[:redis][:aofile] %>appendfsync <%= node[:redis][:appendfsync] %>

# Virtual memoryvm-enabled <%= node[:redis][:vm] %>vm-swap-file <%= node[:redis][:swapfile] %>vm-max-memory <%= node[:redis][:vm_max_memory] %>vm-page-size <%= node[:redis][:vm_page_size] %>vm-pages <%= node[:redis][:vm_pages] %>vm-max-threads 4

#Hash limitshash-max-zipmap-entries 64hash-max-zipmap-value 512activerehashing yes

The template resource uses this template to set up a configuration file; placeholders such asnode[:redis][:log_level] map to values in the attributes file discussed earlier.

BasicThis section handles some basic settings, such specifying the location of several files and whetherRedis should run as a daemon.

DatabaseThis section configures the back-end database, and specifies settings such as how to compressstring objects and some file and directory locations.

Append-onlyThis section enables the Redis append-only mode, which ensures that no data is lost by appendingevery write operation to a file.

Virtual memoryConfigures virtual memory, which allows Redis to work with data sets that are larger than the availableRAM.

Hash limitConfigures hash encoding to be more efficient.

API Version 2013-02-1885

AWS OpsWorks User GuideSet Up the Redis Server

Page 92: Opsworks amazon

Handling Application Deployment and StackConfiguration ChangesThe server.rb recipe and its related attributes and templates are sufficient to set up the Redis server.However, suppose that something subsequently changes; for example, you deploy an application orchange the stack configuration by adding or removing instances.You need to modify the Redis serverconfiguration when either of the following lifecycle events occur.

ConfigureOccurs after the setup event and subsequently whenever the stack configuration changes, typicallywhen the number of instances in the stack changes.

DeployOccurs when you deploy an app. This event is sometimes triggered for multiple layers, even whenapps are deployed to only one of them. In that case, the event's purpose is to notify the other layersabout the deployment, so they can make any required configuration changes.Your deploy recipesmust therefore be able to determine why the event occurred and respond appropriately.

For a custom layer, you handle these events by creating one or more recipes and assigning them to theappropriate lifecycle events. AWS OpsWorks then runs the recipes when event occurs to manage anyrequired changes. This example uses the same recipe for both events to configure a Rails App Serverwith the data that it needs to access the Redis server.

The following recipe, configure-client.rb, handles the configure and deploy events.

node[:deploy].each do |application, deploy| if deploy[:application_type] != 'rails' Chef::Log.debug("Skipping redis::configure as application #{application} as it is not an Rails app") next end

execute "restart Rails app #{application}" do cwd deploy[:current_path] command "touch tmp/restart.txt" action :nothing only_if do File.exists?(deploy[:current_path]) end end

redis_server = node[:opsworks][:layers][:redis][:instances].keys.first rescue nil

template "#{deploy[:deploy_to]}/current/config/redis.yml" do source "redis.yml.erb" mode "0660" group deploy[:group] owner deploy[:user] variables(:host => (node[:opsworks][:layers][:redis][:instances][redis_serv er][:private_dns_name] rescue nil)) notifies :run, resources(:execute => "restart Rails app #{application}")

only_if do File.directory?("#{deploy[:deploy_to]}/current")

API Version 2013-02-1886

AWS OpsWorks User GuideHandling Application Deployment and Stack

Configuration Changes

Page 93: Opsworks amazon

end endend

The first line checks the stack configuration JSON to determine whether this is a Deploy or Configureevent. For a Deploy event, it checks the stack configuration JSON to determine whether a Rails app isbeing deployed. If not, the recipe terminates without doing anything.The remainder of the recipe configuresthe Rails server.

The recipe iterates over all of the stack's apps to update the Rails applications and ignore all others. AWSOpsWorks generally deploys only one app at a time, so iteration might seem unnecessary. However,apps can also be automatically deployed to new instances during the setup phase, an option that isenabled by default. Iterating over all applications ensures that the recipe updates all new apps.

For each Rails app, the recipe defines an execute resource to restart Passenger, which involves touchinga restart.txt file in the app's tmp directory. The action :nothing command ensures that theresource does not run immediately; the recipe runs it only if the configuration has changed. The templateresource then writes the configuration file.

The associated template file contains a single line of code:

host: <%= @host %>

The template sets the :host variable to the active Redis server, which makes it accessible inside thetemplate as @host. The recipe then sets some template variables and notifies the execute resource torun. Chef runs the execute resource if the configuration file has changed.

Assigning Recipes to Lifecycle EventsThe final phase of the process is to assign your custom recipes to the appropriate lifecycle events. AWSOpsWorks runs the assigned recipes in response to an event. The process has two basic steps:

1. Enable custom cookbooks and give AWS OpsWorks access to the repository.

2. Assign the recipes to the appropriate lifecycle events.

For more information, see Automatically Running Recipes (p. 198). To handle Redis server setup, youassign server.rb to the layer's setup event. To handle configuration and deployment, addconfigure-client.rb to the Rails App Server layer.

After the instances finish booting, AWS OpsWorks runs the setup and configuration recipes, includingserver.rb, to set the custom layer's instances up as a Redis server and configure the Rails applicationserver appropriately.You can then deploy your apps, which raises the deploy event to install the appsand configure the Rails server appropriately.

Other LayersAWS OpsWorks also supports the Ganglia and Memcached layers.

Topics

• Ganglia Layer (p. 88)

• Memcached (p. 90)

API Version 2013-02-1887

AWS OpsWorks User GuideAssigning Recipes to Lifecycle Events

Page 94: Opsworks amazon

Ganglia LayerAWS OpsWorks sends all of your instance and volume metrics to Amazon CloudWatch, making it easyto view graphs and set alarms to help you troubleshoot and take automated action based on the state ofyour resources.You can also use the built-in Ganglia layer for additional application monitoring optionssuch as storing nearly unlimited weeks of your chosen metrics.

The Ganglia layer is a blueprint for an instance that monitors your stack by using Ganglia distributedmonitoring. A stack usually has only one Ganglia instance. The Ganglia layer includes the followingoptional configuration settings:

Ganglia URLThe statistic's URL path. The complete URL is http://DNSNameURLPath, where DNSName is theassociated instance's DNS name. The default URLPath value is "/ganglia" which corresponds tosomething like: http://ec2-54-245-151-7.us-west-2.compute.amazonaws.com/ganglia.

Ganglia user nameA user name for the statistics web page.You must provide the user name when you view the page.The default value is "opsworks".

Ganglia passwordA password that controls access to the statistics web page.You must provide the password whenyou view the page. The default value is a randomly generated string.

NoteRecord the password for later use; AWS OpsWorks does not allow you to view the passwordafter you create the layer. However, you can reset the password by going to the layer's Edit pageand clicking Reset now.

API Version 2013-02-1888

AWS OpsWorks User GuideGanglia Layer

Page 95: Opsworks amazon

View the Ganglia StatisticsThe standard AWS OpsWorks recipes install a low-overhead Ganglia client on every instance. If yourstack includes a Ganglia layer, the Ganglia client automatically starts reporting to the Ganglia as soonas the instance comes on line. The Ganglia uses the client data to compute a variety of statistics anddisplays the results graphically on its statistics web page.

To view Ganglia statistics

1. On the Layers page, click Ganglia to open the layer's details page.

2. In the left column, click Instances. Under Ganglia, click the instance name.

3. Copy the instance's Public DNS name.

4. Use the DNS name to construct the statistics URL, which will look something like:http://ec2-54-245-151-7.us-west-2.compute.amazonaws.com/ganglia.

5. Paste the complete URL into your browser, navigate to the page, and enter the Ganglia user nameand password to display the page. An example appears below.

API Version 2013-02-1889

AWS OpsWorks User GuideGanglia Layer

Page 96: Opsworks amazon

MemcachedA Memcached layer provides a template for instances to function as Memcached servers—a distributedmemory-caching system for arbitrary data. The only available setting is Memcached Memory, themaximum amount of memory (in MB) that Memcached can use. The default is 512 MB.

API Version 2013-02-1890

AWS OpsWorks User GuideMemcached

Page 97: Opsworks amazon

Instances

Instances represent the EC2 instances that handle the work of serving applications, balancing traffic, andso on. This section describes how to use AWS OpsWorks to manage a layer's instances.

Topics

• Adding an Instance to a Layer (p. 91)

• Manually Starting, Stopping, and Rebooting 24/7 Instances (p. 94)

• Changing Instance Properties (p. 95)

• Deleting Instances (p. 96)

• Managing Load with Time-based and Load-based Instances (p. 98)

• Using SSH to Communicate with an Instance (p. 103)

Adding an Instance to a LayerAfter you create a layer, you usually add at least one instance.You can add more instances later, if thecurrent set can't handle the load.You can also use load-based or time-based instances to automaticallyscale the number of instances appropriately. For more information, see Managing Load with Time-basedand Load-based Instances (p. 198).

You can add either new or existing instances to a layer:

• New–OpsWorks creates a new instance, configured to your specifications, and makes it a member ofthe layer.

• Existing–You can add an existing instance from any compatible layer, but it must be in the offline(stopped) state.

If an instance belongs to multiple layers, AWS OpsWorks runs the recipes for each of the instance'slayers when a lifecycle event occurs, or when you run a stack (p. 58) or deployment (p. 113) command.However, an instance's layers must be compatible with one another. For example, the HAProxy layer isnot compatible with the Static Web Server layer because they both bind to port 80. An instance can bea member of only one of those layers. For more information, see Appendix A: AWS OpsWorks LayerReference (p. 198).

NoteYou can also make an instance a member of multiple layers by editing its configuration. Formore information, see Changing Instance Properties (p. 198).

API Version 2013-02-1891

AWS OpsWorks User GuideAdding an Instance to a Layer

Page 98: Opsworks amazon

To add a new instance to a layer

1. On the Instances page, click +Instance for the appropriate layer and (if necessary) click the Newtab. If you want to configure more than just the Host name, Size, and Availability Zone, clickAdvanced >> to see more options. The following shows the complete set of options:

2. If desired, you can override the default configuration, most of which you specified when you createdthe stack. For more information, see Create a New Stack (p. 54).

• Hostname identifies the instance on the network. By default, AWS OpsWorks generates eachinstance's host name by using the Hostname theme you specified when you created the stack.You can override this value and specify your preferred host name.

• Size is an Amazon EC2 instance type, which specifies the instance's resources, such as theamount of memory or number of virtual cores. AWS OpsWorks specifies a default size for eachinstance, which you can override with your preferred instance type. AWS OpsWorks supports allinstance types except Cluster Compute, Cluster GPU, and High Memory Cluster. For moreinformation, see Instance Families and Types.

NoteAfter the initial boot, Amazon EBS-backed instances boot faster than instance store-backedinstances because AWS OpsWorks does not have to reinstall the instance's softwarefrom scratch. For more information, see Storage for the Root Device

• Availability Zone is a distinct location within a region that is engineered to be isolated from failuresin other Availability Zones. This field is initially set to the Default Availability Zone value that youspecified when you created the stack.You can override that value and specify a nondefaultAvailability Zone, but it must be from the AWS region that you specified when you created thestack.

• Scaling Type determines how the instance is started and stopped. The default value is a 24/7instance, which must be started and stopped manually.You can also specify a time-based orload-based instance, which are automatically started or stopped by AWS OpsWorks. For moreinformation, see Managing Load with Time-based and Load-based Instances (p. 198).

• SSH key refers to an Amazon EC2 key pair. AWS OpsWorks installs the public key on the instanceand you can use the private key with an SSH client to log into the instance. For more information,

API Version 2013-02-1892

AWS OpsWorks User GuideAdding an Instance to a Layer

Page 99: Opsworks amazon

see Using SSH to Communicate with an Instance (p. 198). This field is initially set to the DefaultSSH key value that you specified when you created the stack.

• If the default value is set to Do not use a default SSH key, you can specify one of your account'sAmazon EC2 keys.

• If the default value is set to an Amazon EC2 key, you can specify a different key or no key.

• Operating system specifies whether the instance is running Amazon Linux or Ubuntu. Initially,this field is set to the Default operating system value that you specified when you created thestack.You can override that value to specify a different operating system.

• Architecture specifies whether the instance's CPU is 32-bit or 64-bit. The default value is 64-bitbut you can also specify 32-bit.

• Root device type determines the type of storage available to the instance.The default root deviceis the instance store, but you can also specify an Amazon EBS-backed root device. For moreinformation, see Storage.

3. Click Add Instance to create the new instance.

To add an existing instance to a layer

1. On the Instances page, click +Instance for the appropriate layer and then click the Existing tab.

NoteIf you change your mind about using an existing instance, click New to create a new instanceas described in the preceding procedure.

2. On the Existing tab, select an instance from the list. The list shows all instances , but lets you selectonly offline instances from compatible layers. For this example, the db-master1 instance will belongto the PHP App Server and MySQL layers, and will run both servers.

If an instance belongs to an incompatible layer, it won't be available here, even if it also belongs toa compatible layer. For example, the PHP App Server and Node.js App Server layers are compatiblewith MySQL but not with each other. Suppose that your stack has a MySQL layer with two instances,db-master1 and db-master2. If you make db-master2 a member of the Node.js App Server layer, itcannot be also be a member of the PHP App Server layer. If you try to add an existing instance toa PHP App Server layer, the Add Instance section will show only db-master1.

3. Click Add Instance to create the new instance.

API Version 2013-02-1893

AWS OpsWorks User GuideAdding an Instance to a Layer

Page 100: Opsworks amazon

An instance represents an Amazon EC2 instance, but is basically just an AWS OpsWorks data structure.An instance must be started to create a running Amazon EC2 instance, as described in the followingsections.

ImportantIf you launch instances into a default VPC, you must be careful about modifying the VPCconfiguration. The instances must always be able to communicate with the AWS OpsWorksservice, Amazon S3, and the package repositories. If, for example, you remove a default gateway,the instances will lose their connection to the AWS OpsWorks service, which will then treat theinstances as failed and auto heal (p. 67) them. However, AWS OpsWorks will not be able toinstall the instance agent on the healed instances. Without an agent, the instances cannotcommunicate with the service, and the startup process will not progress beyond the "booting"status. For more information on default VPC, see Supported Platforms.

Manually Starting, Stopping, and Rebooting 24/7Instances

You must manually start a 24/7 instance to create the corresponding Amazon EC2 instance and manuallystop it to terminate the instance.You can also manually reboot instances that are not functioning properly.AWS OpsWorks automatically starts and stops time-based and load-based instances. For more information,see Managing Load with Time-based and Load-based Instances (p. 198).

To start an instance

• On the Instances page, click start in the Actions column for a desired instance.

You can also create multiple instances and then start them all at the same type by clicking Start allInstances.

After you click start, AWS OpsWorks creates an EC2 instance and boots the operating system, whichtypically takes several minutes.You can monitor the progress by examining the instance's Status column.AWS OpsWorks then runs the associated layer's setup and configure recipes, which perform tasks suchas installing and configuring the instance's packages. If you have created any apps for the instance'slayer, AWS OpsWorks automatically deploys them to the instance. For more information, see Apps (p. 198).When the Status changes to online, the instance is fully operational.

After the instance is on line, AWS OpsWorks replaces the start action with stop, which you can use toterminate the associated Amazon EC2 instance. A stopped instance is still part of the stack and retainsall resources. For example, Amazon EBS volumes and Elastic IP addresses are still attached to a stoppedinstance. If you start the instance again, AWS OpsWorks creates a new EC2 instance and attaches thoseresources to it.

To stop an instance

1. On the Instance page, click stop for an instance, which notifies AWS OpsWorks to run the shutdownrecipes and shut the EC2 instance down.

API Version 2013-02-1894

AWS OpsWorks User GuideManually Starting, Stopping, and Rebooting 24/7

Instances

Page 101: Opsworks amazon

2. Click Yes, stop to confirm.

You can monitor the shutdown process by watching the Status column.You can also shut downevery instance in the stack by clicking Stop All Instances.

To reboot an instance

1. On the Instances page, click the nonfunctioning instance to open the details page.

2. Click Reboot.

TipYou can have AWS OpsWorks automatically replace failed instances by enabling autohealing. For more information, see Using Auto Healing to Replace Failed Instances (p. 198).

Changing Instance PropertiesSome instance properties, such as Availability Zone and Scaling Type, can be set only when you createan instance. Other properties can be modified later, but only when the instance is stopped. After aninstance is online, you can't modify its configuration directly but you can change some aspects of theconfiguration by editing the instance's layers. For more information, see How to Edit a Layer (p. 66).

API Version 2013-02-1895

AWS OpsWorks User GuideChanging Instance Properties

Page 102: Opsworks amazon

To modify instance configuration

1. Stop the instance, if it is not already stopped.

2. On the Instances page, click an instance name to display the Details page.

3. Click Edit to display the edit page.

4. Modify the instance's configuration, as appropriate.

For a description of the Host name, Size, SSH key and Operating system settings, see Adding anInstance to a Layer (p. 198). The Layers setting lets you add or remove layers. The instance's currentlayer's are shown below the list of layers.

• To add another layer, select it from the list and click +.

• To remove the instance from one of its layers, click the x by the appropriate layer.

An instance must be a member of at least one layer, so you cannot remove the last layer.

When you restart the instance, AWS OpsWorks starts a new Amazon EC2 instance with the updatedconfiguration.

Deleting InstancesStopping an instance terminates the EC2 instance, but the instance remains in the stack.You can restartit by clicking start, and AWS OpsWorks creates a new EC2 instance. If you no longer need an instance,you can delete it.

API Version 2013-02-1896

AWS OpsWorks User GuideDeleting Instances

Page 103: Opsworks amazon

ImportantYou should delete instances only by using the AWS OpsWorks console or API. In particular, donot delete AWS OpsWorks instances by using the Amazon EC2 console or API. Amazon EC2actions are not automatically synchronized with AWS OpsWorks. For example, if auto healingis enabled and you terminate an instance by using Amazon EC2, AWS OpsWorks treats theterminated instance as a failed instance and starts another instance to replace it. For moreinformation, see Using Auto Healing to Replace Failed Instances (p. 198).

If an instance belongs to multiple layers, you can delete the instance from the stack or just remove aparticular layer.You can also remove layers from instances by editing the instance configuration, asdescribed in Changing Instance Properties (p. 198).

To delete an instance

1. On the Instances page, locate the instance under the appropriate layer. If the instance is running,click stop in the Actions column.

2. After the status changes to stopped, click delete. If the instance is a member of more than one layer,layer AWS OpsWorks displays the following section.

• To remove the instance from only the selected layer, click Remove from layer.

The instance remains a member of its other layers and can be restarted.

• To delete the instance from all its layers, which removes it from the stack, click here.

3. If you choose to completely remove an instance from the stack, or if the instance is a member ofonly one layer, AWS OpsWorks displays the following section.

Click Yes, delete to confirm. In addition to deleting the instance from the stack, this action deletesany associated logs or data.

API Version 2013-02-1897

AWS OpsWorks User GuideDeleting Instances

Page 104: Opsworks amazon

Managing Load with Time-based and Load-basedInstances

As your incoming traffic varies, your stack may have either too few instances to comfortably handle theload or more instances than necessary.You can save both time and money by using time-based orload-based instances to automatically increase or decrease a layer's instances so that you always haveenough instances to adequately handle incoming traffic without paying for unneeded capacity. There'sno need to monitor server loads or manually start or stop instances. In addition, time- and load-basedinstances automatically distribute, scale, and balance applications over multiple Availability Zones withina region, giving you geographic redundancy and scalability.

Automatic scaling is based on two instance types, which adjust a layer's online instances based ondifferent criteria:

• Load-based instances allow your stack to handle variable loads by starting additional instances whentraffic is high and stopping instances when traffic is low, based on any of several load metrics. Forexample, you can have AWS OpsWorks start instances when the average CPU utilization exceeds80% and stop instances when the average CPU load falls below 60%.

• Time-based instances allow your stack to handle loads that follow a predictable pattern by includinginstances that run only at certain times or on certain days. For example, you could start some instancesafter 6PM to perform nightly backup tasks or stop some instances on weekends when traffic is lower.

An instance can have one of three scaling types: 24/7 (the default), time-based, or load-based. AWSOpsWorks starts or stops time-based or load-based instances according to rules you define for eachlayer. Automatic scaling does not touch 24/7 instances; you must start or stop them manually. A stacktherefore typically consists of a fixed set of 24/7 instances, plus a set of time-based or load-based instanceswhich adjust the number of EC2 instances in the stack based on their automatic scaling configuration.

Topics

• How Automatic Load-based Scaling Works (p. 98)

• How Load-based Scaling Differs from Auto Healing (p. 101)

• How Automatic Time-based Scaling Works (p. 101)

How Automatic Load-based Scaling WorksLoad-based instances let you rapidly start or stop instances in response to changes in incoming traffic.AWS OpsWorks uses Amazon CloudWatch data to compute the following metrics for each layer, whichrepresent average values across all of the layer's instances:

• CPU: The average CPU consumption, such as 80%

• Memory: The average memory consumption, such as 60%

• Load: The average computational work a system performs in one minute.

You define upscaling and downscaling thresholds for any or all of these metrics and specify how AWSOpsWorks responds if the load exceeds a threshold.You can configure all of the following:

• How many instances to start or stop.

• How long AWS OpsWorks should wait after exceeding a threshold before starting or deleting instances.For example, CPU utilization must exceed the threshold for at least 15 minutes. This value allows youto ignore brief traffic fluctuations.

API Version 2013-02-1898

AWS OpsWorks User GuideManaging Load with Time-based and Load-based

Instances

Page 105: Opsworks amazon

• How long AWS OpsWorks should wait after starting or stopping instances before monitoring metricsagain.You usually want to allow enough time for started instances to come online or stopped instancesto shut down before assessing whether the layer is still exceeding a threshold.

When you exceed a metric, AWS OpsWorks starts or stops only load-based instances. It does not startor stop 24/7 instances or time-based instances.

NoteAutomatic load-based scaling does not create new instances; it starts and stops only thoseinstances that you have created.You must therefore provision enough load-based instances inadvance to handle the maximum anticipated load.

To create a load-based instance

1. On the Instances page, click +Instance to add an instance. Click Advanced >> and then clickload-based.

2. Configure the instance as desired. Then click Add Instance to add the instance to the layer.

Repeat this procedure until you have created a sufficient number of instances.You can add or removeinstances later, as required.

After you have added load-based instances to a layer, you must enable load-based scaling and specifythe configuration. The load-based scaling configuration is a layer property, not an instance property, thatspecifies when a layer should start or stop its load-based instances. It must be specified separately foreach layer that uses load-based instances.

To enable and configure automatic load-based scaling

1. In the navigation pane, click Load-based under Instances and click edit for the appropriate layer.

API Version 2013-02-1899

AWS OpsWorks User GuideHow Automatic Load-based Scaling Works

Page 106: Opsworks amazon

2. Toggle Load-based auto scaling enabled to Yes. Then set your desired thresholds.

3. To add additional load-based instances, click + Instance, configure the settings, and click AddInstance. Repeat until you have enough load-based instances to handle your maximum anticipatedload. Then click Save.

NoteYou can also add a new load-based instance to a layer by going to the Load-based page andclicking Add a load-based instance (if you have not yet added a load-based instance to thelayer) or +Instance (if the layer already has one or more load-based instances. Then configurethe instance as described earlier in this section.

To add an existing load-based instance to a layer

1. In the navigation pane, click Load-based under Instances.

2. If you have already enabled load-based auto scaling for a layer, click +Instance. Otherwise, clickAdd a load-based instance. Then click the Existing tab.

API Version 2013-02-18100

AWS OpsWorks User GuideHow Automatic Load-based Scaling Works

Page 107: Opsworks amazon

3. On the Existing tab, select an instance from the list. The list shows only load-based instances.

NoteIf you change your mind about using an existing instance, click the New tab to create a newinstance as described in the preceding procedure.

4. Click Add Instance to add the instance to the layer.

You can modify the configuration for or disable automatic load-based scaling at any time.

To disable automatic load-based scaling

1. In the navigation pane, click Load-based under Instances and click edit for the appropriate layer.

2. Toggle Load-based auto scaling enabled to No.

How Load-based Scaling Differs from Auto HealingAutomatic load-based scaling uses load metrics that are averaged across all running instances. If themetrics remain between the specified thresholds, AWS OpsWorks does not start or stop any instances.With auto healing, on the other hand, AWS OpsWorks automatically starts a new instance with the sameconfiguration when an instance stops responding. The instance may not be able to respond due to anetwork issue or some problem with the instance.

For example, suppose that your CPU upscaling threshold is 80%, and then one instance stops responding.

• If auto healing is disabled, and the remaining running instances are able to keep average CPU utilizationbelow 80%, AWS OpsWorks does not start a new instance. It starts a replacement instance only if theaverage CPU utilization across the remaining instances exceeds 80%.

• If auto healing is enabled, AWS OpsWorks starts a replacement instance irrespective of the loadthresholds.

How Automatic Time-based Scaling WorksTime-based scaling lets you control how many instances a layer should have online at certain times ofday or days of the week by starting or stopping instances on a specified schedule. AWS OpsWorks checksevery couple of minutes and starts or stops instances as required.You specify the schedule separatelyfor each instance, as follows:

• Time of day.You can have more instances running during the day than at night, for example.

• Day of the week.You can have more instances running on weekdays than weekends, for example.

API Version 2013-02-18101

AWS OpsWorks User GuideHow Load-based Scaling Differs from Auto Healing

Page 108: Opsworks amazon

You can either add a new time-based instance to a layer, or use an existing instance.

To add a new time-based instance

1. On the Instances page, click + Instance to add an instance. On the New tab, click Advanced >>and then click time-based.

2. Configure the instance as desired. Then click Add Instance to add the instance to the layer.

To specify a schedule for a time-based instance

1. In the navigation pane, click Time-based under Instances.

2. Specify the online periods for each time-based instance by clicking the appropriate boxes below thedesired hour.

• To use the same schedule every day, click the Every day tab and then specify the online timeperiods.

• To use different schedules on different days, click each day and select the appropriate time periods.

API Version 2013-02-18102

AWS OpsWorks User GuideHow Automatic Time-based Scaling Works

Page 109: Opsworks amazon

A light green square indicates that the instance is online on only some days. Dark green indicates thatthe instance is on line at this time every day. For example, the php-app2 instance is online some daysfrom UTC 0000h to 0600h and every day from 0000h to 0800h.

NoteMake sure to allow for the amount of time it takes to start an instance and the fact that AWSOpsWorks checks only every few minutes to see if instances should be started or stopped. Forexample, if an instance should be running by 1:00 UTC, start it at 0:00 UTC. Otherwise, AWSOpsWorks might not start the instance until several minutes past 1:00 UTC, and it will takeseveral more minutes for it to come online.

You can modify an instance's online time periods at any time using the configuration steps above. Thenext time AWS OpsWorks checks, it uses the new schedule to determine whether to start or stop instances.

NoteYou can also add a new time-based instance to a layer by going to the Time-based page andclicking Add a time-based instance (if you have not yet added a time-based instance to thelayer) or +Instance (if the layer already has one or more time-based instances. Then configurethe instance as described in the preceding procedures.

To add an existing time-based instance to a layer

1. On the Time-based Instances page, click + Instance if a layer already has a time-based instance.Otherwise, click Add a time-based instance. Then click the Existing tab.

2. On the Existing tab, select an instance from the list. The list shows only time-based instances.

NoteIf you change your mind about using an existing instance, click the New tab to create a newinstance, as described in the preceding procedure.

3. Click Add instance to add the instance to the layer.

Using SSH to Communicate with an InstanceYou can use SSH to log on to any of your online instances. There are two basic approaches:

• Using the MindTerm SSH Client (p. 198)

• Using a Third-Party Client with Amazon EC2 Key Pairs (p. 198)

API Version 2013-02-18103

AWS OpsWorks User GuideUsing SSH to Communicate with an Instance

Page 110: Opsworks amazon

Using the MindTerm SSH ClientThe simplest way to log into an instance is to use the MindTerm SSH client.The details depend on whetheryou are logged in as an IAM (AWS Identity and Access Management) user or are using your account'saccess and secret keys.

NoteYou must have Java enabled in your browser to use the MindTerm client.

If you log in to AWS OpsWorks as an IAM user, before using the MindTerm client for the first time, youmust configure AWS OpsWorks.

To use the MindTerm SSH client as an IAM user

1. In your browser, navigate to your IAM account alias. For more information, see Granting UsersPermissions to Work with AWS OpsWorks (p. 198).

2. Log in as the IAM user that will use the client.

3. Create an SSH key pair for the user and give OpsWorks the public key. For details, see Setting anIAM User's Public SSH Key (p. 198).

Store the private key for later use.

4. In the OpsWorks navigation pane, click Permissions. Select the SSH checkbox for the desired IAMuser to grant the necessary permissions. If you want to allow the user to use sudo to elevateprivileges—for example, to run agent CLI (p. 177) commands—check the sudo box as well.

Each online instance includes an ssh action that you can use to open an SSH link to the instance byusing the MindTerm client.

To open an SSH link by using the MindTerm client

1. Log in as the IAM user whose permissions you set in the previous procedure.

2. On the Instances page, click ssh in the Actions column for the appropriate instance.

API Version 2013-02-18104

AWS OpsWorks User GuideUsing the MindTerm SSH Client

Page 111: Opsworks amazon

3. For Path to your private key, specify the location of the IAM user's private key, which mustcorrespond to the public key from the previous procedure. Then click Launch Mindterm.

4. Use the terminal window to run commands on the instance.

API Version 2013-02-18105

AWS OpsWorks User GuideUsing the MindTerm SSH Client

Page 112: Opsworks amazon

The procedure is similar for root users.

To open an SSH link using your access and secret keys

1. Log in using your account's access and secret keys.

2. Assign an Amazon EC2 SSH key to the instance. For more information, see Using a Third-PartyClient with Amazon EC2 Key Pairs (p. 198).

3. On the Instances page, click ssh in the Actions column for the appropriate instance.

4. For Path to your private key, specify the location of the private Amazon EC2 SSH key from Step2. Then click Launch Mindterm.

5. Use the terminal window to run commands on the instance.

Using a Third-Party Client with Amazon EC2 KeyPairsWhen you create a stack, you can specify an Amazon EC2 SSH key that is associated by default withevery instance in the stack.

API Version 2013-02-18106

AWS OpsWorks User GuideUsing a Third-Party Client with Amazon EC2 Key Pairs

Page 113: Opsworks amazon

The Default SSH key list shows your AWS account's Amazon EC2keys.You can do one of the following:

• Select the appropriate key from the list.

• Select Do not use a default SSH key to specify no key.

If you selected Do not use a default SSH key, or you want to override a stack's default key, you canspecify a key when you create an instance.

API Version 2013-02-18107

AWS OpsWorks User GuideUsing a Third-Party Client with Amazon EC2 Key Pairs

Page 114: Opsworks amazon

To use an Amazon EC2 SSH key

1. Obtain the instance's public DNS name from its details page.

2. Provide the associated private key to your preferred SSH client.

3. Enter one of the following host names, where DNSName is the instance's DNS name:

• For Amazon Linux: ec2-user@DNSName

• For Ubuntu: ubuntu@DNSName

API Version 2013-02-18108

AWS OpsWorks User GuideUsing a Third-Party Client with Amazon EC2 Key Pairs

Page 115: Opsworks amazon

Apps

Four of AWS OpsWorks's layers support application servers. In this case, application includes staticHTML pages.

• The Rails App Server layer serves Ruby on Rails applications.

• The PHP App Server layer serves PHP applications.

• The Node.js App Server layer serves JavaScript applications.

• The Static Web Server layer serves static HTML pages, which can include client-side scripting.

An app represents code that you want to run on an application server. The code itself resides in arepository; the app contains the information required to deploy the code to the appropriate applicationserver instances.

NoteIf your stack includes multiple application server instances, you typically add a load balancinglayer to evenly distribute the incoming traffic across the available instances. For more information,see HAProxy Layer (p. 198).

Topics

• Adding Apps (p. 109)

• Deploying Apps (p. 113)

• Using Deploy Keys (p. 115)

• Using Custom Domains (p. 115)

• Running Multiple Applications on an Application Server (p. 117)

• Using SSL (p. 117)

Adding AppsThe purpose of an application server layer is to run one or more custom applications. For example, PHPApp Server layers run PHP apps, Static Web Server layers display a set of static HTML pages, and soon. For more information, on the various layers, see Layers (p. 64).

To add your first app

1. Put the code in your preferred repository—an Amazon S3 bucket, a Github repository, a Subversionrepository, or an HTTP archive. For more information, see Application Source (p. 198).

API Version 2013-02-18109

AWS OpsWorks User GuideAdding Apps

Page 116: Opsworks amazon

2. Click Apps in the left navigation pane. On the Apps page, click Add an app for your first app. Forsubsequent apps, click +App.

3. Use the App New page to provide AWS OpsWorks with the information required to download theapp code from the repository and optionally specify details such as the domain or mount point. Thefollowing section describes how to use App New to configure an app.

Adding an AppThe App New page consists of four sections: Settings, Application source, Add domains, and SSLoptions.

API Version 2013-02-18110

AWS OpsWorks User GuideAdding an App

Page 117: Opsworks amazon

SettingsYour choice for App Type determines what other options you can set in this section.

All Application TypesAll application types have the following required fields:

Name–The app name, which is used to represent the app in the UI.

App Type–The app type. There are four standard types—Ruby on Rails, PHP, Node.js (JavaScript), Static(HTML)—which correspond to the standard application servers. The Other app type lets you installapps intended for custom application server layers. For example, if you implement a custom Javaapplication server layer, you would choose the Other app type.

ImportantThe built-in deployment recipes handle only the standard app types.You must implementyour own deployment recipes to deploy non-standard app types.

Ruby on Rails, PHP, Static, and Other Application TypesThe Ruby on Rails, PHP, Static, or Other app types, include an optional Document root text box forspecifying a document root. The default value is public.

Ruby on Rails Application TypeThe Ruby on Rails app type has two additional optional settings:

• Rails environment lets you specify the environment in which you will execute your Rails app. Thedefault value is production.

• Enable auto bundle lets you specify whether to run bundle install when deploying apps. The defaultvalue is Yes.

Application SourceAWS OpsWorks can deploy the apps from any of five repository types: Git, Subversion, Amazon S3bundle, HTTP bundle, and Other. All repository types require you to specify the repository type and therepository URL. Individual repository types have their own requirements, as explained below.

HTTP ArchiveTo use a publicly-accessible HTTP server as an app repository:

1. Create a compressed archive—zip, gzip, bzip2, or tarball—of the folder that contains the app's codeand any associated files.

2. Upload the archive file to the server.

3. To specify the repository in the console, select HTTP Archive as the repository type and enter theURL.

If the archive is password-protected, under Application Source, specify the user name and password.

API Version 2013-02-18111

AWS OpsWorks User GuideSettings

Page 118: Opsworks amazon

Amazon S3 ArchiveTo use an Amazon Simple Storage Service bucket as an app repository:

1. Create a public or private Amazon S3 bucket. For more information, see Amazon S3 Documentation.

2. For private buckets, create an IAM user with at least read-only rights to the Amazon S3 bucket andrecord the access and secret keys. For more information, see AWS Identity and Access Management(IAM) Documentation.

3. Put the app and any associated files in a folder and store the folder in a compressed archive—zip,gzip, bzip2, or tarball.

4. Upload the archive file to the Amazon S3 bucket.

5. To specify the repository in the AWS OpsWorks console:

• For public buckets, enter the URL and specify HTTP Archive as the repository type.

• For private buckets, enter the URL and specify S3 Archive as the repository type. Under ApplicationSource, specify an Access key ID and Secret access key, such as IAM user keys, that grantyou permission to access the bucket.

Git RepositoryA Github repository provides source control and versioning for your apps. For both apps and Gitsubmodules, the format you use to specify the repository's URL in Application Source depends on whetherthe repository is public or private:

Public repository–Use the HTTPS or Git read-only protocols. For example, Walkthrough: Deploy a WebApp and Learn AWS OpsWorks Basics (p. 6) uses a public repository that can be accessed by eitherof the following URLs:

• Git read-only:git://github.com/amazonwebservices/opsworks-demo-php-simple-app.git

• HTTPS: https://github.com/amazonwebservices/opsworks-demo-php-simple-app.git

Private repository–Use the SSH read/write format shown in these examples:

• Github repositories: [email protected]:project/repository.

• Repositories on a Git server: user@server:project/repository

For private repositories, you must specify a deploy SSH key for Repository SSH key. For Git submodules,the specified key must have access to those submodules.

ImportantThe deploy SSH key cannot require a password; AWS OpsWorks has no way to pass it through.For more information, see Using Deploy Keys (p. 198).

With Github repositories, you can optionally maintain multiple versions or branches. If you do, underApplication Source, specify the name of the branch that you want to use in Branch/Revision.

Subversion RepositoryA Subversion repository provides source control and versioning for your apps.

For a private repository, you must provide your user name and password, as well as the branch name ifyou have multiple branches.

API Version 2013-02-18112

AWS OpsWorks User GuideApplication Source

Page 119: Opsworks amazon

Other RepositoriesIf the standard repositories do not meet your requirements, you can use other repositories, such asBazaar. However, AWS OpsWorks does not automatically deploy apps from such repositories.You mustimplement custom recipes to handle the app deployment process and assign them to the appropriatelayers' Deploy events. For more information, see Cookbooks and Recipes (p. 198).

Domain and SSL SettingsThe final two sections are the same for all application types.

Domain SettingsThis section has an optional Add Domains field for specifying domains. For more information, seeUsing Custom Domains (p. 198).

SSL SettingsThis section has an SSL Support toggle that you can use to enable or disable SSL for the app. Ifyou click Yes, you'll need to provide some information related to your SSL certificate.

Deploying AppsIf you add new instances to a layer, AWS OpsWorks automatically deploys the appropriate apps. However,when you add, stop, or modify an app, you must deploy it manually.

To deploy an app

1. On the Apps page, click the app's deploy action.

TipYou can also deploy an app by clicking Deployments in the left navigation pane. On theDeployments & Commands page, click Deploy an app When you do this, you can alsochoose which app to deploy.

2. Specify the following:

• [Required] Set Command: to deploy, if it is not already selected.

• [Optional] Include a comment.

API Version 2013-02-18113

AWS OpsWorks User GuideOther Repositories

Page 120: Opsworks amazon

3. Click Advanced >> to specify a custom JSON object. AWS OpsWorks passes each instance a stackconfiguration JSON that contains the deployment details and can be used by the deploy recipes tohandle installation and configuration.You can use the custom JSON field to override default AWSOpsWorks settings or pass custom settings to your custom recipes. For more information about howto use custom JSON, see Use Custom JSON to Modify the Stack Configuration JSON (p. 60)

4. Under Instances, click Advanced >> and specify which instances to run the deploy command on.

The deploy command triggers a Deploy event, which runs the deploy recipes on the selected instances.The deploy recipes for the associated application server download the app from the repository andinstall it on the instance, so you typically select all of the associated application server instances.However, other instance types might require some configuration to accommodate the new app, soit often useful to run deploy recipes on those instances as well.Those recipes update the configurationas needed but do not install the app. For more information about recipes, see Cookbooks andRecipes (p. 198).

5. Click Deploy to run the deploy recipes on the specified instances, which displays the Deploymentpage. When the process is complete, AWS OpsWorks marks the app with a green check to indicatesuccessful deployment. If deployment fails, AWS OpsWorks marks the app with a red X. In that case,you can go to the Deployments page and examine the deployment log for more information.

API Version 2013-02-18114

AWS OpsWorks User GuideDeploying Apps

Page 121: Opsworks amazon

Other App Deployment CommandsThe Deploy app page includes several other app deployment commands for managing your apps andthe associated servers:

• undeploy runs the undeploy recipe on the specified instances, which removes all versions of the appfrom the selected instances.

• start web server starts the application server on the selected instances.

• stop web server stops the application server on the selected instances.

• restart web server restarts the application server on the selected instances.

Using Deploy KeysA deploy key is an SSH key with no password that provides access to a private Github repository. Ideally,it doesn't belong to any specific developer. Its purpose is to allow AWS OpsWorks to asynchronouslydeploy apps or cookbooks from a Github repository without requiring any further input from you.

The basic procedure has two steps:

1. Create a deploy key for your Github repository. For more information, see Managing deploy keys.

2. Enter the private key in the Repository SSH Key box when you add an app and specify a Git cookbookrepository. For more information, see Adding Apps (p. 198).

ImportantThe deploy SSH key cannot require a password; AWS OpsWorks has no way to pass it through.

Using Custom DomainsIf you host a domain name with a third party, you can map that domain name to an app. The basicprocedure is as follows:

1. Create a subdomain for the app with your DNS registrar and map it to the IP address of your loadbalancer instance's Elastic IP address or your server's public IP address.

2. Update your app's configuration to point to the subdomain. Then redeploy the app.

NoteMake sure you also forward your unqualified domain name (such as example.com) to yourqualified domain name (such as www.example.com) so that both map to your app.

When you configure the domain for the app, it is listed as a server alias in the server's configuration file.If you are using a load balancer, the load balancer checks the domain name in the URL as requests comein and redirects the traffic based on the domain.

To map a subdomain to an IP address

1. If you are using a load balancer, on the Instances page, click the load balancer instance to open itsdetails page and get the instance's Elastic IP address. Otherwise, get the public IP address fromthe application server instance's details page.

2. Follow the directions provided by your DNS registrar to create and map your subdomain to the IPaddress from Step 1.

API Version 2013-02-18115

AWS OpsWorks User GuideOther App Deployment Commands

Page 122: Opsworks amazon

NoteIf the load balancer instance terminates at some point, you are assigned a new Elastic IP address.You need to update your DNS registrar settings to map to the new Elastic IP address.

To configure the domain for your app

1. Add the app, if you have not already done so. For more information, see Adding Apps (p. 198)

2. On the Apps page click the app name to open its details page.

3. Click Edit App to change the app's configuration.

4. Add the domain name to the app's domains and click + to add the domain to the list.

5. Click Save to save the new configuration and then Deploy app to deploy the app. If the app hasalready been deployed, this step redeploys it with the new configuration. For more information, seeDeploying Apps (p. 198).

After your DNS settings take effect and your app has successfully been deployed or redeployed, youshould be able to enter the app domain in your web browser and see the different applications appear.The following example shows myapp1, which has been mapped to myapp1.example.com:

API Version 2013-02-18116

AWS OpsWorks User GuideUsing Custom Domains

Page 123: Opsworks amazon

Running Multiple Applications on an ApplicationServer

You can have multiple applications of the same type running on an application server by mapping aseparate subdomain to each app, such as myapp1.example.com and myapp2.example.com.

Mapping multiple apps to separate subdomains

1. Create a subdomain for each app with your DNS registrar and map it to the IP address of your loadbalancer instance's Elastic IP address or your server's public IP address.

2. Update each app's configuration to point to its subdomain, and redeploy it.

For more information about how to perform each step, see Using Custom Domains (p. 198).

NoteIf you want both www.mydomain.com and mydomain.com to work, you must specify both. Theload balancer passes the request to the instance, and the server uses the domain to route it tothe correct app.

When you configure the app for a domain, it is listed as a server alias in the Apache configuration file. Ifyou are using a load balancer, it checks the domain name in the URL as requests come in and redirectsthe traffic based on the domain.

NoteIf your apps use HTTPS, a load balancer can handle traffic for only one app. HTTPS requestsare encrypted, which means that the load balancer cannot check the domain name to determinewhich app should handle the request. Because a stack can have only one load balancer, youmust create a separate stack for each HTTPS app.

After your DNS settings take effect and your applications have successfully been redeployed, you shouldbe able to enter each app domain in your web browser and have the different applications appear.

Using SSLTo use SSL with your application, you must obtain a digital server certificate from a Certificate Authority(CA). For the purposes of this walkthrough, we will create a certificate and then self-sign the certificate.Typically, you would only do this for testing purposes; in production, you should always get a certificatesigned by a CA.

In this walkthrough, you'll do the following:

1. Install and configure OpenSSL.

2. Create a private key.

3. Create a certificate signing request.

4. Generate a self-signed certificate.

5. Edit the application with your certificate information.

Step 1: Install and Configure OpenSSLCreating and uploading server certificates requires a tool that supports the SSL and TLS protocols.OpenSSL is an open-source tool that provides the basic cryptographic functions necessary to create anRSA token and sign it with your private key.

API Version 2013-02-18117

AWS OpsWorks User GuideRunning Multiple Applications on an Application Server

Page 124: Opsworks amazon

The following procedure assumes that your computer does not already have OpenSSL installed.

To install OpenSSL on Linux and Unix

1. Go to OpenSSL: Source, Tarballs.

2. Download the latest source.

3. Build the package.

To install OpenSSL on Windows

1. Go to OpenSSL: Binary Distributions.

2. Click OpenSSL for Windows, which displays a new page with links to the Windows downloads.

3. If not already installed on your system, select the Microsoft Visual C++ 2008 Redistributables linkappropriate for your environment and click Download. Follow the instructions provided by the MicrosoftVisual C++ 2008 Redistributable Setup Wizard.

4. After you have installed the Microsoft Visual C++ 2008 Redistributables, select the appropriate versionof the OpenSSL binaries for your environment and save the file locally. Doing so launches theOpenSSL Setup Wizard.

5. Follow the instructions in the OpenSSL Setup Wizard. Save the OpenSSL binaries to a folder inyour working directory.

Create an environment variable that points to the OpenSSL install point by opening a terminal or commandwindow and using the following command lines.

• On Linux and Unix

export OpenSSL_HOME=path_to_your_OpenSSL_installation

• On Windows

set OpenSSL_HOME=path_to_your_OpenSSL_installation

Add the OpenSSL binaries' path to your computer's path variable by opening a terminal or commandwindow and using the following command lines.

• On Linux and Unix

export PATH=$PATH:$OpenSSL_HOME/bin

• On Windows

set Path=OpenSSL_HOME\bin;%Path%

NoteAny changes you make to the environment variables by using these command lines are validonly for the current command-line session.

API Version 2013-02-18118

AWS OpsWorks User GuideStep 1: Install and Configure OpenSSL

Page 125: Opsworks amazon

Step 2: Create a Private KeyYou need a unique private key to create your Certificate Signing Request (CSR). Create the key by usingthe following command line:

openssl genrsa 1024 > privatekey.pem

Step 3: Create a Certificate Signing RequestA Certificate Signing Request (CSR) is a file sent to a Certificate Authority (CA) to apply for a digital servercertificate. Create the CSR by using the following command line.

openssl req -new -key privatekey.pem -out csr.pem

The command's output will look similar to the following:

You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank.

The following table can help you create your certificate request.

Certificate Request Data

ExampleDescriptionName

US=UnitedStates

The two-letter ISO abbreviation for your country.Country Name

WashingtonThe name of the state or province where yourorganization is located. This name cannot beabbreviated.

State or Province

SeattleThe name of the city where your organization islocated.

Locality Name

CorporationXThe full legal name of your organization. Do notabbreviate your organization name.

Organization Name

MarketingOptional, for additional organization information.Organizational Unit

www.example.comThe fully qualified domain name for your CNAME.You will receive a certificate name check warningif this is not an exact match.

Common Name

[email protected] server administrator's email addressEmail address

API Version 2013-02-18119

AWS OpsWorks User GuideStep 2: Create a Private Key

Page 126: Opsworks amazon

NoteThe Common Name field is often misunderstood and is completed incorrectly. The commonname is typically your host plus domain name. It will look like "www.example.com" or"example.com".You need to create a CSR using your correct common name.

Step 4: Submit the CSR to Certificate AuthorityFor production use, you would submit your CSR to a Certificate Authority (CA) to apply for a digital servercertificate. However, you can also generate a self-signed certificate, which can be used for testing purposesonly. For this example, you'll use the following command line to generate a self-signed certificate.

openssl x509 -req -days 365 -in csr.pem -signkey privatekey.pem -out server.crt

The output will look similar to the following:

Loading 'screen' into random state - doneSignature oksubject=/C=us/ST=washington/L=seattle/O=corporationx/OU=marketing/CN=ex ample.com/[email protected] Private key

Step 5: Edit the ApplicationAfter you generate your certificate and sign it, you need to update your app to enable SSL and supplyyour certificate information.

To edit your application to use SSL

1. On the Apps page, click the app name to open the details page. Then click Edit App.

2. Toggle SSL Support to On.

API Version 2013-02-18120

AWS OpsWorks User GuideStep 4: Submit the CSR to Certificate Authority

Page 127: Opsworks amazon

3. Paste the contents of the certificate (.crt) file into SSL Certificate.The contents should look somethinglike the following:

-----BEGIN CERTIFICATE-----MIICuTCCAiICCQCtqFKItVQJpzANBgkqhkiG9w0BAQUFADCBoDELMAkGA1UEBhMCdXMxEzARBgNVBAgMCndhc2hpbmd0b24xEDAOBgNVBAcMB3NlYXR0bGUxDzANBgNVBAoMBmFtYXpvbjEWMBQGA1UECwwNRGV2IGFuZCBUb29sczEdMBsGA1UEAwwUc3RlcGhhbmllYXBpZXJjZS5jb20xIjAgBgkqhkiG9w0BCQEWE3NhcGllcmNlQGFtYXpv...-----END CERTIFICATE-----

4. Paste the contents of the private key file (.pem file) into SSL Certificate Key. The contents shouldlook something like the following:

----BEGIN RSA PRIVATE KEY-----MIICXQIBAAKBgQC0CYklJY5r4vV2NHQYEpwtsLuMMBhylMrgBShKq+HHVLYQQCL6+wGIiRq5qXqZlRXje3GM5Jvcm6q0R71MfRIl1FuzKyqDtneZaAIEYniZibHiUnmO/UNqpFDosw/6hY3ONk0fSBlU4ivD0Gjpf6J80jL3DJ4R23Ed0sdL4pRT3QIDAQABAoGBAKmMfWrNRqYVtGKgnWB6Tji9QrKQLMXjmHeGg95mppdJELiXHhpMvrHtpIyK...-----END RSA PRIVATE KEY-----

5. Click Save and redeploy the app. For more information, see Deploying Apps (p. 198).

After your application has been redeployed, verify that your OpenSSL installation worked by clicking onthe DNS name of the app server instance or the associated load balancer if you are using one. Then addhttps:// in front of the DNS name to verify that SSL is set up correctly.

API Version 2013-02-18121

AWS OpsWorks User GuideStep 5: Edit the Application

Page 128: Opsworks amazon

Cookbooks and Recipes

AWS OpsWorks uses OpsCode Chef cookbooks to handle tasks such as installing and configuringpackages and deploying apps, and includes a set of built-in cookbooks that support the built-in layers.Many approaches to customizing a layer involve overriding or extending the built-in cookbooks byimplementing one or more custom cookbooks.This section provides a brief description of how to implementa cookbook. For more information, see OpsCode.

NoteAWS OpsWorks is currently based on Chef Solo 0.9.

A cookbook typically includes the following basic components:

• Attributes files contain a set of attributes that represent values to be used by the recipes and templates.

For example, the built-in cookbook for the Rails App Server layer includes an attributes file with valuesfor the Rails version, the application server stack, and so on.

• Template files are templates that recipes use to create other files, such as configuration files.

Template files typically let you modify the configuration file by overriding attributes—which can be donewithout touching the cookbook—instead of rewriting a configuration file. The standard practice is thatwhenever you expect to change a configuration file on an instance even slightly, you should use atemplate file.

• Recipe files are Ruby applications that define everything that is required to configure a system, includingcreating and configuring folders, installing and configuring packages, starting services, and so on.

Custom cookbooks don't have to have all three components. As described in Customizing AWSOpsWorks (p. 198), the simpler approaches to customization require only attributes or template files. Inaddition, cookbooks can optionally include other file types, such as definitions or specs.

NoteIf you would like to use standard OpsCode cookbooks with AWS OpsWorks you should be awarethat AWS OpsWorks does not support search or data bags. Instead, AWS OpsWorks installsstack and deployment JSON on each instance that serves many of the same purposes. If yourrecipes depend on search or data bags, you will need to modify them to instead use the stackand deployment JSON. For information, see Customizing AWS OpsWorks (p. 198).

Topics

• Cookbook Repositories (p. 123)

• Cookbook Components (p. 124)

• Installing Custom Cookbooks (p. 130)

API Version 2013-02-18122

AWS OpsWorks User Guide

Page 129: Opsworks amazon

• Updating Custom Cookbooks (p. 132)

• Executing Recipes (p. 133)

Cookbook RepositoriesYour cookbooks must be in one of four types of online repository—an Amazon S3 archive, an HTTParchive, a Git repository, or a Subversion repository. A stack can have only one custom cookbookrepository, but the repository can have any number of cookbooks. When you install or update thecookbooks, AWS OpsWorks downloads the entire repository to a local cache on each of the stack'sinstances. When an instance needs, for example, to run one or more recipes, it uses the code from thelocal cache.

NoteAn archive is compressed archive of a repository, which is packaged as a zip, gzip, bzip2, ortarball file. If you use Amazon S3 or an HTTP site for your cookbook repository, AWS OpsWorksdownloads the archive file to each instance and extracts the contents.

The repository must have following basic structure, where the italicized text represents user-defineddirectory and file names.

NoteFor HTTP and S3 archives, mycookbooks represents a top-level folder. For Git and Subversionrepositories, mycookbooks represents the repository name.

Each cookbook has least one and typically all of the following standard directories, which must use thespecified names:

• attributes contains the cookbook's attributes files.

• recipes contains the cookbook's recipe files.

• templates contains the cookbook's template files.

Other represents optional user-defined directories that contain other file types, such as definitions orspecs.

Templates must be in a subdirectory of the templates directory, which contains at least one and optionallymultiple subdirectories. Those subdirectories can optionally have subdirectories as well. For an example,see the apache2 cookbook.

• Cookbooks usually have a default subdirectory, which contains the template files that Chef uses bydefault.

• other represents optional subdirectories that can be used for operating system-specific templates.

• Chef automatically uses the template from the appropriate subdirectory, based on naming conventionsthat are described in Location Specificity. For the Amazon Linux and Ubuntu operating systems that

API Version 2013-02-18123

AWS OpsWorks User GuideCookbook Repositories

Page 130: Opsworks amazon

are supported by OpsWorks, you can put operating system-specific templates in subdirectories namedamazon or ubuntu, respectively.

TipOne of the best ways to learn how to implement AWS OpsWorks cookbooks is to examine someworking examples, such as the AWS OpsWorks built-in cookbooks athttps://github.com/aws/opsworks-cookbooks or the example cookbooks athttps://github.com/amazonwebservices/opsworks-example-cookbooks.

The details of how you handle custom cookbooks depend on your preferred repository type.

To use an Amazon S3 or HTTP archive for your repository

1. Implement your cookbooks by using the folder structure shown above.

2. Create a compressed archive—zip, gzip, bzip2, or tarball—of mycookbooks and upload it to thewebsite or Amazon S3 bucket.

If you update your cookbooks, you must create and upload a new archive file.

NoteYour cookbooks must be in a mycookbooks folder, even if your repository has only onecookbook.

To use a Github or Subversion repository

1. Set up a repository using the structure shown above.

2. Optionally, use the repository's version control features to implement multiple branches.

If you update your cookbooks, you can do so in a new branch and just direct OpsWorks to use thenew version. For details, see Specifying a Repository (p. 198).

Installing Custom Cookbooks (p. 198) describes how to direct AWS OpsWorks to install your cookbookrepository on the stack's instances.

ImportantAfter you update existing cookbooks, you must run the update_cookbooks stack command todirect AWS OpsWorks to update each instance's local cache. For more information, see RunStack Commands (p. 58).

Cookbook ComponentsThis section describes the three standard cookbook components, attributes, templates, and recipes. Forsome examples of how to implement these components, see Getting Started Walkthroughs (p. 6). Formore information, especially about how to implement recipes, see Opscode.

AttributesRecipes and templates depend on a variety of values, such as configuration settings. Rather than hardcodesuch values directly in recipes or templates, you can create an attributes file with an attribute that representseach value.You then use the attributes in your recipes or templates instead of explicit values. Theadvantage of using attributes is that you can override their values without touching the cookbook. Forthis reason, you should always use attributes to define the following types of values:

• Values that might vary from stack to stack or with time, such as user names.

API Version 2013-02-18124

AWS OpsWorks User GuideCookbook Components

Page 131: Opsworks amazon

If you hardcode such values, you must change the recipe or template each time you need to changea value. By using attributes to define these values, you can use the same cookbooks for every stackand just override the appropriate attributes.

• Sensitive values, such as passwords or secret keys.

Putting explicit sensitive values in your cookbook can increase the risk of exposure. Instead, defineattributes with dummy values and override them to set the actual values.The best way to override suchattributes is with custom JSON. For more information, see Overriding Attributes Using CustomJSON (p. 198).

For more information about attributes and how to override them, see Customizing AWS OpsWorksConfiguration by Overriding Attributes (p. 198).

The following example is a portion of an attributes file (apache.rb) for the built-in apache2 cookbookused by the Rails App Server layer to install and configure an Apache server.

...default[:apache][:listen_ports] = [ '80','443' ]default[:apache][:contact] = '[email protected]'default[:apache][:timeout] = 120default[:apache][:keepalive] = 'Off'default[:apache][:keepaliverequests] = 100default[:apache][:keepalivetimeout] = 3default[:apache][:prefork][:startservers] = 16default[:apache][:prefork][:minspareservers] = 16default[:apache][:prefork][:maxspareservers] = 32default[:apache][:prefork][:serverlimit] = 400default[:apache][:prefork][:maxclients] = 400default[:apache][:prefork][:maxrequestsperchild] = 10000...

AWS OpsWorks defines attributes by using the following syntax:

node.type[:attribute][:subattribute][:...]=value

You can also wrap the names in quotes ("), as follows:

node.type["attribute"]["subattribute"]["..."]=value

An attribute definition has the following components:

node.

The node. prefix is optional and usually omitted, as shown in the example.

type

The type governs whether the attribute can be overridden. AWS OpsWorks attributes typically use oneof the following types:

• default is the most commonly used type, because it allows the attribute to be overridden.

• set defines an attribute that overrides one of the standard AWS OpsWorks attribute values.

API Version 2013-02-18125

AWS OpsWorks User GuideAttributes

Page 132: Opsworks amazon

NoteChef supports additional types, which aren't necessary for AWS OpsWorks but might be usefulfor your project. For more information, see About Attribute Files.

attribute name

The attribute name uses the standard Chef node syntax, [:attribute][:subattribute][...].Youcan use any names you like for your attributes. However, as discussed in Customizing AWS OpsWorksConfiguration by Overriding Attributes (p. 198), custom cookbook attributes are merged into the masterJSON structure, along with the attributes from the built-in cookbooks and the stack configuration JSON.Commonly used configuration names such as port or user might appear in a variety of cookbooks. Toavoid name collisions, the standard convention is to create qualified attribute names with at least twoelements, as shown in the example.The first element should be unique and is typically based on a productname like Apache. It is followed by one or more subattributes that identify the particular value, such as[:user] or [:port].You can use as many subattributes as are appropriate for your project. For example,apache.rb uses an [:apache][:prefork] prefix for the attributes that represent prefork settings.

value

An attribute can be set to the following types of values:

• A string, such as default[:apache][:keepalive] = 'Off'.

• A number (without quotes) such as default[:apache][:timeout] = 120.

• A Boolean value, which can be either true or false (no quotes).

• A list of values, such as default[:apache][:listen_ports] = [ '80','443' ]

The attributes file is a Ruby application, so you can also use node syntax and logical operators to assignvalues based on other attributes. The following example is from the OpsWorks apache2 cookbook, andassigns a value to the [:apache][:pid_file] attribute based on the Linux version.

if node['platform_version'].to_f >= 6 then default[:apache][:pid_file] = '/var/run/httpd/httpd.pid' else default[:apache][:pid_file] = '/var/run/httpd.pid' end

This particular example sets the [:apache][:pid_file] attribute to a literal value, but you can alsoset attributes to other attributes. For more information about how to define attributes, see About AttributeFiles. For examples of working attribute files, see the AWS OpsWorks built-in cookbooks athttps://github.com/aws/opsworks-cookbooks.

TemplatesYou configure many packages by creating a configuration file and placing it in the appropriate directory.You can include a configuration file in your cookbook and copy it to the appropriate directory, but a moreflexible approach is to have your recipes create the configuration file from a template. One advantage ofa template is that you can use attributes to define the templates values. This allows you, for example, tomodify a configuration file without touching the cookbook by using custom JSON to override the appropriateattribute values.

A template has essentially the same content and structure as the associated file. The following exampleis from the apache2 cookbook (apache2.conf.erb), and is used to create an Apache configurationfile, httpd.conf.

API Version 2013-02-18126

AWS OpsWorks User GuideTemplates

Page 133: Opsworks amazon

ServerRoot "<%= node[:apache][:dir] %>"<% if node[:platform] == "debian" || node[:platform] == "ubuntu" -%> LockFile /var/lock/apache2/accept.lock<% else -%> LockFile logs/accept.lock<% end -%>PidFile <%= node[:apache][:pid_file] %>Timeout <%= node[:apache][:timeout] %>KeepAlive <%= node[:apache][:keepalive] %>MaxKeepAliveRequests <%= node[:apache][:keepaliverequests] %>KeepAliveTimeout <%= node[:apache][:keepalivetimeout] %><IfModule mpm_prefork_module> StartServers <%= node[:apache][:prefork][:startservers] %> MinSpareServers <%= node[:apache][:prefork][:minspareservers] %> MaxSpareServers <%= node[:apache][:prefork][:maxspareservers] %> ServerLimit <%= node[:apache][:prefork][:serverlimit] %> MaxClients <%= node[:apache][:prefork][:maxclients] %> MaxRequestsPerChild <%= node[:apache][:prefork][:maxrequestsperchild] %></IfModule>...

The following example is the httpd.conf file that was generated for a Ubuntu instance:

ServerRoot "/etc/httpd"LockFile logs/accept.lockPidFile /var/run/httpd/httpd.pidTimeout 120KeepAlive OffMaxKeepAliveRequests 100KeepAliveTimeout 3<IfModule mpm_prefork_module> StartServers 16 MinSpareServers 16 MaxSpareServers 32 ServerLimit 400 MaxClients 400 MaxRequestsPerChild 10000</IfModule>...

Much of the template's text is simply copied from the template to the httpd.conf file. However, <% ...%> content is handled as follows:

• Chef replaces <%= node[:attribute][:sub_attribute][:...]%> with the attribute's value.

For example, StartServers <%= node[:apache][:prefork][:startservers] %> becomesStartServers 16 in the httpd.conf.

• You can use <%if-%>, <%else-%>, and <%end-%> to conditionally select a value.

The example sets a different file path for accept.lock depending on the platform.

NoteYou are not limited to the attributes in your cookbook's attributes files.You can use any attributein the master JSON. For example, the node[:platform] attribute used in the example is not

API Version 2013-02-18127

AWS OpsWorks User GuideTemplates

Page 134: Opsworks amazon

an apache2 attribute. It is one of a set of attributes that are generated by a Chef tool called Ohaiand also incorporated into the master JSON. For more information on attributes, see CustomizingAWS OpsWorks Configuration by Overriding Attributes (p. 198).

For more information on templates, including how to incorporate Ruby code, see About Templates.

RecipesRecipes are Ruby applications that define everything that is required to configure a system. They installpackages, create configuration files from templates, execute shell commands, create files and folders,and so on.You typically have AWS OpsWorks execute recipes automatically when a lifecycle event (p. 133)occurs on the instance but you can also run them explicitly at any time by using the execute_recipesstack command (p. 133). For more information, see About Recipes.

A recipe typically consists largely of a series of resources, each of which represents an aspect of thesystem. Each resource includes a set of attributes that define the resource and specify what action is tobe taken. Chef associates each resource with an appropriate provider that performs the action. For moreinformation, see Resources and Providers Reference.

A package resource helps you manage software packages. The following example is at the beginningof default.rb and installs the Apache package.

...package 'apache2' do case node[:platform] when 'centos','redhat','fedora','amazon' package_name 'httpd' when 'debian','ubuntu' package_name 'apache2' end action :installend...

Chef uses the appropriate package provider for the platform. Resource attributes are often just assigneda value, but you can use Ruby logical operations to perform conditional assignments. The example usesa case operator, which uses node[:platform] to identify the instance's operating system and sets thepackage_name attribute accordingly.You can insert attributes into a recipe by using the standard Chefnode syntax and Chef replaces it with the associated value.You can use any attribute in the master JSONstructure, not just your cookbook's attributes.

After determining the appropriate package name, the code segment ends with an install action, whichinstalls the package. Other actions for this resource include upgrade and remove. For more information,see package.

It is often useful to break complex installation and configuration tasks into one or more subtasks, eachimplemented as a separate recipe, and have your primary recipe run them at the appropriate time. Thefollowing example shows the line of code that follows the preceding example:

include_recipe 'apache2::service'

To have a recipe execute a child recipe, use the include_recipe keyword, followed by the recipe name.Recipes are identified by using the standard Chef CookbookName::RecipeName syntax, whereRecipeName omits the .rb extension. The example includes the apache2 cookbook's service.rbrecipe, which contains a service resource that starts the Apache server.

API Version 2013-02-18128

AWS OpsWorks User GuideRecipes

Page 135: Opsworks amazon

NoteAn include_recipe statement effectively executes the recipe at that point in the primary recipe.However, what actually happens is that Chef replaces each include_recipe statement withthe specified recipe's code before it executes the primary recipe.

A directory resource represents a directory, such as the one that is to contain a package's files. Thefollowing default.rb resource creates a log directory.

directory node[:apache][:log_dir] do mode 0755 action :createend

The log directory, is defined in one of the cookbook's attributes files.The resource specifies the directory'smode as 0755, and uses a create action to create the directory. For more information, see directory.

The execute resource represents commands, such as shell commands or scripts.The following examplegenerates module.load files.

execute 'generate-module-list' do if node[:kernel][:machine] == 'x86_64' libdir = 'lib64' else libdir = 'lib' end command "/usr/local/bin/apache2_module_conf_generate.pl /usr/#{libdir}/ht tpd/modules /etc/httpd/mods-available" action :runend

The resource first determines the CPU type.[:kernel][:machine] is another of the automatic attributesthat Chef generates to represent various system properties, the CPU type in this case. It then specifiesthe command, a Perl script and uses a run action to run the script, which generates the module.loadfiles. For more information, see execute.

A template resource represents a file—typically a configuration file—that is to be generated from oneof the cookbook's template files. The following example creates an httpd.conf configuration file fromthe apache2.conf.erb template that was discussed in Templates (p. 198).

template 'apache2.conf' do case node[:platform] when 'centos','redhat','fedora','amazon' path "#{node[:apache][:dir]}/conf/httpd.conf" when 'debian','ubuntu' path "#{node[:apache][:dir]}/apache2.conf" end source 'apache2.conf.erb' owner 'root' group 'root' mode 0644 notifies :restart, resources(:service => 'apache2')end

API Version 2013-02-18129

AWS OpsWorks User GuideRecipes

Page 136: Opsworks amazon

The resource determines the generated file's name and location based on the instance's operating system.It then specifies apache2.conf.erb as the template to be used to generate the file and sets the file'sowner, group, and mode. It runs the notify action to notify the service resource that represents theApache server to restart the server. For more information, see template.

Installing Custom CookbooksTo have a stack install and use custom cookbooks, you must explicitly enable them.

To enable custom cookbooks

1. On your stack's page, click Stack settings to display its Settings page.

2. Click Edit to edit the settings.

3. Toggle Use custom Chef Cookbooks to Yes.

Setting the toggle to Yes displays additional settings for specifying the cookbook repository. The nextsection describes how to use the console to complete the process for the different repository types.

API Version 2013-02-18130

AWS OpsWorks User GuideInstalling Custom Cookbooks

Page 137: Opsworks amazon

Specifying a RepositoryAWS OpsWorks can install the cookbooks from any of four repository types:

• HTTP archives are typically the best option for a publicly accessible archive, but can also be passwordprotected.

• S3 archives are typically the preferred option for a private archive.

• Git and Subversion repositories provide source control and the ability to have multiple branches.

All repository types have the following required fields.

• Repository type–The repository type

• Repository URL–The repository URL

For Git repositories, you must use one of the following URL formats, depending on whether the repositoryis public or private. Follow the same URL guidelines for Git submodules.

For a public repository, use the https or Git read-only protocols. For example, the following URLs are forthe publicly available cookbook repository used in Walkthrough: Deploy a Web App and Learn AWSOpsWorks Basics (p. 6)

• Git read-only: git://github.com/amazonwebservices/opsworks-example-cookbooks.git.

• HTTPS: https://github.com/amazonwebservices/opsworks-example-cookbooks.git.

For a private repository, you must use the SSH read/write format, as follows:

• Github repositories: [email protected]:project/repository.

• Repositories on a Git server: user@server:project/repository

The remainder of the fields depend on repository type and are described in the following sections

HTTP ArchiveSelecting Http Archive for Repository type displays two additional settings, which you must completeif the archive is password protected.

• User name–Your user name

• Password–Your password

Amazon S3 ArchiveFor private Amazon S3 archives, select S3 Archive for Repository type, which displays two additionalrequired settings:

• Access key ID–Your AWS access key

• Secret access key–Your AWS secret key

For public Amazon S3 archives, specify HTTP Archive as the repository type.

API Version 2013-02-18131

AWS OpsWorks User GuideSpecifying a Repository

Page 138: Opsworks amazon

Git RepositorySelecting Git under Source Control displays are two additional optional settings:

• Repository SSH key–You must specify a deploy SSH key to access private Git repositories. For Gitsubmodules, the specified key must have access to those submodules. For more information, see GitRepository (p. 198). For more information, see Using Deploy Keys (p. 198).

ImportantThe deploy SSH key cannot require a password; AWS OpsWorks has no way to pass it through.

• Branch/Revision–If the repository has multiple branches, AWS OpsWorks downloads the masterbranch by default.You can use this field so specify a particular branch.

Subversion RepositorySelecting Subversion under Source Control displays three additional settings:

• User name–Your user name, for private repositories.

• Password–Your password, for private repositories.

• Branch/Revision–[Optional] The branch name, if you have multiple branches

Updating Custom CookbooksWhen you provide AWS OpsWorks with custom cookbooks, AWS OpsWorks creates a local cache whenit creates each instance. AWS OpsWorks then runs recipes from the cache, not the repository. If youmodify the cookbooks in the repository, AWS OpsWorks does not automatically update the local caches.You must notify AWS OpsWorks that the repository content has changed and specify whether and howto update the local caches.

To update custom cookbooks

1. Update your repository with the modified cookbooks. AWS OpsWorks uses the cache URL that youprovided when you originally installed the cookbooks, so the cookbook root file name, repositorylocation, and access rights should not change.

• For Amazon S3 or HTTP repositories, replace the original .zip file with a new .zip file that has thesame name.

• For Git or Subversion repositories, edit your stack settings (p. 56) to change the Branch/Revisionfield to the new version.

2. On the stack's page, click Run command and select the update custom cookbooks command.

API Version 2013-02-18132

AWS OpsWorks User GuideUpdating Custom Cookbooks

Page 139: Opsworks amazon

3. Add a comment if desired.

4. You can also add a custom JSON object to be merged into the stack configuration JSON that ispassed to the instances (optional). For more information, see Use Custom JSON to Modify the StackConfiguration JSON (p. 60) and Customizing AWS OpsWorks Configuration by OverridingAttributes (p. 198).

5. By default, AWS OpsWorks updates the cookbooks on every instance. To specify which instancesto update, select the appropriate instances from the list at the bottom of the page. To select everyinstance in a layer, select the appropriate layer checkbox in the left column.

6. Click Deploy to install the updated cookbooks. AWS OpsWorks deletes the cached custom cookbookson the specified instances and installs the new cookbooks from the repository.

NoteThis procedure is required only for existing instances, which have old versions of the cookbooksin their caches. If you subsequently add instances to a layer, AWS OpsWorks deploys thecookbooks that are currently in the repository so they automatically get the latest version.

Executing RecipesYou can run recipes in two ways:

• Automatically, by assigning recipes to the appropriate layer's lifecycle event.

• Manually, by running the update_recipes stack command.

AWS OpsWorks Lifecycle EventsA layer has a sequence of five lifecycle events, each of which has an associated set of recipes that arespecific to the layer. When an event occurs on a layer's instance, AWS OpsWorks automatically runs theappropriate set of recipes.

• Setup occurs on a new instance after it successfully boots. AWS OpsWorks runs recipes that set theinstance up according to its layer. For example, if the instance is a member of the Rails App Server

API Version 2013-02-18133

AWS OpsWorks User GuideExecuting Recipes

Page 140: Opsworks amazon

layer, the Setup recipes install Apache, Ruby Enterprise Edition, Passenger and Ruby on Rails. Setupincludes Deploy, which automatically deploys the appropriate recipes to a new instance after setup iscomplete.

• Configure occurs on all of the stack's instances when an instance enters or leaves the online state.For example, suppose that your stack has instances A, B, and C, and you start a new instance, D. AfterD has finished running its setup recipes, AWS OpsWorks triggers the Configure event on A, B, C, andD. If you subsequently stop A, AWS OpsWorks triggers the Configure event on B, C, and D. AWSOpsWorks responds to the Configure event by running each layer's Configure recipes, which updatethe instances' configuration to reflect the current set of online instances.The Configure event is thereforea good time to regenerate configuration files. For example, the HAProxy Configure recipes reconfigurethe load balancer to accommodate any changes in the set of online application server instances.

• Deploy occurs when you run a deploy command, typically to deploy an application to a set of applicationserver instances. The instances run recipes that deploy the application and any related files from itsrepository to the layer's instances. For example, for a Rails Application Server instances, the Deployrecipes check out a specified Ruby application and tell Phusion Passenger to reload it.You can alsorun deploy on other instances so they can, for example, update their configuration to accommodatethe newly deployed app. Note that Setup includes Deploy; it runs the Deploy recipes after setup iscomplete to automatically deploy the appropriate recipes to a new instance.

• Undeploy occurs when you delete an app or run an undeploy command to remove an app from a setof application server instances. The specified instances run recipes to remove all application versionsand perform any required cleanup.

• Shutdown occurs after you direct AWS OpsWorks to shut an instance down but before the associatedAmazon EC2 instance is actually terminated. AWS OpsWorks runs recipes to perform cleanup taskssuch as shutting down services. AWS OpsWorks allows Shutdown recipes 45 seconds to perform theirtasks, and then terminates theAmazon EC2 instance.

For more discussion about the deploy and undeploy app commands, see Deploying Apps (p. 198).

After a new instance finishes booting, AWS OpsWorks does the following:

1. Runs the built-in Setup recipes.

2. Runs any custom Setup recipes.

3. Runs the built-in Deploy recipes.

4. Runs any custom Deploy recipes

For each lifecycle event, AWS OpsWorks provides each instance with a JSON structure that containsthe current stack state and, for Deploy events, a variety of information about the deployment. This JSONincludes information about what instances are available, their IP addresses, and so on. For moreinformation, see Stack Configuration and Deployment JSON (p. 198).

To respond to these events, implement custom recipes and assign them to the appropriate events foreach layer. AWS OpsWorks runs those recipes after the event's default recipes.

Automatically Running RecipesEach layer has a set of built-in recipes assigned to each lifecycle event, although some layers lackUndeploy recipes. When a lifecycle event occurs on an instance, AWS OpsWorks runs the appropriateset of recipes for the associated layer. To see which built-in recipes are assigned to a layer's events,open the layer's details page and click Show>> under Built-in Chef recipes.

API Version 2013-02-18134

AWS OpsWorks User GuideAutomatically Running Recipes

Page 141: Opsworks amazon

If you have installed custom cookbooks, you can have AWS OpsWorks run some or all of the recipesautomatically by assigning each recipe to a layer's lifecycle event. After an event occurs, AWS OpsWorksruns the specified custom recipes after the layer's built-in recipes.

To assign custom recipes to layer events

1. On the Layers page, click the appropriate layer name to open its details page. Then click Edit. Ifyou haven't yet enabled custom cookbooks, click configure cookbooks to open the stack's Settingspage. Toggle Use custom Chef Cookbooks to Yes, and provide the cookbook's repositoryinformation. Then click Save and navigate back to the layer's details page. For more information,see Installing Custom Cookbooks (p. 198).

2. On the layer details page, under Custom Chef recipes, click edit, enter each custom recipe in theappropriate event field and click + to add it to the list. Specify a recipe as follows:cookbook::somerecipe (omit the .rb extension).

API Version 2013-02-18135

AWS OpsWorks User GuideAutomatically Running Recipes

Page 142: Opsworks amazon

When you start a new instance, AWS OpsWorks automatically runs the custom recipes for each event,after it runs the standard recipes.

NoteCustom recipes execute in the order that you enter them in the console. An alternative way tocontrol execution order is to implement a meta recipe that executes the recipes in the correctorder. For more information, see Recipes (p. 198).

Manually Running RecipesAlthough recipes are typically run automatically in response to lifecycle events, you can manually runrecipes at any time on any or all stack instances.This feature is typically used for tasks that don't naturallymap to a lifecycle event, such backing up instances. To run a custom recipe manually, it must be in oneof your custom cookbooks but does not have to be assigned to a lifecycle event.

To manually run recipes on stack instances

1. On the Stack page, click Run command. For Command, select execute recipes.

API Version 2013-02-18136

AWS OpsWorks User GuideManually Running Recipes

Page 143: Opsworks amazon

2. Enter the recipes to be run in the Recipes to execute box by using the standardcookbookname::recipename format. Use commas to separate multiple recipes; they will run in theorder that you list them.

3. Optionally, use the Custom Chef JSON box to add a custom JSON object that will be merged intothe stack configuration JSON that is passed to the instances. For more information about using howcustom JSON objects, see Use Custom JSON to Modify the Stack Configuration JSON (p. 60) andCustomizing AWS OpsWorks Configuration by Overriding Attributes (p. 198).

4. Under Instances, select the instances on which AWS OpsWorks should run the recipes.

API Version 2013-02-18137

AWS OpsWorks User GuideManually Running Recipes

Page 144: Opsworks amazon

Customizing AWS OpsWorks

AWS OpsWorks built-in layers provide standard functionality that is sufficient for many purposes. However,for many projects, you might encounter one of the following:

• A built-in layer's standard configuration is adequate but not ideal; you would like to optimize it for yourparticular requirements.

For example, you might want to tune a Static Web Server layer's Nginx server configuration by specifyingyour own values for settings such as the maximum number of worker processes or thekeepalivetimeout value.

• A built-in layer's functionality is fine, but you want to extend it by installing additional packages or runningsome custom installation scripts.

For example, you might want to extend a PHP App Server layer by also installing a Redis server.

• You have requirements that aren't handled by any of the built-in layers.

For example, AWS OpsWorks does not include built-in layer for Java application servers.You cancreate a custom layer that installs a Tomcat server to handle Java applications.

AWS OpsWorks provides a variety of ways to customize layers to meet your specific requirements. Thefollowing examples are listed in order of increasing complexity and power:

• Use custom JSON to override default AWS OpsWorks settings.

• Implement a custom Chef cookbook with an attributes file that overrides the default AWS OpsWorkssettings.

• Implement a custom Chef cookbook with a template that overrides or extends a default AWS OpsWorkstemplate.

• Implement a custom Chef cookbook with a simple recipe that runs a shell script.

• Implement a custom Chef cookbook with recipes that perform tasks such as creating and configuringdirectories, installing packages, creating configuration files, deploying applications, and so on.

ImportantYou cannot override a built-in recipe by implementing a custom recipe with the same cookbookand recipe name. For each lifecycle event, AWS OpsWorks always runs the built-in recipes first,followed by any custom recipes. Because Chef does not run a recipe with the same cookbookand recipe name twice, the built-in recipe takes precedence and the custom recipe is not executed.

The following sections describe how to customize an AWS OpsWorks layer:

API Version 2013-02-18138

AWS OpsWorks User Guide

Page 145: Opsworks amazon

• AWS OpsWorks stores configuration data and a variety of other information as attributes in a JSONstructure on each instance. Customizing AWS OpsWorks Configuration by Overriding Attributes (p. 198)describes how the structure's attribute values are determined, and how you can override them.

• The remaining sections describe various ways to customize a layer.

NoteBecause many of the techniques use custom cookbooks, you should first read Cookbooks andRecipes (p. 198) if you are not already familiar with cookbook implementation.

Topics

• Customizing AWS OpsWorks Configuration by Overriding Attributes (p. 139)

• Extending AWS OpsWorks Configuration Files Using Custom Templates (p. 144)

• Extending a Built-in Layer (p. 144)

• Stack Configuration and Deployment JSON (p. 147)

• Troubleshooting (p. 153)

Customizing AWS OpsWorks Configuration byOverriding Attributes

Recipes and templates depend on a variety of Chef attributes for instance or stack-specific informationsuch as layer configurations or application server settings. These attributes have several sources:

• Custom JSON–You can optionally specify custom JSON attributes when you create, update, or clonea stack, or when you deploy an application.

• Stack configuration JSON–AWS OpsWorks creates this structure to hold stack configuration informationthat is determined by the service, including the information that you specify through the console settings.

• Deployment JSON–AWS OpsWorks incorporates deployment-related attributes into the stackconfiguration JSON for Deploy events.

• Cookbook attributes–Built-in and custom cookbooks usually include one or more attributes files (p. 124),which contain attributes that represent cookbook-specific values such as application server configurationsettings.

• Chef–Chef's Ohai tool defines attributes that represent a wide variety of system configuration settings,such as CPU type and installed memory.

For a complete list of stack configuration JSON, deployment JSON, and built-in cookbook attributes, seeAppendix D: AWS OpsWorks Attribute Reference (p. 198). For more information about Ohai attributes,see Ohai.

When a lifecycle event (p. 133) such as Deploy or Configure occurs, or you run a stack command (p. 58)such as execute_recipes or update_packages, AWS OpsWorks does the following:

• Sends a corresponding command to the agent on each affected instance.

The agent runs the appropriate recipes. For example, for a Deploy event, the agent runs the built-inDeploy recipes, followed by any custom Deploy recipes.

• Merges any custom JSON and deployment JSON with the stack configuration JSON and downloadsit to the instances.

The attributes from custom JSON, stack configuration JSON, cookbook attributes, and Ohai attributesare merged into a master JSON structure, which supplies attribute values to recipes. An instance is

API Version 2013-02-18139

AWS OpsWorks User GuideCustomizing AWS OpsWorks Configuration by

Overriding Attributes

Page 146: Opsworks amazon

essentially stateless as far as stack configuration attributes are concerned, including any custom JSON.When you run a deployment or stack command, the associated recipes use the stack configurationattributes that were downloaded with the command.

Attribute PrecedenceIf all attributes are unique, Chef simply combines them into a single structure. However, any of the attributesources can define any attribute, so it is possible for the same attribute to have multiple definitions withdifferent values. For example, the built-in apache2 cookbook defines node[:apache][:keepalive],but you could also define that attribute in custom JSON or in a custom cookbook. The master JSON canhave only one instance of each attribute, so if an attribute is defined by more than one source, Chefdetermines which attribute definition has precedence and incorporates that value into the master JSON.

An attribute is defined as follows:

node.type[:attribute][:sub_attribute][:...]=value

If an attribute has multiple definitions, Chef evaluates them in an order that is described later. It uses theattribute's type to determine which definition wins, and is incorporated into the master JSON. AWSOpsWorks uses two attribute types:

• default–This is the most common type, and it essentially means "use this value if the attribute hasn'talready been defined." If all definitions of an attribute are default type, the first definition in theevaluation order goes in the master JSON and subsequent values are ignored. Note that AWS OpsWorkssets all stack configuration JSON attribute definitions to default type.

• set–This type overrides any values that were defined earlier in the evaluation order, including otherset types. If the first attribute is a default type and the second is a set type, the second definitiongoes in the master JSON.

NoteChef supports several additional attribute types, including an automatic type that takesprecedence over all other attribute definitions.The attribute definitions generated by Chef's Ohaitool are all automatic types, so they are effectively read-only. This isn't usually an issue,because there is no reason to override them and they are distinct from AWS OpsWorks' attributes.However, you should be careful to name your custom cookbook attributes so they are distinctfrom the Ohai attributes. For more information, see About Attribute Files.

Here are the steps that incorporate the various attribute definitions into the master JSON:

1. Merge any custom stack configuration JSON attributes into the stack configuration JSON,.

Custom JSON attributes can be set for the stack, or for a particular deployment. They are first in theevaluation order and are effectively set types. If one or more stack configuration JSON attributes arealso defined in custom JSON, the custom JSON values take precedence. Otherwise AWS OpsWorkssimply incorporates the custom JSON attributes into the stack configuration JSON.

2. Merge any custom deployment JSON into the stack configuration JSON.

Custom deployment JSON is also effectively a set type, so it takes precedence over built-in andcustom stack configuration JSON.

3. Pass the stack configuration JSON to the instance and incorporate its attributes into the instance'smaster JSON.

4. Merge the instance's built-in cookbook attributes into the master JSON.

The built-in cookbook attributes are all default types. If the one or more built-in cookbook attributesare also defined in the stack configuration JSON—typically because you defined them with custom

API Version 2013-02-18140

AWS OpsWorks User GuideAttribute Precedence

Page 147: Opsworks amazon

JSON—the stack configuration definitions take precedence over the built-in cookbook definitions. Allother built-in cookbook attributes are simply incorporated into the master JSON.

5. Merge the instance's custom cookbook attributes into the master configuration JSON.

Custom cookbook attributes can be either set or default types. Unique attributes are incorporatedinto the master JSON. If any custom cookbook attributes are also defined in Steps 1–3 (typicallybecause you defined them with custom JSON), precedence depends on the custom cookbook attribute'stype:

• Attributes defined in Steps 1–3 take precedence over custom cookbook default attributes.

• Custom cookbook set attributes take precedence over definitions from Steps 1–3.

ImportantDo not use custom cookbook default attributes to override stack configuration or built-incookbook attributes. Because custom cookbook attributes are evaluated last, the defaultattributes have the lowest precedence, and cannot override anything.

Overriding Attributes Using Custom JSONThe simplest way to override an attribute is to define it in custom JSON, which takes precedence overstack configuration JSON attributes as well as built-in and custom cookbook default attributes. Formore information, see Attribute Precedence (p. 198).

ImportantYou should override stack configuration JSON attributes with care. For example overridingattributes in the opsworks namespace can interfere with the built-in recipes. For more information,see Stack Configuration and Deployment JSON (p. 198).

You can also use custom JSON to define unique attributes, typically to pass data to your custom recipes.The attributes are simply incorporated into the master JSON, and recipes can reference them by usingthe standard Chef node syntax.

How to Specify Custom JSONTo use custom JSON to override an attribute value, you must first determine the attribute's fully qualifiedattribute name.You then create a JSON object that contains the attributes you want to override, set toyour preferred values. For convenience, Appendix D: AWS OpsWorks Attribute Reference (p. 198)documents commonly used stack configuration, deployment, and built-in cookbook attributes, includingtheir fully qualified names.

The object's parent-child relationships must correspond to the appropriate fully qualified Chef nodes . Forexample, suppose you want to change the following Apache attributes:

• The attribute, whose node is node[:apache][:keepalivetimeout] (p. ?) and has a default valueof 3.

• The logrotate schedule (p. ?) attribute, whose node isnode[:apache][:logrotate][:schedule], and has a default value of "daily".

To override the attributes and set the values to 5 and "weekly", respectively, you would use the followingcustom JSON:

{ "apache" : { "keepalivetimeout" : 5,

API Version 2013-02-18141

AWS OpsWorks User GuideOverriding Attributes Using Custom JSON

Page 148: Opsworks amazon

"logrotate" : { "schedule" : "weekly" } }}

When to Specify Custom JSONYou can specify a custom JSON structure for the following tasks:

• Create a new stack (p. 54)

• Update a stack (p. 56)

• Run a stack command (p. 56)

• Clone a stack (p. 57)

• Deploy an app (p. 113)

For each task, AWS OpsWorks merges the custom JSON with the stack configuration JSON and sendsit to the instances, to be merged into the master JSON. However, note the following:

• If you specify custom JSON when you create, clone, or update a stack, it is merged into the stackconfiguration JSON and is sent to instances for all subsequent lifecycle events and stack commands.

• If you specify custom JSON for a deployment, it is merged into the stack configuration JSON only forthe corresponding event.

If you want to use that JSON for subsequent deployments, you must explicitly specify it again.

It is important to remember that attributes only affect the instance when they are used by recipes. If youoverride an attribute value but no subsequent recipes reference the attribute, the change has no effect.You must either ensure that the custom JSON is sent before the associated recipes run, or ensure thatthe appropriate recipes are re-run.

Custom JSON Best PracticesYou can use custom JSON to override any AWS OpsWorks attribute, but manually entering the informationis somewhat cumbersome, and it is not under any sort of source control. Custom JSON is best used forthe following purposes:

• When you want to override only a small number of attributes, and you do not otherwise need to usecustom cookbooks.

With Custom JSON, you can avoid the overhead of setting up and maintaining a cookbook repositoryjust to override a couple of attributes.

• Sensitive values, such as passwords or authentication keys.

Cookbook attributes are stored in a repository, so any sensitive information is at some risk of beingcompromised. Instead, define attributes with dummy values and use custom JSON to set the realvalues.

• Values that are expected to vary.

For example, a recommended practice is to have your production stack supported by separatedevelopment and staging stacks. Suppose that these stacks support a application that accepts payments.If you use custom JSON to specify the payment endpoint, you can specify a test URL for your stagingstack.When you are ready to migrate an updated stack to your production stack, you can use the samecookbooks and use custom JSON to set the payment endpoint to the production URL.

API Version 2013-02-18142

AWS OpsWorks User GuideOverriding Attributes Using Custom JSON

Page 149: Opsworks amazon

• Values that are specific to a particular stack or deployment command.

Overriding AWS OpsWorks Attributes UsingCustom Cookbook AttributesCustom JSON is a convenient way to override AWS OpsWorks stack configuration and built-in cookbookattributes, but it has some limitations. In particular, you must enter custom JSON manually for each use,so you have no robust way to manage the definitions. A better approach is often to use custom cookbookattribute files to override built-in attributes. Doing so allows you to place the definitions under sourcecontrol.

NoteYou don't have to implement templates or recipes to use attributes files.Your repository canhave as little as one cookbook with a single attributes file.

The procedure for implementing custom attribute definitions is straightforward.

To implement custom attribute definitions

1. Set up a cookbook repository, as described in Cookbooks and Recipes (p. 198).

You must use the standard folder structure, but if all you want to do is override attributes, you canomit the templates and recipes folders.

2. Create an attributes file and store it in your cookbook's attributes folder. Add an attribute definitionto the file for each AWS OpsWorks attribute you want to override, set to your preferred value. Theattribute must be a set type and have exactly the same node name as the corresponding AWSOpsWorks attribute. For a detailed list of AWS OpsWorks attributes, including node names, seeAppendix D: AWS OpsWorks Attribute Reference (p. 198).You can include other attribute definitionsif you wish and Chef will add them to the master JSON.

ImportantYour attributes must be set type to override AWS OpsWorks attributes; default types donot have precedence. For example, if your custom attributes file contains adefault[:apache][:keepalivetimeout] = 5 attribute definition, the correspondingattribute in the built-in apache.rb attributes file is evaluated first, and takes precedence.For more information, see Customizing AWS OpsWorks Configuration by OverridingAttributes (p. 198).

3. Enable custom cookbooks for your stack and provide the information required for AWS OpsWorksto download your cookbooks to the stack's instances. For more information, see Installing CustomCookbooks (p. 198).

If your cookbook contains no recipes, this is all you need to do. The master JSON used by subsequentlifecycle events, deploy commands, and stack commands will contain your attribute definitions insteadof the AWS OpsWorks values.

NoteWhen you use custom cookbook attributes to override AWS OpsWorks attributes in the built-incookbooks, a common convention is to use the same cookbook and attributes file names. Forexample, to override apache2 attributes, you would implement an apache2 cookbook and putthe attribute definitions in an apache.rb attributes file. However, this practice is not required;Chef considers only attributes' node names when it constructs the master JSON, not the file orcookbook names. If you want to override node[:apache][:keepalivetimeout], for example,you simply need to have that attribute in an attributes file, set to your preferred value.

API Version 2013-02-18143

AWS OpsWorks User GuideOverriding AWS OpsWorks Attributes Using Custom

Cookbook Attributes

Page 150: Opsworks amazon

For example, to override the built-in Apache keepalivetimeout and logrotate schedule settingsdiscussed in How to Specify Custom JSON (p. 198), create a cookbook and put the following in an attributesfile.

set[:apache2][:keepalivetimeout] : 5,set[:apache][:logrotate][:schedule] = 'weekly'

Extending AWS OpsWorks Configuration FilesUsing Custom Templates

AWS OpsWorks uses templates to create configuration files, which typically depend on attributes formany of the settings. If you use custom JSON or custom cookbook attributes to override the AWSOpsWorks definitions, your preferred settings are incorporated into the configuration files in place of theAWS OpsWorks settings. However, AWS OpsWorks does not necessarily specify an attribute for everypossible configuration setting; it accepts the defaults for some settings and hardcodes others directly inthe template.You can't use custom JSON or custom cookbook attributes to specify preferred settings ifthere is no corresponding AWS OpsWorks attribute.

You can extend the configuration file to include additional configuration settings by creating a customtemplate.You can then add whatever configuration settings or other content you need to the file, andoverride any hardcoded settings. For more information on templates, see Templates (p. 198).

To create a custom template

1. Create a cookbook that exactly matches the built-in cookbook. For example, to use a custom templateto extend the Apache httpd.conf configuration file, you must implement an apache2 cookbookin your repository and your template file must beapache2/templates/default/apache.conf.erb. The cookbook can also include customattributes and recipes, but they are not required.

2. Customize the template file to produce a configuration file that meets your requirements.The simplestapproach is to start with a copy of the built-in template file and modify it as appropriate.You can addmore settings, delete existing settings, replace hardcoded attributes, and so on.You can find thebuilt-in template files at https://github.com/aws/opsworks-cookbooks.

When the built-in recipe runs, it will create the configuration file using your custom template.

NoteIf OpsWorks makes any changes to the built-in template, your custom template might becomeout of sync and no longer work correctly. For example, suppose your template refers to adependent file, and the file name changes. AWS OpsWorks doesn't make such changes often,and when a template does change, it lists the changes and gives you the option of upgrading toa new version.You should monitor the OpsWorks repository for changes, and manually updateyour template as needed.

Extending a Built-in LayerSometimes, you need to customize a built-in layer beyond what can be handled by modifying AWSOpsWorks attributes or customizing templates. For example, suppose you need to create symlinks, setfile or folder modes, install additional packages, and so on. In that case, you will need to implement oneor more recipes to handle the customization tasks.

API Version 2013-02-18144

AWS OpsWorks User GuideExtending AWS OpsWorks Configuration Files Using

Custom Templates

Page 151: Opsworks amazon

Topics

• Using Recipes to Run Scripts (p. 145)

• Using Chef Deployment Hooks (p. 145)

• Running Cron Jobs (p. 146)

• Installing and Configuring Packages (p. 147)

Using Recipes to Run ScriptsIf you already have a script that performs the required customization tasks, the simplest approach toextending a layer is often to implement a simple recipe to run the script.You can then assign the recipeto the appropriate lifecycle events, typically Setup or Deploy, or use the execute_recipes stack commandto run the recipe manually.

The following example runs a shell script but you can use the same approach for other types of script.

cookbook_file "/tmp/lib-installer.sh" do source "lib-installer.sh" mode 0755end

execute "install my lib" do command "sh /tmp/lib-installer.sh"end

The cookbook_file resource represents a file that is stored in a subdirectory of a cookbook's filesdirectory, and transfers the file to a specified location on the instance. This example transfers a shellscript, lib-installer.sh, to the instance's /tmp directory and sets the file's mode to 0755. For moreinformation, see cookbook_file.

The execute resource represents a command, such as a shell command. This example runslib-installer.sh. For more information, see execute.

You can also run a script by incorporating it into a a recipe. The following example runs a bash script,but Chef also supports Csh, Perl, Python, and Ruby.

script "install_something" do interpreter "bash" user "root" cwd "/tmp" code <<-EOH #insert bash script EOHend

The script resource represents a script.The example specifies a bash interpreter, sets user to "root",and sets the working directory to /tmp. It then runs the bash script in the code block, which can includeas many lines as required. For more information, see script.

Using Chef Deployment HooksYou can customize deployment by implementing a recipe to perform the required customization andassign it to the appropriate layer's Deploy event. A alternative and sometimes simpler approach—especially

API Version 2013-02-18145

AWS OpsWorks User GuideUsing Recipes to Run Scripts

Page 152: Opsworks amazon

if you don't need to implement a cookbook for other purposes—is to use Chef deployment hooks to runyour customization code. In addition, custom Deploy recipes run after the deployment has already beenperformed by the built-in recipes. Deployment hooks allow you to interact during a deployment, for example,after the app's code is checked out of the repository but before Apache is restarted.

Chef deploys apps in four stages:

• Checkout–Downloads the app's code from the repository

• Migrate–Runs a migration, as required

• Symlink–Creates symlinks

• Restart–Restarts the application

Chef deployment hooks provide a simple way to customize a deployment by optionally running auser-supplied Ruby application after each stage completes. To use deployment hooks, implement oneor more Ruby applications and place them in your app's /deploy directory. An application must haveone of the following names, which determines when it runs.

• before_migrate.rb runs after the Checkout stage is complete but before Migrate.

• before_symlink.rb runs after the Migrate stage is complete but before Symlink.

• before_restart.rb runs after the Symlink stage is complete but before Restart.

• after_restart.rb runs after the Restart stage is complete.

For more information on how to use deployment hooks, see Deploy Phases.

Running Cron JobsA cron job runs a task on a specified schedule. For example, suppose your stack supports a PHPe-commerce app and you want to receive a sales report at weekly intervals.You can use recipes to setup cron jobs. The following example sets up a cron job to send a weekly report.

cron "send out mailing" do hour "1" minute "10" weekday "6" command "cd /srv/www/myapp/current && php .lib/mailing.php"end

A cron resource represents a cron job. In this example, "send out mailing" is the name of the cronentry.The hour, minute, and weekday attributes configure the schedule.This example configures cronto run the PHP application that mails the report, mailing.php, every Saturday at 1:10 AM.To have yourPHP server mail the reports, put this code in a recipe called, for example, cronjob.rb, and assign therecipe to the PHP App Server server layer's Setup and Deploy events. For more information, see cron.

Assigning cronjob.rb to the PHP Layer's lifecycle events will work if your stack has multiple applicationservers, but it is not ideal. For example, if you assign cronjob.rb to the PHP App Server layer, it runsthe recipe on every server instance, and you will receive multiple identical reports. A better approach isto use a custom layer to ensure that only one server sends a report, as follows:

1. Create a custom layer called, for example, AdminLayer and assign cronjob.rb to its Setup andDeploy events.

Custom layers don't necessarily have to do very much. In this case, AdminLayer just runs one customrecipe on its instances.

API Version 2013-02-18146

AWS OpsWorks User GuideRunning Cron Jobs

Page 153: Opsworks amazon

2. Assign one of the PHP App Server instances to AdminLayer.

If an instance belongs to more than one layer, AWS OpsWorks runs both layer's built-in and customrecipes.

Because only one PHP App Server instance belongs to AdminLayer, cronjob.rb runs only on thatinstance and you receive just one report.

Installing and Configuring PackagesThe built-in layers support only certain packages. For more information, see Layers (p. 64).You caninstall other packages, such as a Redis server or a Java application server, by implementing customrecipes to handle the associated setup, configuration, and deployment tasks. In some cases, the bestapproach is to extend a built-in layer to have it install the package on its instances alongside the layer'sstandard packages. For example, if you have a stack that supports a PHP application, and you wouldlike to include a Redis server, you could extend the PHP App Server layer to install and configure a Redisserver on the layer's instances in addition to a PHP application server.

A package installation recipe typically needs to perform tasks like these:

• Create one or more directories and set their modes.

• Create a configuration file from a template.

• Run the installer to install the package on the instance.

• Start one or more services.

For an example of how to install a Redis server, see Create a Custom Redis Layer (p. 198). The topicdescribes how to set up a custom Redis layer, but you could use much the same code to install andconfigure Redis on a built-in layer. For examples of how to install other packages, see the built-incookbooks, at https://github.com/aws/opsworks-cookbooks.

Stack Configuration and Deployment JSONWhen AWS OpsWorks runs a command on an instance—for example, a deploy command in responseto a Deploy lifecycle event—it sends a JSON object to the instance that describes the stack's currentconfiguration and. For deployments, the object includes some additional deployment information. Theobject's attributes are incorporated into the instance's master JSON structure, as described in CustomizingAWS OpsWorks Configuration by Overriding Attributes (p. 198).You can also view the structure directlyby using the agent CLI. For more information, see How to Obtain a Stack Configuration JSON (p. 198).For a list of commonly used stack configuration and deployment attributes, including fully qualified nodenames, see Appendix D: AWS OpsWorks Attribute Reference (p. 198).

The following sections show the JSON associated with a Configure event and a Deploy event for a simplestack, which consists of the following:

• A PHP App Server layer with two instances.

• An HAProxy layer with one instance

The JSON examples are from one of the PHP App Server instances, php-app1.

NoteInstances and layers are identified by their short names in the configuration JSON. For example,the PHP App Server layer is identified by "php-app".

API Version 2013-02-18147

AWS OpsWorks User GuideInstalling and Configuring Packages

Page 154: Opsworks amazon

Configure JSONThe following example is the JSON object for a Configure event, which occurs on every instance in thestack when an instance comes online or goes offline. The JSON for a Configure event consists of thebuilt-in stack configuration JSON and any custom stack JSON that was specified prior to the event (nonein this example). It has been edited for length.

{ "opsworks": { "layers": { "php-app": { "id": "4a2a56c8-f909-4b39-81f8-556536d20648", "instances": { "php-app2": { "elastic_ip": null, "region": "us-west-2", "booted_at": "2013-02-26T20:41:10+00:00", "ip": "192.112.235.192", "aws_instance_id": "i-34037f06", "availability_zone": "us-west-2a", "instance_type": "c1.medium", "private_dns_name": "ip-10-252-0-203.us-west-2.compute.internal", "private_ip": "10.252.0.203", "created_at": "2013-02-26T20:39:39+00:00", "status": "online", "backends": 8, "public_dns_name": "ec2-192-112-235-192.us-west-2.compute.amazon aws.com" }, "php-app1": { ... } }, "name": "PHP Application Server" }, "lb": { "id": "15c86142-d836-4191-860f-f4d310440f14", "instances": { "lb1": { ... } }, "name": "Load Balancer" } }, "agent_version": "104", "applications": [

], "stack": { "name": "MyStack" }, "ruby_version": "1.8.7", "sent_at": 1361911623, "ruby_stack": "ruby_enterprise", "instance": {

API Version 2013-02-18148

AWS OpsWorks User GuideConfigure JSON

Page 155: Opsworks amazon

"layers": [ "php-app" ], "region": "us-west-2", "ip": "192.112.44.160", "id": "45ef378d-b87c-42be-a1b9-b67c48edafd4", "aws_instance_id": "i-32037f00", "availability_zone": "us-west-2a", "private_dns_name": "ip-10-252-84-253.us-west-2.compute.internal", "instance_type": "c1.medium", "hostname": "php-app1", "private_ip": "10.252.84.253", "backends": 8, "architecture": "i386", "public_dns_name": "ec2-192-112-44-160.us-west-2.compute.amazonaws.com" }, "activity": "configure", "rails_stack": { "name": null }, "deployment": null, "valid_client_activities": [ "reboot", "stop", "setup", "configure", "update_dependencies", "install_dependencies", "update_custom_cookbooks", "execute_recipes" ] }, "opsworks_custom_cookbooks": { "recipes": [

], "enabled": false }, "recipes": [ "opsworks_custom_cookbooks::load", "opsworks_ganglia::configure-client", "ssh_users", "agent_version", "mod_php5_apache2::php", "php::configure", "opsworks_stack_state_sync", "opsworks_custom_cookbooks::execute", "test_suite", "opsworks_cleanup" ], "opsworks_rubygems": { "version": "1.8.24" }, "ssh_users": { }, "opsworks_bundler": { "manage_package": null, "version": "1.0.10"

API Version 2013-02-18149

AWS OpsWorks User GuideConfigure JSON

Page 156: Opsworks amazon

}, "deploy": { }}

Most of the information is in the opsworks attribute, which is often referred to as a namespace. Thefollowing list describes the key attributes:

• layers attributes–A set of attributes, each of which describes the configuration of one of the stack'slayers. The layers are identified by their shortnames, php-app and lb for this example. For moreinformation about layer shortnames for other layers, see Appendix A: AWS OpsWorks LayerReference (p. 198).

Every layer has an instances element, each of whose attributes describes one of the layers' instancesand bears the instance's short name. The PHP App Server layer has two instances, php-app1 andphp-app2.The HAProxy layer has one instance, lb1. Each instance attribute contains a set of attributesthat specify values such as the instance's private IP address and private DNS name. For brevity, theexample shows only php-app2 in detail; the others contain similar information.

• applications–A list of deployed apps, not found in this example.

• stack–The stack name; MyStack in this example.

• instance–The instance that this JSON resides on; php-app1 in this example. Recipes can use thisattribute to obtain information about the instance that they are running on, such as the instance's publicIP address.

• activity–The activity that produced the JSON; a configure event in this example.

• rails_stack–The Rails stack for stacks that include a Rails App Server layer.

• deployment–Whether this JSON is associated with a deployment. It is set to null for this examplebecause the JSON is associated with a Configure event.

• valid_client_activities–A list of valid client activities.

The opsworks attribute is followed by several top-level attributes, including the following:

• opsworks_custom_cookbooks–Whether custom cookbooks are enabled. If so, the attribute includesa list of custom recipes.

• recipes–The recipes that were run by this activity.

• opsworks_rubygems–The instance's RubyGems version.

• ssh_users–Lists SSH users; none in this example.

• opsworks_bundler–The bundler version and whether it is enabled.

• deploy–Information about deployment activities; none in this example.

Deploy JSONThe following example is a JSON object from php-app1 that is associated with the Deploy event thatdeployed the SimplePHP app to the stack's PHP instances. The JSON for a Deploy event consists of thebuilt-in stack configuration and deployment JSON, and any custom stack or deployment JSON (none forthis example). Much of the object is stack configuration JSON that is similar to the JSON for the Configureevent described in the previous section, so the example focuses primarily on the deployment-specificparts.

{ ...

API Version 2013-02-18150

AWS OpsWorks User GuideDeploy JSON

Page 157: Opsworks amazon

"opsworks": { ... "activity": "deploy", "applications": [ { "slug_name": "simplephp", "name": "SimplePHP", "application_type": "php" } ], "deployment": "5e6242d7-8111-40ee-bddb-00de064ab18f", ... }, ... "deploy": { "simplephp": { "migrate": false, "domains": [ "simplephp" ], "document_root": null, "symlink_before_migrate": { "config/opsworks.php": "opsworks.php" }, "restart_command": "echo 'restarting app'", "application_type": "php", "application": "simplephp", "scm": { "repository": "git://github.com/amazonwebservices/opsworks-demo-php-simple-app.git", "password": null, "ssh_key": null, "revision": null, "user": null, "scm_type": "git" }, "database": { "reconnect": true, "password": null, "username": "root", "host": null, "database": "simplephp" }, "symlinks": { }, "stack": { "needs_reload": false }, "auto_bundle_on_deploy": true, "sleep_before_restart": 0, "mounted_at": null, "memcached": { "host": null, "port": 11211 }, "ssl_certificate": null, "rails_env": null, "deploy_to": "/srv/www/simplephp",

API Version 2013-02-18151

AWS OpsWorks User GuideDeploy JSON

Page 158: Opsworks amazon

"ssl_certificate_ca": null, "ssl_support": false, "ssl_certificate_key": null } }}

The opsworks attribute is largely identical to the configure JSON example in the previous section. Thefollowing sections are most relevant to app deployment:

• activity–The event that is associated with the JSON; a Deploy event in this example.

• applications–A list of elements, one for each app, that provide the apps' names, slug names, andtypes. The slug name is a short name that AWS OpsWorks generates from the app name in order toidentify the app. The slug name for SimplePHP is simplephp.

• deployment–The deployment ID, which uniquely identifies the deployment.

The deploy section provides information about the applications that are currently being deployed. It isused, for example, by the built-in Deploy recipes. The section has one attribute for each deployed app.Each app attribute includes the following information:

• domains–By default, the domain is the app's slug name, which is the case in this example. If you haveassigned custom domains, they appear here as well. For more information, see Using CustomDomains (p. 198).

• application–The app's slug name.

• scm–This element contains the information required to download the app from its repository; a Gitrepository in this example.

• database–Database information, if the stack includes a MySQL layer.

• document_root–The document root, which is set to null in this example, indicating that the root ispublic.

• ssl_certificate_ca, ssl_support, ssl_certificate_key–Indicates whether the app has SSLsupport. If so, it includes the certificate information.

• deploy_to–The location of the app's code on the instance.

Using Stack Configuration JSON Values in CustomRecipesYour custom recipes can access stack configuration JSON values by constructing Chef nodes from thestructure. Each level in the structure corresponds to a node element. The following example obtains theactivity that is associated with the JSON:

node[:opsworks][:activity]

The following example obtains the private IP address of the HAProxy layer's first instance:

node[:opsworks][:layers][:lb][:instances].first[:private_ip]

For more information, see the documentation on Opscode Chef.

API Version 2013-02-18152

AWS OpsWorks User GuideUsing Stack Configuration JSON Values in Custom

Recipes

Page 159: Opsworks amazon

How to Obtain a Stack Configuration JSONAWS OpsWorks stores recent stack configuration JSONs locally as files named time-stamp.json,where time-stamp is the date and time that the JSON was installed on the system. There are typicallymultiple JSON files in this folder.You can identify the appropriate file by examining the time stamps onthe deployments page.The simplest way to retrieve a stack configuration JSON is to use SSH to connectto the instance and call the get_json agent CLI command to retrieve the JSON. For example, thefollowing command retrieves the most recent stack configuration JSON.

sudo opsworks-agent-cli get_json

For more information about how to use SSH with AWS OpsWorks instances, see Using SSH toCommunicate with an Instance (p. 198). For more information about how to use the agent CLI, see AppendixB: Instance Agent CLI (p. 198).

TroubleshootingThe best way to troubleshoot issues with your custom recipes is to examine the log files on a affectedinstance, which are in the following location:

• /var/lib/aws/opsworks/chef

• /var/log/aws/opsworks

You can rerun recipes on an instance by using SSH to connect to instance and using the instance agentCLI run_command command. This command is especially useful for setup recipes, which can't be rerunfrom the console. For more information on the instance agent CLI, see Appendix B: Instance AgentCLI (p. 198). For more information on how to set up an SSH connection to an instance, see Using SSH toCommunicate with an Instance (p. 198).

API Version 2013-02-18153

AWS OpsWorks User GuideHow to Obtain a Stack Configuration JSON

Page 160: Opsworks amazon

Monitoring

AWS OpsWorks uses Amazon CloudWatch to provide metrics for a stack and summarizes them for yourconvenience on the Monitoring page.You can view metrics for the entire stack, a specified layer, or aspecified instance.

To see the underlying data, go to the Amazon CloudWatch console and click Metrics in the left navigationcolumn. Then use the Viewing list at the top to select OpsWorks Stack Metrics, OpsWorks LayerMetrics, or OpsWorks Instance Metrics. Note that OpsWorks metrics are collected by a process runningon each instance (the instance agent) and the Amazon CloudWatch metrics are collected by the hypervisor,so they might have slightly different values.

You can also use Amazon CloudWatch console to set alarms. For more information, see AmazonCloudWatch.

Topics

• Stack Metrics (p. 154)

• Layer Metrics (p. 156)

• Instance Metrics (p. 156)

Stack MetricsTo view a summary of metrics for the entire stack, select a stack in the OpsWorks Dashboard and thenclick Monitoring in the left pane.The following example is for a stack with a PHP App Server and MySQLlayer.

API Version 2013-02-18154

AWS OpsWorks User GuideStack Metrics

Page 161: Opsworks amazon

The stack view displays graphs of four types of metrics for each layer—CPU utilization, memory utilization,load, and number of processes—over a specified time period: 1 hour, 8 hours, 24 hours, 1 week, or 2weeks. Note the following:

• AWS OpsWorks periodically updates the graphs; the countdown timer at the upper right indicates thetime remaining until the next update,

• If a layer has more than one instance, the graphs display average values for the layer.

• You can specify the time period by clicking the list at the upper right and selecting your preferred value.

For each metric type, you can use the list at the top of the graph to select the particular metric that youwant to view.

• CPU graph ranges from 0 - 100% and can display the following metrics:

• CPU Idle: The percentage of time that the CPU is idle.

• CPU User: The percentage of time that the CPU is handling user operations.

• CPU System: The percentage of time that the CPU is handling system operations.

• CPU IO wait: The percentage of time that the CPU is waiting for input/output operations.

• Memory graph ranges from 0 to the total amount of memory and can display the following metrics:

• Memory Total: The total amount of memory.

• Memory Used: The amount of memory in use.

• Memory SWAP: The amount of swap space.

• Memory Free: The amount of free memory.

• Load graph ranges from 0 to the current maximum value and displays the following metrics:

• Load (1 min): The load averaged over a 1-minute window.

• Load (5 min): The load averaged over a 5-minute window.

• Load (15 min): The load averaged over a 15-minute window.

• Processes graph ranges from 0 to the current maximum value, and displays a single metric: the numberof active processes.

API Version 2013-02-18155

AWS OpsWorks User GuideStack Metrics

Page 162: Opsworks amazon

Layer MetricsTo view metrics for a particular layer, click the layer name in the Monitoring Layers view. The followingexample shows metrics for the PHP App Server layer, which has two instances.

The metric types are the same as for the stack metrics, and for each type, you can use the list at the topof the graph to select the particular metric that you want to view.

TipYou can also display layer metrics by going to the layer's details page and clicking Monitoringat the upper right.

Instance MetricsTo view metrics for a particular instance, click the instance name in the layer monitoring view.The followingexample shows metrics for the PHP App Server layer's php-app1 instance.

API Version 2013-02-18156

AWS OpsWorks User GuideLayer Metrics

Page 163: Opsworks amazon

The graphs summarize all the available metrics for each metric type. To get exact values for a particularpoint in time, use your mouse to move the slider (indicated by the red arrow in the above illustration) tothe appropriate position.

TipYou can also display instance metrics by going to the instance's details page and clickingMonitoring at the upper right.

API Version 2013-02-18157

AWS OpsWorks User GuideInstance Metrics

Page 164: Opsworks amazon

Security and Permissions

When you create an AWS account, you create an access key and a secret key that you can use to loginto the account. However, the account keys provide unrestricted access to your account's resourcesand are difficult to revoke. To provide a more robust way to manage account access, AWS OpsWorksintegrates with AWS Identity and Access Management (IAM). By using IAM, you can give users accessto AWS OpsWorks but deny direct access to dependent services such as Amazon EC2. For example,you can give a user permission to stop instances by using AWS OpsWorks, but deny them the ability toterminate instances by using the Amazon EC2 console or API.

Using IAM with AWS OpsWorks lets you control the following:

• How AWS OpsWorks can act in your behalf to manage stack resources.You set permissions whenyou create a stack; IAM provides a policy template with predefined permissions for this task.

• How individual users are allowed to interact with AWS OpsWorks, such as managing stacks and usingSSH to connect to EC2 instances.

• How apps that run on EC2 instances controlled by AWS OpsWorks can access AWS resources. Thisapplies only if you deploy apps that access other AWS services and get their credentials through rolesin EC2 instances.

Topics

• Granting Users Permissions to Work with AWS OpsWorks (p. 159)

• Setting Permissions When Creating a Stack (p. 162)

• Specifying Permissions for Apps Running on EC2 instances (p. 163)

For more information about IAM, see:

• Identity and Access Management (IAM)

• Working with Users and Groups

• Delegating API Access by Using Roles

API Version 2013-02-18158

AWS OpsWorks User Guide

Page 165: Opsworks amazon

Granting Users Permissions to Work with AWSOpsWorks

With IAM users, you can grant each of your users a set of permissions that specify how they can workwith AWS OpsWorks, such as managing stacks, layers, and apps. In addition, you can enable users touse the MindTerm SSH client to log in to EC2 instances that are managed by AWS OpsWorks.

You often want to grant the same AWS OpsWorks permissions to multiple users. In that case, it's easiestto add those users to a group and then assign the permissions to the group. The following procedureassumes that you want to grant permissions to an IAM group that already contains users. For moreinformation, see Working with Users and Groups in the AWS Identity and Access Management UsingIAM guide.

To grant AWS OpsWorks permissions to a group of users

1. Sign in to the AWS Management Console and open the IAM console athttps://console.aws.amazon.com/iam/.

NoteTo import users as described in this procedure, you must be logged in as an IAM user whohas been granted the permissions defined in the IAM Administrator Access policy templateor logged in with the account's access and secret keys.

2. In the navigation pane on the left, click Groups.

3. Select an IAM group you want to grant to AWS OpsWorks permissions to.

4. Click the Permissions tab at the bottom and then click Attach Policy. If the group already has apolicy attached to it, click Attach Another Policy.

5. In the Manage Group Permissions wizard, click Select Policy Template.

6. Click Select next to the AWS OpsWorks Full Access template.This template provides permissionsthat let users manage AWS OpsWorks stacks. (Users can create stacks, but are only allowed toselect existing roles for the stack.)

7. Click Apply Policy.

After you grant permissions to a group or user, you must import them into AWS OpsWorks.

To import an IAM group or user into AWS OpsWorks

1. Navigate to the AWS OpsWorks console at https://console.aws.amazon.com/opsworks/.

2. In the AWS OpsWorks console, select a stack.

NoteYou must select a stack to import an IAM group or user, but you have to do so only once;the action makes the group or user available in every stack.

API Version 2013-02-18159

AWS OpsWorks User GuideGranting Users Permissions to Work with AWS

OpsWorks

Page 166: Opsworks amazon

3. On the Permissions page, click + Import IAM Users, select the user or users to add, and then clickImport.

4. Optionally, use the checkboxes to the right of a user's name to specify the following types of accessfor instances in the stack:

• SSH–This lets the user use the MindTerm SSH client to connect to instances in the stack. Whenusers log in to an instance using SSH, they use their IAM user's short name.To generate the shortname, AWS OpsWorks starts with the IAM user name, removes all non-alphanumeric characters,and then makes all alphabetic characters lowercase. For example, the user name "OpsWorks User1" becomes "opsworksuser1". For more information about using SSH with AWS OpsWorks stacks,see Using SSH to Communicate with an Instance (p. 198).

• sudo–Enables the user to have sudo privileges for the instances in the stack.You must selectSSH before you can select sudo. AWS OpsWorks adds the user's short name to the list of userswith sudo privileges.

NoteYou must specify SSH and sudo permissions individually for each stack.

Logging in as an IAM UserEach account has a URL called an Account Alias, which IAM users use to log in to the account. The URLis on your IAM console's Dashboard (Getting Started) page under Account Alias.

When creating a new IAM user, an administrator specifies or has the IAM service generate the following:

• A user name

• An optional password

You can specify a password or have IAM generate one for you.

• An optional Access Key ID and Secret Access Key

IAM generates a new key pair for each user. The keys are required for users who need to access AWSOpsWorks using the API or CLI. They are not required for console-only users.

The administrator then provides this information and the account alias to each new user, for example, inan e-mail.

To log into AWS OpsWorks as an IAM user

1. In your browser, navigate to the account alias.

API Version 2013-02-18160

AWS OpsWorks User GuideLogging in as an IAM User

Page 167: Opsworks amazon

2. Enter your user name and password and click Sign in using our secure server.

3. In the upper left corner, click Services and select OpsWorks.

To make AWS OpsWorks your default service, click the orange cube in the upper left corner. Thenselect OpsWorks in the Select Start Page dropdown.

Setting an IAM User's Public SSH KeyBefore an IAM user can use the MindTerm SSH client to connect to Amazon EC2 instances, the usermust provide AWS OpsWorks with the public key from an SSH key pair. AWS OpsWorks then distributesthe public key to every EC2 instance that it manages and the user can use the private half of the key toconnect. For more information on how to use the MindTerm client, see Using SSH to Communicate withan Instance (p. 198).

NoteYou cannot use an Amazon EC2 key for this purpose; Amazon EC2 does not provide you withthe public key.You must instead create a key pair by using a third-party tool, and store the publicand private keys. For more information see How to Generate Your Own Key and Import It toAmazon EC2.

TipIf you use PuTTYgen to generate your key pair, copy the public key from the Public key forpasting into OpenSSH authorized_keys file box. Save Public Key saves the public key in aformat that is not supported by MindTerm.

After you have imported IAM users into AWS OpsWorks with the permissions specified in the AWSOpsWorks Full Access policy template (as explained in Granting Users Permissions to Work with AWSOpsWorks (p. 198)), they can specify the public key themselves.

To specify an IAM User's SSH public key

1. Log into the AWS OpsWorks console as an IAM user.

2. Select My Settings, which displays the settings for the logged-in IAM user.

3. On the My Settings page, click Edit.

4. In the Public SSH Key box, enter your SSH public key, and then click Save.

API Version 2013-02-18161

AWS OpsWorks User GuideSetting an IAM User's Public SSH Key

Page 168: Opsworks amazon

NoteThis procedure associates the logged-in IAM user with a public SSH key; each IAM user provideshis or her own key.You cannot perform the procedure if you sign in with your account's accessand secretkeys. The console displays My Settings only if you are logged in as an IAM user.

Setting Permissions When Creating a StackTo work on users' behalf, AWS OpsWorks needs permissions to perform tasks on your behalf such aslaunching EC2 instances and getting Amazon CloudWatch statistics. When you create a stack, AWSOpsWorks lets you select an IAM role that specifies the appropriate permissions:

You have these options when you specify the role for a new stack:

• Let AWS OpsWorks create a new role that has the permissions that AWS OpsWorks needs.

• Reuse a role that AWS OpsWorks created when a stack was added previously.

• Specify an existing IAM role that has the permissions you need.You might do this if you want AWSOpsWorks to have more limited permissions than those that are granted by the default role.

In practice, it's usually easiest to allow AWS OpsWorks to create a role, or to reuse a role that AWSOpsWorks created previously. The default role specifies that the stack is allowed to do the following:

• Perform all Amazon EC2 actions (ec2:*). This lets AWS OpsWorks launch instances on behalf ofusers.

API Version 2013-02-18162

AWS OpsWorks User GuideSetting Permissions When Creating a Stack

Page 169: Opsworks amazon

• Get Amazon CloudWatch statistics (cloudwatch:GetMetricStatistics).This lets AWS OpsWorkstrack metrics.

• Use Elastic Load Balancing to distribute traffic to servers.

• Use IAM roles (iam:PassRole). This lets AWS OpsWorks add an IAM instance profile to providesecure communication between AWS OpsWorks and your Amazon EC2 instances.

NoteTo create the first stack in the console, you must be logged in as an IAM user who has beengranted the permissions defined in the IAM Administrator Access policy template or loggedwith the account's access and secret keys. This gives you permissions to have AWS OpsWorkscreate a new role. It also gives you permissions to import users, as described earlier. After thefirst stack has been created, users can select a role created earlier by AWS OpsWorks andtherefore don't require full administrator permissions to create a stack.

A new stack also requires a default instance profile:

This instance profile specifies a role to be associated with EC2 instances that are launched by AWSOpsWorks. If you want to specify permissions that are needed by apps running on EC2 instances (forexample, if your apps access Amazon S3 buckets), you should choose an existing instance profile (role)that has the right permissions. Otherwise, you should let AWS OpsWorks create this instance profile foryou. For more information, see Specifying Permissions for Apps Running on EC2 instances (p. 198).

Specifying Permissions for Apps Running onEC2 instances

When you create an AWS OpsWorks stack, the Default IAM Instance Profile list (under Advanced >>settings) lets you specify an instance profile (effectively, a role) that will be associated with EC2 instanceslaunched in the stack. The instance profile identifies an IAM role that provides credentials used in theinstance. AWS OpsWorks can create the instance profile (and role) for you. However, there is no policyassociated with the generated role, meaning that the role has no permissions.

You might have apps that run on EC2 instances and that access other AWS resources such as AmazonS3 buckets or Amazon RDS databases. If those apps are written to get credentials from the instancethey're running on, instead of allowing AWS OpsWorks to generate a role for you, you should choose anexisting role for the stack that already has the appropriate permissions to let the app access AWSresources.

If you use an instance profile to call the AWS OpsWorks API from an EC2 instance, you must allow theiam:PassRole operation in addition to the appropriate AWS OpsWorks actions. The iam:PassRolepermission allows AWS OpsWorks to assume the service role on your behalf. For more information aboutthe AWS OpsWorks API, see AWS OpsWorks API Reference.

The following is an example of an IAM policy that allows you to call any AWS OpsWorks action from anEC2 instance, as well as any Amazon EC2 or Amazon S3 action.

API Version 2013-02-18163

AWS OpsWorks User GuideSpecifying Permissions for Apps Running on EC2

instances

Page 170: Opsworks amazon

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:*", "s3:*", "opsworks:*", "iam:PassRole"], "Resource": "*" } ] }

NoteIf you do not allow iam:PassRole, any attempt to call an AWS OpsWorks action fails with anerror like the following:

User: arn:aws:sts::123456789012:federated-user/Bob is not authorizedto perform: iam:PassRole on resource:arn:aws:sts::123456789012:role/OpsWorksStackIamRole

For more information about using roles on an EC2 instance for permissions, see Granting Applicationsthat Run on Amazon EC2 Instances Access to AWS Resources in the AWS Identity and AccessManagement Using IAM guide.

API Version 2013-02-18164

AWS OpsWorks User GuideSpecifying Permissions for Apps Running on EC2

instances

Page 171: Opsworks amazon

Appendix A: AWS OpsWorks LayerReference

Every instance deployed by AWS OpsWorks must be a member of at least one layer, which define aninstance's role in the stack and control the details of setting up and configuring the instance, installingpackages, deploying applications, and so on. This topic describes the AWS OpsWorks layers. For moreinformation about how to use the AWS OpsWorks to create and manage layers, see Layers (p. 64).

Each layer description includes a list of the standard recipes that AWS OpsWorks runs for each of thelayer's lifecycle events, which are stored at https://github.com/aws/opsworks-cookbooks. Note that thelists include only those recipes that are run directly by AWS OpsWorks. Those recipes sometimes rundependent recipes, which are not listed.To see the complete list of recipes for a particular event, includingdependent and custom recipes, examine the run list in the appropriate lifecycle event's log file.

Topics

• HAProxy Layer (p. 165)

• MySQL Layer (p. 167)

• Web Server Layers (p. 168)

• Custom Layer (p. 173)

• Other Layers (p. 174)

HAProxy LayerA HAProxy layer uses HAProxy—a reliable high-performance TCP/HTTP load balancer— to provide highavailability load balancing and proxy services for TCP and HTTP-based applications. It is particularlyuseful for websites that must crawl under very high loads while requiring persistence or Layer 7 processing.

HAProxy monitors traffic and displays the statistics and the health of the associated instances on a webpage. By default, the URI is http://DNSName/haproxy?stats, where DNSName is the HAProxy instance'sDNS name.

Short name: lb

Compatibility: A HAProxy layer is compatible with the following layers: custom, db-master, andmemcached.

API Version 2013-02-18165

AWS OpsWorks User GuideHAProxy Layer

Page 172: Opsworks amazon

Open Ports: HAProxy allows public access to ports 22(SSH), 80 (HTTP), and 443 (HTTPS).

Auto-assign Elastic IP Addresses: On by default

Default EBS Volume: No

Default Security Group: AWS-OpsWorks-LB-Server

Configuration: To configure a HAProxy layer, you must specify the following:

• Health check URI (default: http://DNSName/).

• Statistics URI (default: http://DNSName/haproxy?stats).

• Statistics Password (optional).

• Health check method (optional). By default, HaProxy uses the HTTP OPTIONS method.You can alsospecify GET or HEAD.

• Enable statistics (optional)

• Ports. By default, AWS OpsWorks configures HaProxy to handle both HTTP and HTTPS traffic.Youcan configure HaProxy to handle only one or the other by overriding the Chef configuration template,haproxy.cfg.erb.

Setup recipes:

• opsworks_initial_setup

• ssh_host_keys

• ssh_users

• mysql::client

• dependencies

• ebs

• opsworks_ganglia::client

• haproxy

Configure recipes:

• opsworks_ganglia::configure-client

• ssh_users

• agent_version

• haproxy::configure

Deploy recipes:

• deploy::default

• haproxy::configure

Shutdown recipes:

• opsworks_shutdown::default

• haproxy::stop

Installation

• AWS OpsWorks uses the instance's package installer to install HAProxy to its default locations.

API Version 2013-02-18166

AWS OpsWorks User GuideHAProxy Layer

Page 173: Opsworks amazon

• You must set up syslog to direct the log files to a specified location. For more information, see HAProxy.

MySQL LayerThe MySQL layer supports MySQL, a widely used relational database management system. AWSOpsWorks installs the most recent available version, which depends on the operating system. If you adda MySQL instance, the needed access information is provided to the application server layers.You mustwrite custom Chef recipes to set up master/master or master/slave configurations.

Short name: db-master

Compatibility: A MySQL layer is compatible with the following layers: custom, lb, memcached,monitoring-master, nodejs-app, php-app, rails-app, and web.

Open Ports: A MySQL layer allows public access to port 22(SSH) and all ports from the stack's webservers, custom servers, and Rails, PHP, and Node.js application servers.

Auto-assign Elastic IP Addresses: Off by default

Default EBS Volume: Yes, at /vol/mysql

Default Security Group: AWS-OpsWorks-DB-Master-Server

Configuration: To configure a MySQL layer, you must specify the following:

• Root user password

• MySQL Engine

Setup recipes:

• opsworks_initial_setup

• ssh_host_keys

• ssh_users

• mysql::client

• dependencies

• ebs

• opsworks_ganglia::client

• mysql::server

• dependencies

• deploy::mysql

Configure recipes:

• opsworks_ganglia::configure-client

• ssh_users

• agent_version

• deploy::mysql

Deploy recipes:

• deploy::default

• deploy::mysql

API Version 2013-02-18167

AWS OpsWorks User GuideMySQL Layer

Page 174: Opsworks amazon

Shutdown recipes:

• opsworks_shutdown::default

• mysql::stop

Installation

• AWS OpsWorks uses the instance's package installer to install MySQL and its log files to their defaultlocations. For more information, see MySQL Documentation.

Web Server LayersAWS OpsWorks supports several different application and static web page servers.

Topics

• Node.js App Server Layer (p. 168)

• PHP App Server Layer (p. 169)

• Rails App Server Layer (p. 170)

• Static Web Server Layer (p. 172)

Node.js App Server LayerA Node.js App Server layer supports a Node.js application server, which is a platform for implementinghighly scalable network application servers. Programs are written in JavaScript, using event-drivenasynchronous I/O to minimize overhead and maximize scalability.

Short name: nodejs-app

Compatibility: A Node.js App Server layer is compatible with the following layers: custom, db-master,memcached, and monitoring-master.

Open Ports: A Node.js App Server layer allows public access to ports 22(SSH), 80 (HTTP), 443 (HTTPS),and all ports from HAProxy layers.

Auto-assign Elastic IP Addresses: Off by default

Default EBS Volume: No

Default Security Group: AWS-OpsWorks-nodejs-App-Server

Setup recipes:

• opsworks_initial_setup

• ssh_host_keys

• ssh_users

• mysql::client

• dependencies

• ebs

• opsworks_ganglia::client

• opsworks_nodejs

• opsworks_nodejs::npm

API Version 2013-02-18168

AWS OpsWorks User GuideWeb Server Layers

Page 175: Opsworks amazon

Configure recipes:

• opsworks_ganglia::configure-client

• ssh_users

• agent_version

• opsworks_nodejs::configure

Deploy recipes:

• deploy::default

• opsworks_nodejs

• opsworks_nodejs::npm

• deploy::nodejs

Undeploy recipes:

• deploy::nodejs-undeploy

Shutdown recipes:

• opsworks_shutdown::default

• deploy::nodejs-stop

Installation

• Node.js installs to /usr/local/bin/node.

• For more information about how to produce log files, see How to log in node.js.

Node.js Application Configuration

• The main file run by Node.js must be named server.js and reside in the root directory of the deployedapplication.

• The Node.js application must be set to listen on port 80 (or port 443, if applicable).

PHP App Server LayerThe PHP App Server layer supports a PHP application server by using Apache2 with mod_php.

Short name: php-app

Compatibility: A PHP App Server layer is compatible with the following layers: custom, db-master,memcached, monitoring-master, and rails-app.

Open Ports: A PHP App Server layer allows public access to ports 22(SSH), 80 (HTTP), 443 (HTTPS),and all ports from load balancer layers.

Auto-assign Elastic IP Addresses: Off by default

Default EBS Volume: No

Default Security Group: AWS-OpsWorks-PHP-App-Server

Setup recipes:

API Version 2013-02-18169

AWS OpsWorks User GuidePHP App Server Layer

Page 176: Opsworks amazon

• opsworks_initial_setup

• ssh_host_keys

• ssh_users

• mysql::client

• dependencies

• ebs

• opsworks_ganglia::client

• mysql::client

• dependencies

• mod_php5_apache2

Configure recipes:

• opsworks_ganglia::configure-client

• ssh_users

• agent_version

• mod_php5_apache2::php

• php::configure

Deploy recipes:

• deploy::default

• deploy::php

Undeploy recipes:

• deploy::php-undeploy

Shutdown recipes:

• opsworks_shutdown::default

• apache2::stop

Installation

• AWS OpsWorks uses the instance's package installer to install Apache2, mod_php and the associatedlog files to their default locations. For more information about installation, see Apache. For moreinformation about logging, see Log Files.

Rails App Server LayerThe Rails App Server layer supports a Ruby on Rails application server.

Short name: rails-app

Compatibility: A Rails App Server layer is compatible with the following layers: custom, db-master,memcached, monitoring-master, php-app.

Ports: A Rails App Server layer allows public access to ports 22(SSH), 80 (HTTP), 443 (HTTPS), andall ports from load balancer layers.

API Version 2013-02-18170

AWS OpsWorks User GuideRails App Server Layer

Page 177: Opsworks amazon

Auto-assign Elastic IP Addresses: Off by default

Default EBS Volume: No

Default Security Group: AWS-OpsWorks-Rails-App-Server

Configuration: To configure a Rails App Server layer, you must specify the following:

• Ruby version

• Rails stack

• Rubygems version

• Whether to install and manage Bundler

• The Bundler version

Setup recipes:

• opsworks_initial_setup

• ssh_host_keys

• ssh_users

• mysql::client

• dependencies

• ebs

• opsworks_ganglia::client

• apache2 apache2::mod_deflate

• passenger_apache2

• passenger_apache2::mod_rails

• passenger_apache2::rails

Configure recipes:

• opsworks_ganglia::configure-client

• ssh_users

• agent_version

• rails::configure

Deploy recipes:

• deploy::default

• deploy::rails

Undeploy recipes:

• deploy::rails-undeploy

Shutdown recipes:

• opsworks_shutdown::default

• apache2::stop

Installation

API Version 2013-02-18171

AWS OpsWorks User GuideRails App Server Layer

Page 178: Opsworks amazon

• AWS OpsWorks uses the instance's package installer to install Apache2 with mod_passenger, mod_rails,and the associated log files to their default locations. For more information about installation, seePhusion Passenger. For more information about logging, see Log Files.

Static Web Server LayerThe Static Web Server layer serves static HTML pages, which can include client-side code such asJavaScript. It is based on Nginx, which is an open source HTTP, reverse proxy, and mail proxy server.

Short name: web

Compatibility: A Static Web Server layer is compatible with the following layers: custom, db-master,memcached.

Open Ports: A Static Web Server layer allows public access to ports 22(SSH), 80 (HTTP), 443 (HTTPS),and all ports from HAProxy layers.

Auto-assign Elastic IP Addresses: Off by default

Default EBS Volume: No

Default Security Group: AWS-OpsWorks-Web-Server

Setup recipes:

• opsworks_initial_setup

• ssh_host_keys

• ssh_users

• mysql::client

• dependencies

• ebs

• opsworks_ganglia::client

• nginx

Configure recipes:

• opsworks_ganglia::configure-client

• ssh_users

• agent_version

Deploy recipes:

• deploy::default

• deploy::web

Undeploy recipes:

• deploy::web-undeploy

Shutdown recipes:

• opsworks_shutdown::default

• nginx::stop

API Version 2013-02-18172

AWS OpsWorks User GuideStatic Web Server Layer

Page 179: Opsworks amazon

Installation

• Nginx installs to /usr/sbin/nginx.

• Nginx log files are in /var/log/nginx.

Custom LayerIf the standard layers don't suit your requirements, you can create a custom layer. A stack can havemultiple custom layers. By default, the custom layer runs a limited set of standard recipes that supportbasic functionality, such as Ganglia monitoring.You then implement the layer's primary functionality byimplementing a set of custom Chef recipes for each of the appropriate lifecycle events to set up andconfigure the layer's software, and so on. Custom recipes run after the standard AWS OpsWorks recipesfor each event.

Short name: User-defined; each custom layer in a stack must have a different short name

Open Ports: By default, a custom server layer opens public access to ports 22(SSH), 80 (HTTP), 443(HTTPS), and all ports from the stack's Rails and PHP application server layers

Auto-assign Elastic IP Addresses: Off by default

Default EBS Volume: No

Default Security Group: AWS-OpsWorks-Custom-Server

Compatibility: Custom layers are compatible with the following layers: custom, db-master, lb, memcached,monitoring-master, nodejs-app, php-app, rails-app, and web

Configuration: To configure a custom layer, you must specify the following:

• The layer's name

• The layer's short name, which identifies the layer in Chef recipes and must use only a-z and numbers

Setup recipes:

• opsworks_initial_setup

• ssh_host_keys

• ssh_users

• mysql::client

• dependencies

• ebs

• opsworks_ganglia::client

Configure recipes:

• opsworks_ganglia::configure-client

• ssh_users

• agent_version

Deploy recipes:

• deploy::default

API Version 2013-02-18173

AWS OpsWorks User GuideCustom Layer

Page 180: Opsworks amazon

Shutdown recipes:

• opsworks_shutdown::default

Other LayersAWS OpsWorks also supports the following layers.

Ganglia LayerA Ganglia layer supports Ganglia, a distributed monitoring system that manages the storage andvisualization of instance metrics. It is designed to work with hierarchical instance topologies, which makesit particularly useful for groups of instances. Ganglia has two basic components:

• A low-overhead client, which is installed on each instance in the stack and sends metrics to the master.

• A master, which collects metrics from the clients and stores them on an Amazon EBS volume. It alsodisplays the metrics on a web page.

AWS OpsWorks has a Ganglia monitoring agent on each instance that it manages. When you add aGanglia layer to your stack and start it, the Ganglia agents on each instance report metrics to the Gangliainstance. To use Ganglia, add a Ganglia layer with one instance to the stack.You access the data bylogging in to the Ganglia backend at the master's IP address.You can provide additional metric definitionsby writing Chef recipes.

Short name: monitoring-master

Compatibility: A Ganglia layer is compatible with the following layers: custom, db-master, memcached,php-app, rails-app.

Open Ports: Load-Balancer allows public access to ports 22(SSH), 80 (HTTP), and 443 (HTTPS).

Auto-assign Elastic IP Addresses: Off by default

Default EBS Volume: Yes, at /vol/ganglia

Default Security Group: AWS-OpsWorks-Monitoring-Master-Server

Configuration: To configure a Ganglia layer, you must specify the following:

• The URI that provides access to the monitoring graphs. The default value is http://DNSName/ganglia,where DNSName is the Ganglia instance's DNS name.

• A user name and password that control access to the monitoring statistics.

Setup recipes:

• opsworks_initial_setup

• ssh_host_keys

• ssh_users

• mysql::client

• dependencies

• ebs

• opsworks_ganglia::client

• opsworks_ganglia::server

API Version 2013-02-18174

AWS OpsWorks User GuideOther Layers

Page 181: Opsworks amazon

Configure recipes:

• opsworks_ganglia::configure-client

• ssh_users

• agent_version

• opsworks_ganglia::configure-server

Deploy recipes:

• deploy::default

• opsworks_ganglia::configure-server

• opsworks_ganglia::deploy

Shutdown recipes:

• opsworks_shutdown::default

• apache2::stop

Installation

• The Ganglia client is installed under: /etc/ganglia.

• The Ganglia web front end is installed under: /usr/share/ganglia-webfrontend.

• The Ganglia logtailer is installed under: /usr/share/ganglia-logtailer.

Memcached LayerMemcached is a distributed memory-caching system for arbitrary data. It speed up websites by cachingstrings and objects as keys and values in RAM to reduce the number of times an external data sourcemust be read.

To use Memcached in a stack, create a Memcached layer and add one or more instances, which functionas Memcached servers. The instances automatically install Memcached and the stack's other instancesare able to access and use the Memcached servers. If you use a Rails App Server layer, AWS OpsWorksautomatically places a memcached.yml configuration file in the config directory of each instance in thelayer.You can obtain the Memcached server and port number from this file.

Short name: memcached

Compatibility: A Memcached layer is compatible with the following layers: custom, db-master, lb,monitoring-master, nodejs-app, php-app, rails-app, and web.

Open Ports: A Memcached layer allows public access to port 22(SSH) and all ports from the stack's webservers, custom servers, and Rails, PHP, and Node.js application servers.

Auto-assign Elastic IP Addresses: Off by default

Default EBS Volume: No

Default Security Group: AWS-OpsWorks-Memcached-Server

To configure a Memcached layer, you must specify the cache size, in MB.

Setup recipes:

API Version 2013-02-18175

AWS OpsWorks User GuideMemcached Layer

Page 182: Opsworks amazon

• opsworks_initial_setup

• ssh_host_keys

• ssh_users

• mysql::client

• dependencies

• ebs

• opsworks_ganglia::client

• memcached

Configure recipes:

• opsworks_ganglia::configure-client

• ssh_users

• agent_version

Deploy recipes:

• deploy::default

Shutdown recipes:

• opsworks_shutdown::default

• memcached::stop

Installation

• AWS OpsWorks uses the instance's package installer to install Memcached and its log files to theirdefault locations.

API Version 2013-02-18176

AWS OpsWorks User GuideMemcached Layer

Page 183: Opsworks amazon

Appendix B: Instance Agent CLI

The instance agent that AWS OpsWorks installs on every instance exposes a a command line interface(CLI). If you connect using SSH to the instance, you can use the CLI to:

• Access Chef run log files

• Access AWS OpsWorks commands

• Manually run Chef recipes

• View instance reports

• View agent reports

• View an abstract of the most recent stack configuration JSON (p. 147)

ImportantYou can run agent CLI commands only as root or by using sudo.

The basic command syntax is:

sudo opsworks-agent-cli [--help] [command [activity] [date]]

The four arguments are:

help[Optional] Displays a brief synopsis of the available commands when used by itself. When used witha command, help displays a description of the command.

command[Optional] The agent CLI command, which must be set to one of the following:

• agent_report (p. 198)

• get_json (p. 198)

• instance_report (p. 198)

• list_commands (p. 198)

• run_command (p. 198)

• show_log (p. 198)

• stack_state (p. 198)

activity[Optional] You can use this argument with some commands to specify a particular AWS OpsWorksactivity: setup, configure, deploy, undeploy, start, stop, or restart.

API Version 2013-02-18177

AWS OpsWorks User Guide

Page 184: Opsworks amazon

date[Optional] You can use this argument with some commands to specify a particular AWS OpsWorkscommand execution.You specify the command execution by setting date to the time that the commandwas executed in the 'yyyy-mm-ddd-hh-mm-ss' format, including the single quotes. For example, for10:31:55 on Tuesday Feb 5, 2013, use: '2013-02-05T10:31:55'.To determine when a particular AWSOpsWorks command was executed, run list_commands (p. 198).

NoteIf the agent has executed the same AWS OpsWorks activity multiple times, you can pick aparticular execution by specifying both the activity and the time it was executed. If you specifyan activity and omit the time, the agent CLI command acts on the activity's most recent execution.If you omit both arguments, the agent CLI command acts on the most recent activity.

The following sections describe the commands and their associated arguments. For brevity, the syntaxsections omit the optional --help option, which can be used with any command.

Topics

• agent_report (p. 178)

• get_json (p. 178)

• instance_report (p. 181)

• list_commands (p. 182)

• run_command (p. 182)

• show_log (p. 183)

• stack_state (p. 184)

agent_reportDisplays an agent report.

sudo opsworks-agent-cli agent_report

The following output example is from a PHP App Server instance that most recently ran a deploy activity.

[ec2-user@php-app1 ~]$ sudo opsworks-agent-cli agent_report

AWS OpsWorks Instance Agent State Report:

Last activity was a "deploy" on Tue Feb 26 19:21:13 UTC 2013 Agent Status: The AWS OpsWorks agent is running as PID 1282 Agent Version: 104, up to date

get_jsonDisplays a command's stack configuration JSON.

sudo opsworks-agent-cli get_json [activity] [date]

API Version 2013-02-18178

AWS OpsWorks User Guideagent_report

Page 185: Opsworks amazon

By default, get_json displays the stack configuration JSON for the most recent activity. Use the followingoptions to specify a particular file.

activityDisplay the specified activity's JSON file.

dateDisplay the JSON file for the activity executed at the specified date.

The following output example is from a PHP App Server instance and shows the JSON for the most recentconfigure activity.

[ec2-user@php-app1 ~]$ sudo opsworks-agent-cli get_json configure{ "opsworks": { "layers": { "php-app": { "id": "4a2a56c8-f909-4b39-81f8-556536d20648", "instances": { "php-app2": { "elastic_ip": null, "region": "us-west-2", "booted_at": "2013-02-26T20:41:10+00:00", "ip": "10.112.235.192", "aws_instance_id": "i-34037f06", "availability_zone": "us-west-2a", "instance_type": "c1.medium", "private_dns_name": "ip-10-252-0-203.us-west-2.compute.internal", "private_ip": "10.252.0.203", "created_at": "2013-02-26T20:39:39+00:00", "status": "online", "backends": 8, "public_dns_name": "ec2-10-112-235-192.us-west-2.compute.amazon aws.com" }, "php-app1": { "elastic_ip": null, "region": "us-west-2", "booted_at": "2013-02-26T20:41:09+00:00", "ip": "10.112.44.160", "aws_instance_id": "i-32037f00", "availability_zone": "us-west-2a", "instance_type": "c1.medium", "private_dns_name": "ip-10-252-84-253.us-west-2.compute.internal",

"private_ip": "10.252.84.253", "created_at": "2013-02-26T20:39:35+00:00", "status": "online", "backends": 8, "public_dns_name": "ec2-10-112-44-160.us-west-2.compute.amazon aws.com" } }, "name": "PHP Application Server" }, "lb": { "id": "15c86142-d836-4191-860f-f4d310440f14",

API Version 2013-02-18179

AWS OpsWorks User Guideget_json

Page 186: Opsworks amazon

"instances": { "lb1": { "elastic_ip": "54.244.244.50", "region": "us-west-2", "booted_at": "2013-02-26T20:41:14+00:00", "ip": null, "aws_instance_id": "i-3a037f08", "availability_zone": "us-west-2a", "instance_type": "c1.medium", "private_dns_name": "ip-10-253-1-116.us-west-2.compute.internal", "private_ip": "10.253.1.116", "created_at": "2013-02-26T20:39:44+00:00", "status": "online", "backends": 8, "public_dns_name": null } }, "name": "Load Balancer" } }, "agent_version": "104", "applications": [

], "stack": { "name": "MyStack" }, "ruby_version": "1.8.7", "sent_at": 1361911623, "ruby_stack": "ruby_enterprise", "instance": { "layers": [ "php-app" ], "region": "us-west-2", "ip": "10.112.44.160", "id": "45ef378d-b87c-42be-a1b9-b67c48edafd4", "aws_instance_id": "i-32037f00", "availability_zone": "us-west-2a", "private_dns_name": "ip-10-252-84-253.us-west-2.compute.internal", "instance_type": "c1.medium", "hostname": "php-app1", "private_ip": "10.252.84.253", "backends": 8, "architecture": "i386", "public_dns_name": "ec2-10-112-44-160.us-west-2.compute.amazonaws.com" }, "activity": "configure", "rails_stack": { "name": null }, "deployment": null, "valid_client_activities": [ "reboot", "stop", "setup", "configure", "update_dependencies",

API Version 2013-02-18180

AWS OpsWorks User Guideget_json

Page 187: Opsworks amazon

"install_dependencies", "update_custom_cookbooks", "execute_recipes" ] }, "opsworks_custom_cookbooks": { "recipes": [

], "enabled": false }, "recipes": [ "opsworks_custom_cookbooks::load", "opsworks_ganglia::configure-client", "ssh_users", "agent_version", "mod_php5_apache2::php", "php::configure", "opsworks_stack_state_sync", "opsworks_custom_cookbooks::execute", "test_suite", "opsworks_cleanup" ], "opsworks_rubygems": { "version": "1.8.24" }, "ssh_users": { }, "opsworks_bundler": { "manage_package": null, "version": "1.0.10" }, "deploy": { }}

instance_reportDisplays an extended instance report.

sudo opsworks-agent-cli instance_report

The following output example is from a PHP App Server instance.

[ec2-user@php-app1 ~]$ sudo opsworks-agent-cli instance_report

AWS OpsWorks Instace Agent State Report:

Last activity was a "deploy" on Tue Feb 26 19:21:13 UTC 2013 Agent Status: The AWS OpsWorks agent is running as PID 1282 Agent Version: 104, up to date OpsWorks Stack: MyStack OpsWorks Layers: php-app

API Version 2013-02-18181

AWS OpsWorks User Guideinstance_report

Page 188: Opsworks amazon

OpsWorks Instance: php-app1 EC2 Instace ID: i-065fc875 EC2 Instance Type: c1.medium Architecture: i386 Total Memory: 1.76 Gb CPU: 2x Intel(R) Xeon(R) CPU E5410 @ 2.33GHz

Location:

EC2 Region: us-east-1 EC2 Availability Zone: us-east-1a

Networking:

Public IP: 204.236.200.220 Private IP: domU-12-31-39-01-96-8A.compute-1.internal

list_commandsLists the time for each activity that has been executed on this instance.You can use these times for otheragent-CLI commands to specify a particular execution.

sudo opsworks-agent-cli list_commands [activity] [date]

The following output example is from a PHP App Server instance that has run a setup, deploy, and twoconfigure activities:

[ec2-user@php-app1 ~]$ sudo opsworks-agent-cli list_commands2013-02-26T19:08:26 setup2013-02-26T19:12:01 configure2013-02-26T19:12:05 configure2013-02-26T19:22:12 deploy

run_commandRuns an AWS OpsWorks command, which is a JSON file containing a Chef run-list that contains theinformation necessary to execute an AWS OpsWorks activity (setup, configure, deploy, and so on). Therun_command command generates a log entry that you can view by running show_log (p. 198). Thisoption is intended only for development purposes, so AWS OpsWorks does not track changes.

sudo opsworks-agent-cli run_command [activity] [date] [/path/to/valid/json.file]

By default, run_command runs the most recent AWS OpsWorks command. Use the following options tospecify a particular command.

activityRun the AWS OpsWorks command for the specified activity:setup, configure, deploy, undeploy,start, stop, or restart.

API Version 2013-02-18182

AWS OpsWorks User Guidelist_commands

Page 189: Opsworks amazon

dateRuns the AWS OpsWorks command executed at the specified time.

fileRuns the specified command JSON file. To get a command's file path, run get_json (p. 198).

The following output example is from a PHP App Server instance and runs the configure command.

[ec2-user@php-app1 ~]$ sudo opsworks-agent-cli run_command configure[2013-02-26 19:56:58] INFO [opsworks-agent (6694)] About to re-run 'configure' from 2013-02-26T19:12:05Waiting for process 6697pid 6697 exited with status 0, exit code: 0 (time=4 sec)[2013-02-26 19:57:02] INFO [opsworks-agent (6694)] Finished Chef run with exit code 0

show_logDisplays a command's log file.

sudo opsworks-agent-cli show_log [activity] [date]

By default, show_log tails the most recent log file. Use the following options to specify a particularcommand.

activityDisplays the specified activity's log file.

dateDisplays the log file for the activity executed at the specified time.

The following output example is from a PHP App Server instance and shows the most recent log.

[ec2-user@php-app1 ~]$ sudo opsworks-agent-cli show_log[Tue, 26 Feb 2013 19:22:20 +0000] INFO: Chef Run complete in 6.441339 seconds[Tue, 26 Feb 2013 19:22:20 +0000] INFO: cleaning the checksum cache[Tue, 26 Feb 2013 19:22:20 +0000] DEBUG: removing unused checksum cache file /var/chef/cache/checksums/chef-file--etc-sudoers[Tue, 26 Feb 2013 19:22:20 +0000] DEBUG: removing unused checksum cache file /var/chef/cache/checksums/chef-file--tmp-chef-rendered-template20130226-3288-y75s0q-0[Tue, 26 Feb 2013 19:22:20 +0000] DEBUG: removing unused checksum cache file /var/chef/cache/checksums/chef-file--tmp-chef-rendered-template20130226-3288-1jlrfv4-0[Tue, 26 Feb 2013 19:22:20 +0000] DEBUG: removing unused checksum cache file /var/chef/cache/checksums/chef-file--tmp-chef-rendered-template20130226-3288-s6k78b-0[Tue, 26 Feb 2013 19:22:20 +0000] DEBUG: removing unused checksum cache file /var/chef/cache/checksums/chef-file--var-lib-aws-opsworks-TARGET_VERSION[Tue, 26 Feb 2013 19:22:20 +0000] DEBUG: removing unused checksum cache file /var/chef/cache/checksums/chef-file--tmp-chef-rendered-template20130226-3288-1bq1mfg-0

API Version 2013-02-18183

AWS OpsWorks User Guideshow_log

Page 190: Opsworks amazon

[Tue, 26 Feb 2013 19:22:20 +0000] DEBUG: removing unused checksum cache file /var/chef/cache/checksums/chef-file--etc-ganglia-gmond-conf[Tue, 26 Feb 2013 19:22:20 +0000] INFO: Running report handlers[Tue, 26 Feb 2013 19:22:20 +0000] INFO: Report handlers complete[Tue, 26 Feb 2013 19:22:20 +0000] DEBUG: Exiting

stack_stateDisplays the current stack configuration JSON.

opsworks-agent-cli stack_state

The following output example is from a PHP App Server instance.

[ec2-user@php-app1 ~]$ sudo opsworks-agent-cli stack_state{ "layers": { "php-app": { "instances": { "php-app2": { "availability_zone": "us-east-1a", "instance_type": "c1.medium", "backends": 8, "booted_at": "2013-02-26T19:05:33+00:00", "status": "online", "ip": "10.243.25.193", "region": "us-east-1", "public_dns_name": "ec2-10-243-25-193.compute-1.amazonaws.com", "private_ip": "domU-12-31-39-0C-84-11.compute-1.internal", "elastic_ip": null, "created_at": "2013-02-26T19:03:43+00:00", "aws_instance_id": "i-005fc873", "private_dns_name": "domU-12-31-39-0C-84-11.compute-1.internal" }, "php-app1": { "availability_zone": "us-east-1a", "instance_type": "c1.medium", "backends": 8, "booted_at": "2013-02-26T19:05:36+00:00", "status": "online", "ip": "10.236.200.220", "region": "us-east-1", "public_dns_name": "ec2-10-236-200-220.compute-1.amazonaws.com", "private_ip": "domU-12-31-39-01-96-8A.compute-1.internal", "elastic_ip": null, "created_at": "2013-02-26T19:03:38+00:00", "aws_instance_id": "i-065fc875", "private_dns_name": "domU-12-31-39-01-96-8A.compute-1.internal" } }, "id": "0539f6b4-9080-4fc9-a7ae-1c4514f074d2", "name": "PHP Application Server" }, "lb": {

API Version 2013-02-18184

AWS OpsWorks User Guidestack_state

Page 191: Opsworks amazon

"instances": { "lb1": { "availability_zone": "us-east-1a", "instance_type": "c1.medium", "backends": 8, "booted_at": "2013-02-26T19:06:03+00:00", "status": "online", "ip": "10.22.247.194", "region": "us-east-1", "public_dns_name": "ec2-10-22-247-194.compute-1.amazonaws.com", "private_ip": "domU-12-31-39-09-08-A8.compute-1.internal", "elastic_ip": null, "created_at": "2013-02-26T19:03:50+00:00", "aws_instance_id": "i-465dca35", "private_dns_name": "domU-12-31-39-09-08-A8.compute-1.internal" } }, "id": "a20986c1-c9d5-45f0-a565-bb43ddd34150", "name": "Load Balancer" } }, "last_command": { "sent_at": 1361906473, "activity": "deploy" }, "instance": { "availability_zone": "us-east-1a", "backends": 8, "instance_type": "c1.medium", "ip": "10-456-789-012", "id": "1a78dd65-a365-4f54-9027-8b6234ee65d4", "region": "us-east-1", "public_dns_name": "ec2-10-456-789-012.compute-1.amazonaws.com", "private_ip": "domU-12-31-39-01-96-8A.compute-1.internal", "layers": [ "php-app" ], "architecture": "i386", "hostname": "php-app1", "aws_instance_id": "i-065fc875", "private_dns_name": "domU-12-31-39-01-96-8A.compute-1.internal" }, "stack": { "name": "MyStack" }, "agent": { "valid_activities": [ "reboot", "stop", "setup", "configure", "update_dependencies", "install_dependencies", "update_custom_cookbooks", "execute_recipes" ] }, "applications": [

API Version 2013-02-18185

AWS OpsWorks User Guidestack_state

Page 192: Opsworks amazon

{ "slug_name": "simplephpapp", "name": "SimplePHPApp", "application_type": "php" } ]}

API Version 2013-02-18186

AWS OpsWorks User Guidestack_state

Page 193: Opsworks amazon

Appendix C: SDKs and CommandLine Tools

In addition to the AWS Management Console and the AWS OpsWorks HTTP API, you can also accessAWS OpsWorks from the following:

• AWS Command Line Interface (AWS CLI)

• AWS SDKs

• AWS Tools for PowerShell

AWS Command Line InterfaceAWS OpsWorks is supported by the AWS Command Line Interface (AWS CLI). The AWS CLI providesa uniform command-line syntax for accessing AWS services. The AWS CLI uses a single setup processto enable access for all supported services. For more information about the AWS CLI and installationinstructions, go to the AWS Command Line Interface User Guide.

AWS SDKsAmazon Web Services provides SDKs that enable you to access AWS OpsWorks from several differentprogramming languages. The SDK libraries automatically take care of tasks such as:

• Cryptographically signing your service requests

• Retrying requests

• Handling error responses

The links below take you to the setup instructions and reference documentation for each SDK that supportsAWS OpsWorks.

• AWS SDK for Java

• Install

• Documentation

• AWS SDK for .NET

API Version 2013-02-18187

AWS OpsWorks User GuideAWS Command Line Interface

Page 194: Opsworks amazon

• Install

• Documentation

• AWS SDK for PHP 2

• Install

• Documentation

• AWS SDK for Ruby

• Install

• Documentation

• AWS SDK for Node.js

• Install

• Documentation

AWS Tools for PowerShellFor Windows users that work in the Windows PowerShell environment, the AWS Tools for PowerShellsupport AWS OpsWorks. The AWS Tools for PowerShell are a set of Windows PowerShell cmdlets thatare packaged as a PowerShell module. The cmdlets expose the functionality of the AWS SDK for .NETin the PowerShell environment. For more information, go to the AWS Tools for PowerShell User Guide.

API Version 2013-02-18188

AWS OpsWorks User GuideAWS Tools for PowerShell

Page 195: Opsworks amazon

Appendix D: AWS OpsWorksAttribute Reference

AWS OpsWorks exposes a wide variety of settings to recipes as Chef attributes.

These settings derive from two sources:

• The stack configuration and deployment JSON that are sent to instances for each lifecycle event.

• The built-in cookbooks' attributes.

Each attribute is assigned a value, which can be any of the following:

• String–For JSON attributes, string values must be contained in double quotes. Cookbook attributesfollow standard Ruby syntax so strings can use single or double quotes, although strings containingcertain special characters must be double-quoted. For more information, see Ruby.

• Boolean–These values are either true or false (no quotes).

• Number–These values are either integer or decimal numbers, such as 4 or 2.5 (no quotes).

• List–These values contain a list of comma-separated values enclosed in square brackets (no quotes),such as [ '80', '443' ]

• JSON object–A JSON attribute can be assigned a JSON object that contains one or more attributes,such as "php-app2": {"elastic_ip": null,...}.

Your custom recipes can access attribute values by using the standard Chefnode[:attribute][:child_attribute][:...] syntax. For example, the following represents anactivity, such as deploy or configure, that has occurred on an instance.

node[:opsworks][:activity]

You can also use quotes rather than colons, as follows:

node["opsworks"]["activity"]

You can override these settings by using custom JSON or custom attributes, as described in CustomizingAWS OpsWorks Configuration by Overriding Attributes (p. 198). However, you should be aware that

API Version 2013-02-18189

AWS OpsWorks User Guide

Page 196: Opsworks amazon

overriding some settings, such as the attributes in the opsworks namespace, might interfere with thecorrect operation of built-in recipes.

For more discussion of stack configuration JSON and recipes, see Stack Configuration and DeploymentJSON (p. 198).

This appendix is a reference for the commonly used AWS OpsWorks attributes.

Stack Configuration and Deployment JSONAttributes

When AWS OpsWorks runs an activity on an instance—for example, a setup activity after an instanceboots or a deploy activity in response to a deployment—it installs a JSON object on the instance thatdescribes the stack's current configuration. For deployments, the object includes additionaldeployment-related attributes.Your custom recipes can access these JSON values by using standardChef node[:attribute][:sub_attribute][:...] syntax.

This section includes the most commonly used stack configuration and deployment JSON attributes andtheir associated node syntax. Note that the same attribute names are sometimes used for differentpurposes, and occur in different namespaces. For example, id can refer to a stack ID, a layer ID, an appID, and so on, so you need the fully qualified name to use the attribute value. For that reason, this attributereference is organized around the stack configuration namespace structure. For examples of stack anddeployment configuration JSON, see Stack Configuration and Deployment JSON (p. 198).

The following are general guidelines for using stack configuration and deployment JSON attributes:

• Some attributes, such as the ones that define layer configurations, are common to the stack as a whole.

These attributes and their values are the same for JSON associated with any activity, and change onlywhen the stack configuration changes.

• Some attributes depend on the instance.

For example, the instance_id value is specific to a particular instance.

• Some of the attributes depend on the activity.

For example, deployment-related attributes are included only for deploy activities.

• Layers and instances are referred to by their short names, such as "lb" and "lb1". Apps are referredto by their slug names, which is a short name such as "simplephp" that is generated by AWSOpsWorks from the user-defined name.

• Most attributes use AWS OpsWorks-defined names that are the same for all JSON objects.

Some attributes, such as custom layer names and app names, use user-defined names.

• Attributes aren't always listed in the same order.

Topics

• opsworks Attributes (p. 191)

• opsworks_custom_cookbooks Attributes (p. 197)

• dependencies Attributes (p. 198)

• ganglia Attributes (p. 198)

• mysql Attributes (p. 198)

• passenger Attributes (p. 199)

• opsworks_bundler Attributes (p. 199)

API Version 2013-02-18190

AWS OpsWorks User GuideStack Configuration and Deployment JSON Attributes

Page 197: Opsworks amazon

• deploy Attributes (p. 199)

• Other Top-Level Attributes (p. 203)

opsworks AttributesThe opsworks element—sometimes referred to as the opsworks namespace—contains a set of attributesthat define the basic stack configuration.

ImportantOverriding the attribute values in the opsworks namespace is not recommended. Doing so cancause the built-in recipes to fail.

Topics

• applications Attributes (p. 191)

• instance Attributes (p. 191)

• layers Attributes (p. 193)

• rails_stack Attributes (p. 196)

• Other Top-level opsworks Attributes (p. 196)

applications AttributesA list of app attributes, one for each app that exists for the stack.

node[:opsworks][:applications]

Each attribute's value is an object that contains the following attributes:

application_typeThe application's type (string). Possible values are as follows:

• "php": PHP app

• "rails": A Ruby on Rails app

• "node": A JavaScript app

• "web": A static HTML page

• "other": All other application types

nameThe user-defined app name, such as "SimplePHP" (string).

slug_nameA short name , which is an all-lowercase name such as "simplephp" that is generated by OpsWorksfrom the app's name (string).

instance AttributesThe instance attribute contains a set of attributes that specify the configuration of this instance.

backends (p. 198)availability_zone (p. 198)architecture (p. 198)

id (p. 198)hostname (p. 198)aws_instance_id (p. 198)

layers (p. 198)ip (p. 198)instance_type (p. 198)

public_dns_name (p. 198)private_ip (p. 198)private_dns_name (p. 198)

API Version 2013-02-18191

AWS OpsWorks User Guideopsworks Attributes

Page 198: Opsworks amazon

region (p. 198)

architectureThe instance's architecture, such as "i386" (string).

node[:opsworks][:instance][:architecture]

availability_zoneThe instance's availability zone, such as "us-east-1a" (string).

node[:opsworks][:instance][:availability_zone]

backendsThe number of backend web processes (string). It determines, for example, the number of concurrentconnections that HAProxy will forward to a Rails back end.The default value depends on the instance'smemory and number of cores.

node[:opsworks][:instance][:backends]

aws_instance_idThe EC2 instance ID (string).

node[:opsworks][:instance][:aws_instance_id]

hostnameThe hostname, such as "php-app1" (string).

node[:opsworks][:instance][:hostname]

idThe instance ID, which is an AWS OpsWorks-generated GUID that uniquely identifies the instance(string).

node[:opsworks][:instance][:id]

instance_typeThe instance type, such as "c1.medium" (string).

node[:opsworks][:instance][:instance_type]

ipThe public IP address (string).

node[:opsworks][:instance][:ip]

layersA list of the instance's layers, which are identified by their short names, such as "lb" or "db-master"(List of String).

API Version 2013-02-18192

AWS OpsWorks User Guideopsworks Attributes

Page 199: Opsworks amazon

node[:opsworks][:instance][:layers]

private_dns_nameThe private DNS name (string).

node[:opsworks][:instance][:private_dns_name]

private_ipThe private IP address (string).

node[:opsworks][:instance][:private_ip]

public_dns_nameThe public DNS name (string).

node[:opsworks][:instance][:public_dns_name]

regionThe AWS region, such as "us-east-1" (string).

node[:opsworks][:instance][:region]

layers AttributesThe layers attribute contains a set of layer attributes, one for each of the stack's layers, which are namedwith the layer's short name, such as php-app. A stack can have at most one each of the built-in layers,whose short names are as follows:

• lb: HAProxy layer

• db-master: MySQL layer

• nodejs-app: Node.js App Server layer

• php-app: PHP App Server layer

• rails-app: Rails App Server layer

• web: Static Web Server layer

• monitoring-master: Ganglia layer

• memcached: Memcached layer

A stack can contain any number of custom layers, which have user-defined short names.

Each layer attribute contains the following attributes:

• id (p. 193)

• instances (p. 194)

• name (p. 196)

idThe layer ID, which is a GUID that is generated by OpsWorks and uniquely identifies the layer (string).

API Version 2013-02-18193

AWS OpsWorks User Guideopsworks Attributes

Page 200: Opsworks amazon

node[:opsworks][:layers][:layershortname][:id]

instancesThe instances element contains a set of instance attributes, one for each of the layer's onlineinstances.They are named with the instance's short name, such as php-app1. Each instance elementcontains the following attributes:

backends (p. 198)aws_instance_id (p. 198)availability_zone (p. 198)

elastic_ip (p. 198)created_at (p. 198)booted_at (p. 198)

private_ip (p. 198)ip (p. 198)instance_type (p. 198)

region (p. 198)private_dns_name (p. 198)public_dns_name (p. 198)

status (p. 198)

availability_zoneThe Availability Zone, such as "us-east-1a" (string).

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:availability_zone]

aws_instance_idThe EC2 instance ID (string).

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:ws_instance_id]

backendsThe number of backend web processes (number). It determines, for example, the number ofconcurrent connections that HAProxy will forward to a Rails back end.The default value dependson the instance's memory and number of cores.

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:backends]

booted_atThe time that the EC2 instance was booted, using a yyyy-mm-ddd-hh-mm-ss format (string).For example, "2013-02-05T10:31:55" corresponds to 10:31:55 on Tuesday Feb 5, 2013.

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:booted_at]

created_atThe time that the EC2 instance was created, using a yyyy-mm-ddd-hh-mm-ss format (string).For example, "2013-02-05T10:31:55" corresponds to 10:31:55 on Tuesday Feb 5, 2013.

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:created_at]

API Version 2013-02-18194

AWS OpsWorks User Guideopsworks Attributes

Page 201: Opsworks amazon

elastic_ipThe Elastic IP address, which is set to null if the instance does not have one (string).

node[:opsworks][:layers][:layershortname][:instances][:Instance Name][:elastic_ip]

instance_typeThe instance type, such as "c1.medium" (string).

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:instance_type]

ipThe public IP address (string).

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:ip]

private_ipThe private IP address (string).

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:private_ip]

public_dns_nameThe public DNS name (string).

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:public_dns_name]

private_dns_nameThe private DNS name (string).

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:private_dns_name]

regionThe AWS region, such as "us-east-1" (string).

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:region]

statusThe status (string). Possible values are as follows:

• "requested"

• "booting"

• "running_setup"

• "online"

• "setup_failed"

• "start_failed"

API Version 2013-02-18195

AWS OpsWorks User Guideopsworks Attributes

Page 202: Opsworks amazon

• "terminating"

• "terminated"

• "stopped"

• "connection_lost"

node[:opsworks][:layers][:layershortname][:instances][:instanceshort name][:status]

nameThe layer's name, which is used to represent the layer in the console (string). It can be user-definedand is not necessarily unique.

node[:opsworks][:layers][:layershortname][:name]

rails_stack Attributesname

Specifies the rails stack, and is set to "apache_passenger" or "nginx_unicorn " (string).

node[:opsworks][:rails_stack][:name]

recipeThe associated recipe, which depends on whether you are using Passenger or Unicorn (string):

• Unicorn: "unicorn::rails"

• Passenger: "passenger_apache2::rails"

node[:opsworks][:rails_stack][:recipe]

restart_commandThe restart command, which depends on whether you are using Passenger or Unicorn (string):

• Unicorn: "../../shared/scripts/unicorn clean-restart"

• Passenger: "touch tmp/restart.txt"

serviceThe service name, which depends on whether you are using Passenger or Unicorn (string):

• Unicorn: "unicorn"

• Passenger: "apache2"

node[:opsworks][:rails_stack][:service]

Other Top-level opsworks AttributesThis section contains the opsworks attributes that do not have child attributes.

activityThe activity that is associated with the JSON object (string).

node[:opsworks][:activity]

API Version 2013-02-18196

AWS OpsWorks User Guideopsworks Attributes

Page 203: Opsworks amazon

agent_version AttributesThe version of the instance's OpsWorks agent (string).

node[:opsworks][:agent_version]

ruby_stack AttributesThe Ruby stack, such as "ruby_enterprise" (string).

node[:opsworks][:ruby_stack]

ruby_version AttributesThe Ruby version number (string).

node[:opsworks][:ruby_version]

sent_at AttributesWhen this command was sent to the instance (number).

node[:opsworks][:sent_at]

stack AttributesContains a name element that is set to the user-defined stack name (string).

node[:opsworks][:stack][:name]

deploymentIf this JSON is associated with a deploy activity, deployment is set to the deployment ID, an AWSOpsWorks-generated GUID that uniquely identifies the deployment (string). Otherwise the attributeis set to null.

node[:opsworks][:deployment]

opsworks_custom_cookbooks AttributesContains elements that specify the stack's custom cookbooks.

enabledWhether custom cookbooks are enabled (Boolean).

node[:opsworks_custom_cookbooks][:enabled]

recipesA list of the recipes that are to be executed for this command, including custom recipes, using thecookbookname::recipename format (List of String).

node[:opsworks_custom_cookbooks][:recipes]

API Version 2013-02-18197

AWS OpsWorks User Guideopsworks_custom_cookbooks Attributes

Page 204: Opsworks amazon

dependencies AttributesContains several attributes that are related to the update_dependencies stack command (p. 58).

upgrade_gemsWhether to upgrade Gems (Boolean).

gem_binaryThe location of the Gems binary (string).

upgrade_debsWhether to upgrade Debs packages (Boolean).

update_debsWhether to update Debs packages (Boolean).

ganglia AttributesContains a web attribute that contains several attributes that how to access the Ganglia statistics webpage:

passwordThe password required to access the statistics page (string).

node[:ganglia][:web][:password]

urlThe statistics page's URL path, such as "/ganglia" (string). The complete URL ishttp://DNSNameURLPath, where is the associated instance's DNS name.

node[:ganglia][:web][:url]

userThe user name required to access the statistics page (string).

node[:ganglia][:web][:user]

mysql AttributesContains a set of attributes that specify the MySQL database server configuration.

clientsA list of client IP addresses (List of String).

node[:mysql][:clients]

server_root_passwordThe root password (string).

node[:mysql][:server_root_password]

API Version 2013-02-18198

AWS OpsWorks User Guidedependencies Attributes

Page 205: Opsworks amazon

passenger AttributesContains a set of attributes that specify the Phusion Passenger configuration.

gem_binThe location of the RubyGems binaries, such as "/usr/local/bin/gem" (string).

node[:passenger][:gem_bin]

max_pool_sizeThe maximum pool size (number).

node[:passenger][:max_pool_size]

ruby_binThe location of the Ruby binaries, such as "/usr/local/bin/ruby".

node[:passenger][:ruby_bin]

versionThe Passenger version (string).

node[:passenger][:version]

opsworks_bundler AttributesContains elements that specify Bundler support.

manage_packageWhether to install and manage Bundler (Boolean).

node[:opsworks_bundler][:manage_package]

versionThe bundler version (string).

node[:opsworks_bundler][:version]

deploy AttributesIf the JSON is associated with a deploy activity, the deploy attribute contains one or attributes, one foreach app that was deployed, named by the app's slug name. Each of these attributes contains the followingattributes:

auto_bundle_on_deploy (p. 198)application_type (p. 198)application (p. 198)

domains (p. 198)deploy_to (p. 198)database (p. 198)

migrate (p. 198)memcached (p. 198)document_root (p. 198)

API Version 2013-02-18199

AWS OpsWorks User Guidepassenger Attributes

Page 206: Opsworks amazon

restart_command (p. 198)rails_env (p. 198)mounted_at (p. 198)

ssl_certificate_ca (p. 198)ssl_certificate (p. 198)scm (p. 198)

stack (p. 198)ssl_support (p. 198)ssl_key (p. 198)

symlinks (p. 198)symlink_before_migrate (p. 198)

applicationThe app's slug name, such as "simplephp" (string).

node[:deploy][:appslugname][:application]

application_typeThe app type (string). Possible values are as follows:

• "php": A PHP app

• "rails": A Ruby on Rails app

• "node": A Node.js app

• "web": A static HTML page

• "other": All other application types

node[:deploy][:appslugname][:application_type]

auto_bundle_on_deployFor Rails applications, whether to execute bundler during the deployment (Boolean).

node[:deploy][:appslugname][:auto_bundle_on_deploy]

databaseIf the stack includes a database, contains attributes with the information required to connect todatabase.

databaseThe database name, which is usually the app's slug name, such as "simplephp" (string).

node[:deploy][:appslugname][:database][:database]

hostThe database host's IP address (string).

node[:deploy][:appslugname][:database][:host]

passwordThe database password (string).

node[:deploy][:appslugname][:database][:password]

reconnectFor Rails applications, whether the application should reconnect if the connection no longerexists (Boolean).

API Version 2013-02-18200

AWS OpsWorks User Guidedeploy Attributes

Page 207: Opsworks amazon

node[:deploy][:appslugname][:database][:reconnect]

usernameThe user name (string).

node[:deploy][:appslugname][:database][:username]

deploy_toWhere the app is to be deployed to, such as "/srv/www/simplephp" (string).

node[:deploy][:appslugname][:deploy_to]

domainsA list of the app's domains (List of String).

node[:deploy][:appslugname][:domains]

document_rootThe document root, if you specify a nondefault root, or null if you use the default root (string).

node[:deploy][:appslugname][:document_root]

memcachedContains two attributes that define the memcached configuration.

hostThe Memcached server instance's IP address (string).

node[:deploy][:appslugname][:memcached][:host]

portThe port that the memcached server is listening on (number).

node[:deploy][:appslugname][:memcached][:port]

migrateFor Rails applications, whether to run migrations (Boolean).

node[:deploy][:appslugname][:migrate]

mounted_atThe app's mount point, if you specify a nondefault mount point, or null if you use the default mountpoint (string).

node[:deploy][:appslugname][:mounted_at]

rails_envFor Rails App Server instances, the rails environment, such as "production" (string).

node[:deploy][:appslugname][:rails_env]

API Version 2013-02-18201

AWS OpsWorks User Guidedeploy Attributes

Page 208: Opsworks amazon

restart_commandA command to be run when the app is restarted, such as "echo 'restarting app'".

node[:deploy][:appslugname][:restart_command]

scmContains a set of attributes that specify the information that OpsWorks uses to deploy the app fromits source control repository. The attributes vary depending on the repository type.

passwordThe password, for private repositories, and null for public repositories (string). For private AmazonS3 buckets, the attribute is set to the secret key.

node[:deploy][:appslugname][:scm][:password]

repositoryThe repository URL, such as"git://github.com/amazonwebservices/opsworks-demo-php-simple-app.git"(string).

node[:deploy][:appslugname][:scm][:repository]

revisionIf the repository has multiple branches, the attribute specifies the app's branch or version, suchas "version1" (string). Otherwise it is set to null.

node[:deploy][:appslugname][:scm][:revision]

scm_typeThe repository type (string). Possible values are as follows:

• "git": A Git repository

• "svn": A Subversion repository

• "s3": An Amazon S3 bucket

• "archive": An HTTP archive

• "other": Another repository type

node[:deploy][:appslugname][:scm][:scm_type]

ssh_keyA deploy SSH key (p. 115), for accessing private Git repositories, and null for public repositories(string).

node[:deploy][:appslugname][:scm][:ssh_key]

userThe user name, for private repositories, and null for public repositories (string). For privateAmazon S3 buckets, the attribute is set to the access key.

node[:deploy][:appslugname][:scm][:user]

API Version 2013-02-18202

AWS OpsWorks User Guidedeploy Attributes

Page 209: Opsworks amazon

ssl_certificateThe app's SSL certificate, if you enabled SSL support, or null otherwise (string).

node[:deploy][:appslugname][:ssl_certificate]

ssl_certificate_caIf SSL is enabled, this attribute can be used to specify an intermediate certificate authority key orclient authentication (string).

node[:deploy][:appslugname][:ssl_certificate_ca]

ssl_keyThe app's SSL private key, if you enabled SSL support, or null otherwise (string).

node[:deploy][:appslugname][:ssl_key]

ssl_supportWhether SSL is supported (Boolean).

node[:deploy][:appslugname][:ssl_support]

stackContains one Boolean attribute, needs_reload, that specifies whether to reload the app serverduring deployment.

node[:deploy][:appslugname][:stack][:needs_reload]

symlink_before_migrateFor Rails apps, contains symlinks that are to be created before running migrations as"link":"target" pairs.

node[:deploy][:appslugname][:symlink_before_migrate]

symlinksContains the deployment's symlinks as "link":"target" pairs.

node[:deploy][:appslugname][:symlinks]

Other Top-Level AttributesThis section contains top-level stack configuration attributes that do not have child attributes.

rails AttributesContains a max_pool_size attribute that specifies the server's maximum pool size (number).

node[:rails][:max_pool_size]

recipes AttributesA list of the built-in recipes that were run by this activity, using the "cookbookname::recipename"format (List of String).

API Version 2013-02-18203

AWS OpsWorks User GuideOther Top-Level Attributes

Page 210: Opsworks amazon

node[:recipes]

opsworks_rubygems AttributesContains a version element that specifies the RubyGems version (string).

node[:opsworks_rubygems][:version]

languages AttributesContains an attribute for each installed language, named for the language, such as ruby.The attributeis an object that contains an attribute, such as ruby_bin, that specifies the installation folder, suchas "/usr/bin/ruby" (string).

ssh_users AttributesContains a set of attributes, each of which describes one of the IAM users that have been grantedSSH permissions. Each attribute is named with a user's Unix ID. AWS OpsWorks generates a uniqueID for each user in the 2000 range, such as "2001", and creates a user with that ID on every instance.Each attribute contains the following attributes:

emailThe IAM user's e-mail address (string).

node[:ssh_users][:UnixID][:email]

public_keyThe IAM user's public SSH key (string).

node[:ssh_users][:UnixID][:public_key]

sudoerWhether the IAM user has sudo permissions (Boolean).

node[:ssh_users][:UnixID][:sudoer]

nameThe IAM user name (string).

node[:ssh_users][:UnixID][:sudoer]

Built-in Recipe AttributesMost of the built-in recipes have one or more attributes files (p. 124) that define various settings.You canaccess these settings in your custom recipes, and override them by using custom JSON.You typicallyneed to access or override attributes that control the configuration of the various server technologies thatare supported by AWS OpsWorks. This section summarizes those attributes. The complete attributesfiles, and the associated recipes and templates, are available athttps://github.com/aws/opsworks-cookbooks.git.

NoteAll built-in recipe attributes are default type.

API Version 2013-02-18204

AWS OpsWorks User GuideBuilt-in Recipe Attributes

Page 211: Opsworks amazon

apache2 AttributesThe apache2 attributes specify the Apache HTTP server configuration. For more information, see ApacheCore Features.

dir (p. 198)contact (p. 198)binary (p. 198)

hide_info_headers (p. 198)group (p. 198)document_root (p. 198)

keepalive (p. 198)init_script (p. 198)icondir (p. 198)

lib_dir (p. 198)keepalivetimeout (p. 198)keepaliverequests (p. 198)

log_dir (p. 198)listen_ports (p. 198)libexecdir (p. 198)

prefork Attributes (p. 198)pid_file (p. 198)logrotate Attributes (p. 198)

timeout (p. 198)servertokens (p. 198)serversignature (p. 198)

worker Attributes (p. 198)user (p. 198)traceenable (p. 198)

binaryThe location of the Apache binary (string). The default value is '/usr/sbin/httpd'.

node[:apache][:binary]

contactAn e-mail contact (string). The default value is a dummy address, '[email protected]'.

node[:apache][:contact]

dirThe server's root directory (string). The default values are as follows:

• Amazon Linux: '/etc/httpd'

• Ubuntu: '/etc/apache2'

node[:apache][:dir]

document_rootThe document root (string). The default values are as follows:

• Amazon Linux: '/var/www/html'

• Ubuntu: '/var/www'

node[:apache][:document_root]

groupThe group name (string). The default values are as follows:

• Amazon Linux: 'apache'

• Ubuntu: 'www-data'

node[:apache][:group]

API Version 2013-02-18205

AWS OpsWorks User Guideapache2 Attributes

Page 212: Opsworks amazon

hide_info_headersWhether to omit version and module information from HTTP headers ('true'/'false') (string).The default value is 'true'.

node[:apache][:hide_info_headers]

icondirThe icon directory (string). The defaults value are as follows:

• Amazon Linux: '/var/www/icons/'

• Ubuntu: '/usr/share/apache2/icons'

node[:apache][:icondir]

init_scriptThe initialization script (string). The default values are as follows:

• Amazon Linux: '/etc/init.d/httpd'

• Ubuntu: '/etc/init.d/apache2'

node[:apache][:init_script]

keepaliveWhether to enable keep-alive connections (string).The possible values are 'On' and 'Off' (string).The default value is 'Off'.

node[:apache][:keepalive]

keepaliverequestsThe maximum number of keep-alive requests that Apache will handle at the same time (number).The default value is 100.

node[:apache][:keepaliverequests]

keepalivetimeoutThe time that Apache waits for a request before closing the connection (number). The default valueis 3.

node[:apache][:keepalivetimeout]

lib_dirThe directory that contains the object code libraries (string). The default values are as follows:

• Amazon Linux (x86): '/usr/lib/httpd'

• Amazon Linux (x64): '/usr/lib64/httpd'

• Ubuntu: '/usr/lib/apache2'

node[:apache][:lib_dir]

libexecdirThe directory that contains the program executables (string). The default values are as follows:

• Amazon Linux (x86): '/usr/lib/httpd/modules'

• Amazon Linux (x64): '/usr/lib64/httpd/modules'

API Version 2013-02-18206

AWS OpsWorks User Guideapache2 Attributes

Page 213: Opsworks amazon

• Ubuntu: '/usr/lib/apache2/modules'

node[:apache][:libexecdir]

listen_portsA list of ports that the server listens to (List of String). The default value is [ '80','443' ].

node[:apache][:listen_ports]

log_dirThe log directory (string). The default values are as follows:

• Amazon: '/var/log/httpd'

• Ubuntu: '/var/log/apache2'

node[:apache][:log_dir]

logrotate AttributesThese attributes specify how to rotate the log files.

delaycompressWhether to delay compressing a closed log file until the start of the next rotation cycle('true'/'false') (string). The default value is 'true'.

node[:apache][:logrotate][:delaycompress]

groupThe log files' group (string). The default value is 'adm'.

node[:apache][:logrotate][:group]

modeThe log files' mode (string). The default value is '640'.

node[:apache][:logrotate][:mode]

ownerThe log files' owner (string). The default value is 'root'.

node[:apache][:logrotate][:owner]

rotateThe number of rotation cycles before a closed log file is removed (string). The default value is'30'.

node[:apache][:logrotate][:rotate]

scheduleThe rotation schedule (string). Possible values are as follows:

• 'daily'

• 'weekly'

• 'monthly'

API Version 2013-02-18207

AWS OpsWorks User Guideapache2 Attributes

Page 214: Opsworks amazon

The default value is 'daily'.

node[:apache][:logrotate][:schedule]

pid_fileThe file that contains the daemon's process ID (string). The default values are as follows:

• Amazon (Linux version 6 or later): '/var/run/httpd/httpd.pid'

• Amazon (Linux version 5 or earlier): '/var/run/httpd.pid'

• Ubuntu: '/var/run/apache2.pid'

node[:apache][:pid_file]

prefork AttributesThese attributes specify the pre-forking configuration.

maxclientsThe maximum number of simultaneous requests that will be served (number). The default valueis 400.

node[:apache][:prefork][:maxclients]

maxrequestsperchildThe maximum number of requests that a child server process will handle (number). The defaultvalue is 10000.

node[:apache][:prefork][:maxrequestsperchild]

maxspareserversThe maximum number of idle child server processes (number). The default value is 32.

node[:apache][:prefork][:maxspareservers]

minspareserversThe minimum number of idle child server processes (number). The default value is 16.

node[:apache][:prefork][:minspareservers]

serverlimitThe maximum number of processes that can be configured (number). The default value is 400.

node[:apache][:prefork][:serverlimit]

startserversThe number of child server processes to be created at startup (number). The default value is16.

node[:apache][:prefork][:startservers]

serversignatureSpecifys whether and how to configure a trailing footer for server-generated documents (string). Thepossible values are 'On', 'Off', and 'Email'). The default value is 'Off'.

API Version 2013-02-18208

AWS OpsWorks User Guideapache2 Attributes

Page 215: Opsworks amazon

node[:apache][:serversignature]

servertokensSpecifies what type of server version information is included in the response header (string):

• 'Full': Full information. For example, Server: Apache/2.4.2 (Unix) PHP/4.2.2 MyMod/1.2

• 'Prod': Product name. For example, Server: Apache

• 'Major': Major version. For example, Server: Apache/2

• 'Minor': Major and minor version. For example, Server: Apache/2.4

• 'Min': Minimal version. For example, Server: Apache/2.4.2

• 'OS': Version with operating system. For example, Server: Apache/2.4.2 (Unix)

The default value is 'Prod'.

node[:apache][:servertokens]

timeoutThe amount of time that Apache waits for I/O (number). The default value is 120.

node[:apache][:timeout]

traceenableWhether to enable TRACE requests (string). The possible values are 'On' and 'Off'. The defaultvalue is 'Off'.

node[:apache][:traceenable]

userThe user name (string). The default values are as follows:

• Amazon Linux: 'apache'

• Ubuntu: 'www-data'

node[:apache][:user]

worker AttributesThese attributes specify the worker process configuration.

startserversThe number of child server processes to be created at startup (number). The default value is 4.

node[:apache][:worker][:startservers]

maxclientsThe maximum number of simultaneous requests that will be served (number). The default valueis 1024.

node[:apache][:worker][:maxclients]

maxsparethreadsThe maximum number of idle threads (number). The default value is 192.

API Version 2013-02-18209

AWS OpsWorks User Guideapache2 Attributes

Page 216: Opsworks amazon

node[:apache][:worker][:maxsparethreads]

minsparethreadsThe minimum number of idle threads (number). The default value is 64.

node[:apache][:worker][:minsparethreads]

threadsperchildThe number of threads per child process (number). The default value is 64.

node[:apache][:worker][:threadsperchild]

maxrequestsperchildThe maximum number of requests that a child server process will handle (number). The defaultvalue is 10000.

node[:apache][:worker][:maxrequestsperchild]

haproxy AttributesThe haproxy attributes specify the HAProxy server configuration. For more information, see HAProxyDocs.

connect_timeout (p. 198)client_timeout (p. 198)check_interval (p. 198)

health_check_method (p. 198)global_max_connections (p.198)default_max_connections (p.198)

http_request_timeout (p. 198)queue_timeout (p. 198)health_check_url (p. 198)

maxcon_factor_php_app (p. 198)maxcon_factor_nodejs_app_ssl(p. 198)

maxcon_factor_nodejs_app(p. 198)

maxcon_factor_rails_app_ssl(p. 198)

maxcon_factor_rails_app (p.198)maxcon_factor_php_app_ssl(p. 198)

retries (p. 198)maxcon_factor_static_ssl (p.198)maxcon_factor_static (p. 198)

stats_user (p. 198)stats_url (p. 198)server_timeout (p. 198)

check_intervalThe health check time interval (string). The default value is '10s'.

node[:haproxy][:check_interval]

client_timeoutThe maximum amount of time that a client can be inactive (string). The default value is '60s'.

node[:haproxy][:client_timeout]

API Version 2013-02-18210

AWS OpsWorks User Guidehaproxy Attributes

Page 217: Opsworks amazon

connect_timeoutThe maximum amount of time that HAProxy will wait for a server connection attempt to succeed(string). The default value is '10s'.

node[:haproxy][:connect_timeout]

default_max_connectionsThe default maximum number of connections (string). The default value is '80000'.

node[:haproxy][:default_max_connections]

global_max_connectionsThe maximum number of connections (string). The default value is '80000'.

node[:haproxy][:global_max_connections]

health_check_methodThe health check method (string). The default value is 'OPTIONS'.

node[:haproxy][:health_check_method]

health_check_urlThe URL path that is used to check servers' health (string). The default value is '/'.

node[:haproxy][:health_check_url ]

queue_timeoutThe maximum wait time for a free connection (string). The default value is '120s'.

node[:haproxy][:queue_timeout]

http_request_timeoutThe maximum amount of time that HAProxy will wait for a complete HTTP request (string).The defaultvalue is '30s'.

node[:haproxy][:http_request_timeout]

retriesThe number of retries after server connection failure (string). The default value is '3'.

node[:haproxy][:retries]

server_timeoutThe maximum amount of time that a client can be inactive (string). The default value is '60s'.

node[:haproxy][:server_timeout]

stats_urlThe URL path for the statistics page (string). The default value is '/haproxy?stats'.

API Version 2013-02-18211

AWS OpsWorks User Guidehaproxy Attributes

Page 218: Opsworks amazon

node[:haproxy][:stats_url]

stats_userThe statistics page user name (string). The default value is 'opsworks'.

node[:haproxy][:stats_user]

The maxcon attributes represent a load factor multiplier that is used to compute the maximum numberof connections that HAProxy allows for backends (p. 192). For example, suppose you have a Rails appserver on a small instance with a backend value of 4, which means that AWS OpsWorks will configurefour Rails processes for that instance. If you use the default maxcon_factor_rails_app value of 7,HAProxy will handle 28 (4*7) connections to the Rails server.

maxcon_factor_nodejs_appThe maxcon factor for a Node.js app server (number). The default value is 10.

node[:haproxy][:maxcon_factor_nodejs_app]

maxcon_factor_nodejs_app_sslThe maxcon factor for a Node.js app server with SSL (number). The default value is 10.

node[:haproxy][:maxcon_factor_nodejs_app_ssl]

maxcon_factor_php_appThe maxcon factor for a PHP app server (number). The default value is 10.

node[:haproxy][:maxcon_factor_php_app]

maxcon_factor_php_app_sslThe maxcon factor for a PHP app server with SSL (number). The default value is 10.

node[:haproxy][:maxcon_factor_php_app_ssl]

maxcon_factor_rails_appThe maxcon factor for a Rails app server (number). The default value is 7.

node[:haproxy][:maxcon_factor_rails_app]

maxcon_factor_rails_app_sslThe maxcon factor for a Rails app server with SSL (number). The default value is 7.

node[:haproxy][:maxcon_factor_rails_app_ssl]

maxcon_factor_staticThe maxcon factor for a static web server (number). The default value is 15.

node[:haproxy][:maxcon_factor_static]

API Version 2013-02-18212

AWS OpsWorks User Guidehaproxy Attributes

Page 219: Opsworks amazon

maxcon_factor_static_sslThe maxcon factor for a static web server with SSL (number). The default value is 15.

node[:haproxy][:maxcon_factor_static_ssl]

memached AttributesThe memached attributes specify the Memcached server configuration.

pid_file (p. 198)max_connections (p. 198)memory (p. 198)

stop_command (p. 198)start_command (p. 198)port (p. 198)

user (p. 198)

memoryThe maximum memory to use, in MB (number). The default value is 512.

node[:memcached][:memory]

max_connectionsThe maximum number of connections (string). The default value is '4096'.

node[:memcached][:max_connections]

pid_fileThe file that contains the daemon's process ID (string). The default value is'var/run/memcached.pid'.

node[:memcached][:pid_file]

portThe port to listen on (number). The default value is 11211.

node[:memcached][:port]

start_commandThe start command (string). The default value is '/etc/init.d/memcached start'.

node[:memcached][:start_command]

stop_commandThe stop command (string). The default value is '/etc/init.d/memcached stop'.

node[:memcached][:stop_command]

userThe user (string). The default value is 'nobody'.

API Version 2013-02-18213

AWS OpsWorks User Guidememached Attributes

Page 220: Opsworks amazon

node[:memcached][:user]

mysql AttributesThe mysql attributes specify the MySQL master configuration. For more information, see Server SystemVariables.

clients (p. 198)bind_address (p. 198)basedir (p. 198)

datadir (p. 198)confd_dir (p. 198)conf_dir (p. 198)

mysqladmin_bin (p. 198)mysql_bin (p. 198)grants_path (p. 198)

root_group (p. 198)port (p. 198)pid_file (p. 198)

tunable Attributes (p. 198)socket (p. 198)server_root_password (p. 198)

basedirThe base directory (string). The default value is '/usr'.

node[:mysql][:basedir]

bind_addressThe address that MySQL listens on (string). The default value is '0.0.0.0'.

node[:mysql][:bind_address]

clientsA list of clients (List of String).

node[:mysql][:clients]

conf_dirThe directory that contains the configuration file (string). The default values are as follows:

• Amazon: '/etc'

• Ubuntu: '/etc/mysql'

node[:mysql][:conf_dir]

confd_dirThe directory that contains additional configuration files (string). The default value is'/etc/mysql/conf.d'.

node[:mysql][:confd_dir]

datadirThe data directory (string). The default value is '/var/lib/mysql'.

node[:mysql][:datadir]

API Version 2013-02-18214

AWS OpsWorks User Guidemysql Attributes

Page 221: Opsworks amazon

grants_pathThe grant table location (string). The default value is '/etc/mysql_grants.sql'.

node[:mysql][:grants_path]

mysql_binThe mysql binaries location (string). The default value is '/usr/bin/mysql'.

node[:mysql][:mysql_bin]

mysqladmin_binThe mysqladmin location (string). The default value is '/usr/bin/mysqladmin'.

node[:mysql][:mysqladmin_bin]

pid_fileThe file that contains the daemon's process ID (string). The default value is'/var/run/mysqld/mysqld.pid'.

node[:mysql][:pid_file]

portThe port that the server listens on (number). The default value is 3306.

node[:mysql][:port]

root_groupThe root group (string). The default value is 'root'.

node[:mysql][:]

server_root_passwordThe server's root password (string). The default value is randomly generated.

node[:mysql][:server_root_password]

socketThe location of the socket file (string). The default value is '/var/lib/mysql/mysql.sock'. Thedefault values are as follows:

• Amazon Linux: '/var/lib/mysql/mysql.sock'

• Ubuntu: '/var/run/mysqld/mysqld.sock'

node[:mysql][:socket]

tunable AttributesThe tunable attributes are used for performance tuning.

innodb_buffer_pool_size (p.198)innodb_additional_mem_pool_size(p. 198)

back_log (p. 198)

API Version 2013-02-18215

AWS OpsWorks User Guidemysql Attributes

Page 222: Opsworks amazon

key_buffer (p. 198)innodb_lock_wait_timeout(p. 198)

innodb_flush_log_at_trx_commit(p. 198)

max_allowed_packet (p. 198)long_query_time (p. 198)log_slow_queries (p. 198)

net_read_timeout (p. 198)max_heap_table_size (p. 198)max_connections (p. 198)

query_cache_size (p. 198)query_cache_limit (p. 198)net_write_timeout (p. 198)

thread_stack (p. 198)thread_cache_size (p. 198)query_cache_type (p. 198)

table_cache (p. 198)wait_timeout (p. 198)

back_logThe maximum number of outstanding requests (string). The default value is '128'.

node[:mysql][:tunable][:back_log]

innodb_additional_mem_pool_sizeThe size of the pool that Innodb uses to store internal data structures (string). The default valueis '20M'.

node[:mysql][:tunable][:innodb_additional_mem_pool_size]

innodb_buffer_pool_sizeThe Innodb buffer pool size (string). The default value is '1200M'.

node[:mysql][:tunable][:innodb_buffer_pool_size]

innodb_flush_log_at_trx_commitHow often Innodb flushes the log buffer (string). The default value is '2'. For more information,see innodb_flush_log_at_trx_commit.

node[:mysql][:tunable][:innodb_flush_log_at_trx_commit]

innodb_lock_wait_timeoutThe maximimum amount of time, in seconds, that an Innodb transaction waits for a row lock(string). The default value is '50'.

node[:mysql][:tunable][:innodb_lock_wait_timeout]

key_bufferThe index buffer size (string). The default value is '250M'.

node[:mysql][:tunable][:key_buffer]

log_slow_queriesThe location of the slow-query log file (string). The default value is'/var/log/mysql/mysql-slow.log'.

node[:mysql][:tunable][:log_slow_queries]

API Version 2013-02-18216

AWS OpsWorks User Guidemysql Attributes

Page 223: Opsworks amazon

long_query_timeThe time, in seconds, required to designate a query as a long query (string). The default valueis '1'.

node[:mysql][:tunable][:long_query_time]

max_allowed_packetThe maximum allowed packet size (string). The default value is '32M'.

node[:mysql][:tunable][:max_allowed_packet]

max_connectionsThe maximum number of concurrent client connections (string). The default value is '2048'.

node[:mysql][:tunable][:max_connections]

max_heap_table_sizeThe maximum size of user-created MEMORY tables (string). The default value is '32M'.

node[:mysql][:tunable][:max_heap_table_size]

net_read_timeoutThe amount of time, in seconds, to wait for more data from a connection (string). The defaultvalue is '30'.

node[:mysql][:tunable][:net_read_timeout]

net_write_timeoutThe amount of time, in seconds, to wait for a block to be written to a connection (string). Thedefault value is '30'.

node[:mysql][:tunable][:net_write_timeout]

query_cache_limitThe maximum size of an individual cached query (string). The default value is '2M'.

node[:mysql][:tunable][:query_cache_limit]

query_cache_sizeThe query cache size (string). The default value is '128M'.

node[:mysql][:tunable][:query_cache_size]

query_cache_typeThe query cache type (string). The possible values are as follows:

• '0': No caching or retrieval of cached data.

• '1': Cache statements that don't begin with SELECT SQL_NO_CACHE.

• '2': Cache statements that begin with SELECT SQL_CACHE.

The default value is '1'.

API Version 2013-02-18217

AWS OpsWorks User Guidemysql Attributes

Page 224: Opsworks amazon

node[:mysql][:tunable][:query_cache_type]

thread_cache_sizeThe number of client threads that are cached for re-use (string). The default value is '8'.

node[:mysql][:tunable][:thread_cache_size]

thread_stackThe stack size for each thread (string). The default value is '192K'.

node[:mysql][:tunable][:thread_stack]

wait_timeoutThe amount of time, in seconds, to wait on a noninteractive connection. The default value is'180' (string).

node[:mysql][:tunable][:wait_timeout]

table_cacheThe number of open tables (string). The default value is '2048'.

node[:mysql][:tunable][:table_cache]

nginx AttributesThe nginx attributes specify the Nginx configuration. For more information, see Directive Index.

gzip (p. 198)dir (p. 198)binary (p. 198)

gzip_http_version (p. 198)gzip_disable (p. 198)gzip_comp_level (p. 198)

gzip_types (p. 198)gzip_static (p. 198)gzip_proxied (p. 198)

keepalive_timeout (p. 198)keepalive (p. 198)gzip_vary (p. 198)

server_names_hash_bucket_size (p.198)user (p. 198)log_dir (p. 198)

worker_connections (p. 198)worker_processes (p. 198)

binaryThe location of the Nginx binaries (string). The default value is '/usr/sbin/nginx'.

node[:nginx][:binary]

dirThe location of files such as configuration files (string). The default value is '/etc/nginx'.

node[:nginx][:dir]

API Version 2013-02-18218

AWS OpsWorks User Guidenginx Attributes

Page 225: Opsworks amazon

gzipWhether gzip compression is enabled (string).The possible values are 'on' and 'off'.The defaultvalue is 'on'.

node[:nginx][:gzip]

gzip_comp_levelThe compression level, which can range from 1–9, with 1 corresponding to the least compression(string). The default value is '2'.

node[:nginx][:gzip_comp_level]

gzip_disableDisables gzip compression for specified user agents (string). The value is a regular expression andthe default value is 'MSIE [1-6].(?!.*SV1)'.

node[:nginx][:gzip_disable]

gzip_http_versionEnables gzip compression for a specified HTTP version (string). The default value is '1.0'.

node[:nginx][:gzip_http_version]

gzip_proxiedWhether and how to compress the response to proxy requests, which can take one of the followingvalues (string):

• 'off': do not compress proxied requests.

• 'expired': compress if the Expire header prevents caching

• 'no-cache': compress if the Cache-Control header is set to "no-cache"

• 'no-store': compress if the Cache-Control header is set to "no-store"

• 'private': compress if the Cache-Control header is set to "private"

• 'no_last_modified': compress if Last-Modified is not set

• 'no_etag': compress if the request lacks an ETag header

• 'auth': compress if the request includes an Authorization header

• 'any': compress all proxied requests

The default value is 'any'.

node[:nginx][:gzip_proxied]

gzip_staticWhether the gzip static module is enabled (string). The possible values are 'on' anf 'off'. Thedefault value is 'on'.

node[:nginx][:gzip_static]

gzip_typesA list of MIME types to be compressed (List of String). The default value is ['text/plain','text/html', 'text/css', 'application/x-javascript', 'text/xml','application/xml', 'application/xml+rss', 'text/javascript'].

API Version 2013-02-18219

AWS OpsWorks User Guidenginx Attributes

Page 226: Opsworks amazon

node[:nginx][:gzip_types]

gzip_varyWhether to enable a Vary:Accept-Encoding response header (string). The possible values are'on' and 'off'. The default value is 'on'.

node[:nginx][:gzip_vary]

keepaliveWhether to enable a keep-alive connection (string). The possible values are 'on' and 'off'. Thedefault value is 'on'.

node[:nginx][:keepalive]

keepalive_timeoutThe maximum amount of time, in seconds, that a keep-alive connection remains open (number).Thedefault value is 65.

node[:nginx][:keepalive_timeout]

log_dirThe location of the log files (string). The default value is '/var/log/nginx'.

node[:nginx][:log_dir]

userThe user (string). The default values are as follows:

• Amazon: 'www-data'

• Ubuntu: 'nginx'

node[:nginx][:user]

server_names_hash_bucket_sizeThe bucket size for hash tables of server names, which can be set to 32, 64, or 128 (number). Thedefault value is 64.

node[:nginx][:server_names_hash_bucket_size]

worker_processesThe number of worker processes (number). The default value is 10.

node[:nginx][:worker_processes]

worker_connectionsThe maximum number of worker connections (number). The default value is 1024. The maximumnumber of clients is set to worker_processes * worker_connections.

node[:nginx][:worker_connections]

API Version 2013-02-18220

AWS OpsWorks User Guidenginx Attributes

Page 227: Opsworks amazon

passenger_apache2 AttributesThe passenger_apache2 attributes specify the Phusion Passenger configuration. For more information,see Phusion Passenger users guide, Apache version.

high_performance_mode (p. 198)gems_path (p. 198)gem_bin (p. 198)

max_pool_size (p. 198)max_instances_per_app (p.198)root_path (p. 198)

pool_idle_time (p. 198)module_path (p. 198)max_requests (p. 198)

rails_spawn_method (p. 198)rails_framework_spawner_idle_time(p. 198)

rails_app_spawner_idle_time(p. 198)

stat_throttle_rate (p. 198)ruby_wrapper_bin (p. 198)ruby_bin (p. 198)

version (p. 198)

gem_binThe location of the Gem binaries (string). The default value is '/usr/local/bin/gem'.

node[:passenger_apache2][:gem_bin]

gems_pathThe gems path (string). The default value depends on the Ruby version:

• Ruby version 1.8: '/usr/local/lib/ruby/gems/1.8/gems'

• Ruby version 1.9: '/usr/local/lib/ruby/gems/1.9.1/gems'

node[:passenger_apache2][:gems_path]

high_performance_modeWhether to use Passenger's high-performance mode (string). The possible values are 'on' and'off'. The default value is 'off'.

node[:passenger_apache2][:high_performance_mode ]

root_pathThe Passenger root directory (string).The default value depends on the Ruby and Passenger versions.In Chef syntax, the value is"#{node[:passenger][:gems_path]}/passenger-#{passenger[:version]}".

node[:passenger_apache2][:root_path]

max_instances_per_appThe maximum number of application processes per app (number). The default value is 0. For moreinformation, see PassengerMaxInstancesPerApp.

node[:passenger_apache2][:max_instances_per_app]

max_pool_sizeThe maximum number of application processors (number). The default value is 8. For moreinformation, see PassengerMaxPoolSize.

API Version 2013-02-18221

AWS OpsWorks User Guidepassenger_apache2 Attributes

Page 228: Opsworks amazon

node[:passenger_apache2][:max_pool_size]

max_requestsThe maximum number of requests (number). The default value is 0.

node[:passenger_apache2][:max_requests]

module_pathThe module path (string). The default values are as follows:

• Amazon: "#{node['apache']['libexecdir (p. 206)']}/mod_passenger.so"

• Ubuntu: "#{passenger[:root_path (p. 221)]}/ext/apache2/mod_passenger.so"

node[:passenger_apache2][:module_path]

pool_idle_timeThe maximum time, in seconds, that an application process can be idle (number). The default valueis 14400 (4 hours). For more information, see PassengerPoolIdleTime.

node[:passenger_apache2][:pool_idle_time]

rails_app_spawner_idle_timeThe maximum idle time for the Rails app spawner (number). If this attribute is set to zero, the appspawner does not time out. The default value is 0. For more information, see Spawning MethodsExplained.

node[:passenger_apache2][:rails_app_spawner_idle_time]

rails_framework_spawner_idle_timeThe maximum idle time for the Rails framework spawner (number). If this attribute is set to zero, theframework spawner does not time out. The default value is 0. For more information, see SpawningMethods Explained.

node[:passenger_apache2][:rails_framework_spawner_idle_time]

rails_spawn_methodThe Rails spawn method (string). The default value is 'smart-lv2'. For more information, seeSpawning Methods Explained.

node[:passenger_apache2][:rails_spawn_method]

ruby_binThe location of the Ruby binaries (string). The default value is '/usr/local/bin/ruby'.

node[:passenger_apache2][:ruby_bin]

ruby_wrapper_binThe location of the Ruby wrapper script (string). The default value is'/usr/local/bin/ruby_gc_wrapper.sh'.

node[:passenger_apache2][:ruby_wrapper_bin]

API Version 2013-02-18222

AWS OpsWorks User Guidepassenger_apache2 Attributes

Page 229: Opsworks amazon

stat_throttle_rateThe rate at which Passenger performs file system checks (number). The default value is 5, whichmeans that the checks will be performed at most once every 5 seconds. For more information, seePassengerStatThrottleRate .

node[:passenger_apache2][:stat_throttle_rate]

versionThe version (string). The default value is '3.0.9'.

node[:passenger_apache2][:version]

ruby AttributesThe ruby attributes specify the Ruby configuration.

major_versionThe major version number (string). The default value is '1.9'.

[:ruby][:major_version]

full_versionThe full version number (string). The default value is '1.9.3'.

[:ruby][:full_version]

patchThe patch number (string).

[:ruby][:patch]

pkgreleaseThe package release number (string). The default value is '1'.

[:ruby][:pkgrelease]

unicorn AttributesThe unicorn attributes specify the Unicorn configuration. For more information, see Unicorn::Configurator.

delay (p. 198)backlog (p. 198)accept_filter (p. 198)

preload_app (p. 198)tcp_nopush (p. 198)tcp_nodelay (p. 198)

version (p. 198)tries (p. 198)timeout (p. 198)

worker_processes (p. 198)

API Version 2013-02-18223

AWS OpsWorks User Guideruby Attributes

Page 230: Opsworks amazon

accept_filterThe accept filter, 'httpready' or 'dataready' (string). The default value is 'httpready'.

node[:unicorn][:accept_filter]

backlogThe maximum number of requests that the queue can hold (number). The default value is 1024.

node[:unicorn][:backlog]

delayThe amount of time, in seconds, to wait to retry binding a socket (number). The default value is 0.5.

node[:unicorn][:delay]

preload_appWhether to preload an app before forking a worker process (Boolean). The default value is true.

node[:unicorn][:preload_app]

tcp_nodelayWhether to disable Nagle's algorithm for TCP sockets (Boolean). The default value is true.

node[:unicorn][:tcp_nodelay]

tcp_nopushWhether to enable TCP_CORK (Boolean). The default value is false.

node[:unicorn][:tcp_nopush]

timeoutThe maximum amount time, in seconds, that a worker is allowed to use for each request (number).Workers that exceed the timeout value are terminated. The default value is 60.

node[:unicorn][:timeout]

triesThe maximum number of times to retry binding to a socket (number). The default value is 5.

node[:unicorn][:tries]

versionThe Unicorn version (string). The default value is '4.0.1'.

node[:unicorn][:version]

worker_processesThe number of worker processes (number). The default value is max_pool_size, if it exists, and 4otherwise.

API Version 2013-02-18224

AWS OpsWorks User Guideunicorn Attributes

Page 231: Opsworks amazon

node[:unicorn][:worker_processes]

API Version 2013-02-18225

AWS OpsWorks User Guideunicorn Attributes

Page 232: Opsworks amazon

History

The following table describes the important changes to the documentation in this release of AWSOpsWorks.

• API version: 2013-02-18

• Latest documentation update: February 18, 2013

Date ChangedDescriptionChange

February 18, 2013This is the first release of the AWS OpsWorks User Guide.Initial Release

May 14, 2013Added support for Amazon EBS-backed instances, ElasticLoad Balancing, and Amazon CloudWatch monitoring.

Second Release

API Version 2013-02-18226

AWS OpsWorks User Guide