[PDF] ec2 ug - Free Download PDF (2024)

Download ec2 ug...

Amazon Elastic Compute Cloud User Guide for Linux API Version 2014-10-01

Amazon Elastic Compute Cloud User Guide for Linux

Amazon Elastic Compute Cloud: User Guide for Linux Copyright © 2014 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. The following are trademarks of Amazon Web Services, Inc.: Amazon, Amazon Web Services Design, AWS, Amazon CloudFront, Cloudfront, CloudTrail, Amazon DevPay, DynamoDB, ElastiCache, Amazon EC2, Amazon Elastic Compute Cloud, Amazon Glacier, Kinesis, Kindle, Kindle Fire, AWS Marketplace Design, Mechanical Turk, Amazon Redshift, Amazon Route 53, Amazon S3, Amazon VPC. In addition, Amazon.com graphics, logos, page headers, button icons, scripts, and service names are trademarks, or trade dress of Amazon in the U.S. and/or other countries. Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon.

Amazon Elastic Compute Cloud User Guide for Linux

Table of Contents What Is Amazon EC2? ................................................................................................................... 1 Features of Amazon EC2 ........................................................................................................ 1 How to Get Started with Amazon EC2 ....................................................................................... 2 Related Services ................................................................................................................... 2 Accessing Amazon EC2 ......................................................................................................... 3 Pricing for Amazon EC2 ......................................................................................................... 4 Instances and AMIs ............................................................................................................... 4 Instances ..................................................................................................................... 5 AMIs ........................................................................................................................... 6 Regions and Availability Zones ................................................................................................ 7 Region and Availability Zone Concepts .............................................................................. 7 Describing Your Regions and Availability Zones .................................................................. 9 Specifying the Region for a Resource .............................................................................. 11 Launching Instances in an Availability Zone ...................................................................... 12 Migrating an Instance to Another Availability Zone ............................................................. 13 Root Device Volume ............................................................................................................. 14 Root Device Storage Concepts ...................................................................................... 14 Choosing an AMI by Root Device Type ............................................................................ 16 Determining the Root Device Type of Your Instance ............................................................ 17 Changing the Root Device Volume to Persist .................................................................... 17 Setting Up .................................................................................................................................. 20 Sign Up for AWS ................................................................................................................. 20 Create an IAM User ............................................................................................................. 21 Create a Key Pair ................................................................................................................ 22 Create a Virtual Private Cloud (VPC) ....................................................................................... 24 Create a Security Group ....................................................................................................... 24 Getting Started ............................................................................................................................ 26 Step 1: Launch an Instance ................................................................................................... 27 Step 2: Connect to Your Instance ............................................................................................ 28 Option 1: Connect Using Your Browser ............................................................................ 29 Option 2: Connect from Windows Using PuTTY ................................................................. 30 Option 3: Connect from Mac or Linux Using an SSH Client .................................................. 31 Step 3: Add a Volume ........................................................................................................... 31 Step 4: Clean Up ................................................................................................................. 34 Best Practices ............................................................................................................................. 36 Tutorial: Installing a LAMP Web Server ............................................................................................ 38 Tutorial: Hosting a WordPress Blog ................................................................................................. 45 Amazon Machine Images .............................................................................................................. 53 Using an AMI ...................................................................................................................... 53 Creating Your Own AMI ......................................................................................................... 54 Buying, Sharing, and Selling AMIs .......................................................................................... 54 Deregistering Your AMI ......................................................................................................... 54 Amazon Linux ..................................................................................................................... 54 AMI Types .......................................................................................................................... 55 Launch Permissions ..................................................................................................... 55 Storage for the Root Device ........................................................................................... 55 Virtualization Types .............................................................................................................. 58 Finding a Linux AMI ............................................................................................................. 58 Finding a Linux AMI Using the Amazon EC2 Console ......................................................... 59 Finding an AMI Using the Command Line ........................................................................ 59 Shared AMIs ....................................................................................................................... 60 Finding Shared AMIs .................................................................................................... 60 Making an AMI Public ................................................................................................... 63 Sharing an AMI with Specific AWS Accounts .................................................................... 64 Using Bookmarks ........................................................................................................ 66 API Version 2014-10-01 iii

Amazon Elastic Compute Cloud User Guide for Linux

Guidelines for Shared Linux AMIs ................................................................................... 66 Paid AMIs ........................................................................................................................... 70 Selling Your AMI .......................................................................................................... 70 Finding a Paid AMI ....................................................................................................... 71 Purchase a Paid AMI .................................................................................................... 71 Getting the Product Code for Your Instance ...................................................................... 72 Using Paid Support ...................................................................................................... 72 Bills for Paid and Supported AMIs ................................................................................... 73 Managing Your AWS Marketplace Subscriptions ................................................................ 73 Creating an Amazon EBS-Backed Linux AMI ............................................................................ 74 Overview of the Creation Process for Amazon EBS-Backed AMIs ........................................ 74 Creating the AMI from an Instance .................................................................................. 75 Creating an AMI from a Snapshot ................................................................................... 76 Creating an Instance Store-Backed Linux AMI .......................................................................... 77 Overview of the Creation Process for Instance Store-Backed AMIs ....................................... 77 Prerequisites .............................................................................................................. 78 Creating an AMI from an Instance Store-Backed Linux Instance ........................................... 78 Converting your Instance Store-Backed AMI to an Amazon EBS-Backed AMI ......................... 82 Copying an AMI ................................................................................................................... 85 AMI Copy ................................................................................................................... 85 Copying an Amazon EC2 AMI ........................................................................................ 86 Copying an Amazon EC2 AMI with Encrypted Volumes ...................................................... 87 Stopping a Pending AMI Copy Operation ......................................................................... 89 Deregistering Your AMI ......................................................................................................... 90 Cleaning Up Your Amazon EBS-Backed AMI .................................................................... 90 Cleaning Up Your Instance Store-Backed AMI ................................................................... 91 Amazon Linux ..................................................................................................................... 91 Finding the Amazon Linux AMI ....................................................................................... 92 Launching and Connecting to an Amazon Linux Instance .................................................... 92 Identifying Amazon Linux AMI Images ............................................................................. 92 Included AWS Command Line Tools ................................................................................ 93 cloud-init .............................................................................................................. 94 Repository Configuration ............................................................................................... 95 Adding Packages ......................................................................................................... 96 Accessing Source Packages for Reference ...................................................................... 96 Developing Applications ................................................................................................ 97 Instance Store Access .................................................................................................. 97 Product Life Cycle ........................................................................................................ 97 Security Updates ......................................................................................................... 97 Support ...................................................................................................................... 98 PV-GRUB ........................................................................................................................... 98 Limitations of PV-GRUB ................................................................................................ 99 Configuring GRUB ....................................................................................................... 99 Amazon PV-GRUB Kernel Image IDs ............................................................................. 100 Updating PV-GRUB .................................................................................................... 102 Instances .................................................................................................................................. 103 Instance Types .................................................................................................................. 103 Available Instance Types ............................................................................................. 104 Hardware Specifications .............................................................................................. 105 T2 Instances ............................................................................................................. 105 I2 Instances .............................................................................................................. 109 HI1 Instances ............................................................................................................ 110 HS1 Instances ........................................................................................................... 112 R3 Instances ............................................................................................................. 113 GPU Instances .......................................................................................................... 115 T1 Micro Instances ..................................................................................................... 118 EBS-Optimized Instances ............................................................................................ 125 Placement Groups ..................................................................................................... 126 API Version 2014-10-01 iv

Amazon Elastic Compute Cloud User Guide for Linux

Resizing Instances ..................................................................................................... Spot Instances .................................................................................................................. Quick Look: Getting Started with Spot Instances Video ..................................................... Checklist for Getting Started with Spot Instances ............................................................. Getting Started with Spot Instances .............................................................................. Fundamentals of Spot Instances ................................................................................... Walkthroughs: Using Spot Instances with AWS Services ................................................... Advanced Tasks ......................................................................................................... Reserved Instances ............................................................................................................ Reserved Instance Overview ........................................................................................ Getting Started with Reserved Instances ........................................................................ Reserved Instance Fundamentals ................................................................................. Buying Reserved Instances ......................................................................................... Obtaining Information About Your Reserved Instances ...................................................... Modifying Your Reserved Instances ............................................................................... Selling in the Reserved Instance Marketplace ................................................................. Requirements Checklist for Reserved Instances .............................................................. Instance Metadata and User Data ......................................................................................... Retrieving Instance Metadata ....................................................................................... Retrieving User Data .................................................................................................. Retrieving Dynamic Data ............................................................................................. Example: AMI Launch Index Value ................................................................................ Instance Metadata Categories ...................................................................................... Importing and Exporting Instances ........................................................................................ Prerequisites ............................................................................................................. Importing a VM into Amazon EC2 ................................................................................. Exporting Amazon EC2 Instances ................................................................................. Troubleshooting ......................................................................................................... Instance Lifecycle ...................................................................................................................... Instance Launch ................................................................................................................ Instance Stop and Start (Amazon EBS-backed instances only) .................................................. Instance Reboot ................................................................................................................ Instance Retirement ........................................................................................................... Instance Termination .......................................................................................................... Differences Between Reboot, Stop, and Terminate ................................................................... Launch ............................................................................................................................. Launching an Instance ................................................................................................ Launching an Instance From an Existing Instance ............................................................ Launching a Linux Instance from a Backup ..................................................................... Launching an AWS Marketplace Instance ....................................................................... Connect ........................................................................................................................... Connect Using SSH ................................................................................................... Connect Using PuTTY ................................................................................................ Connect Using MindTerm ............................................................................................ Stop and Start ................................................................................................................... Overview .................................................................................................................. Stopping and Starting Your Instances ............................................................................ Modifying a Stopped Instance ...................................................................................... Troubleshooting ......................................................................................................... Reboot ............................................................................................................................. Retire ............................................................................................................................... Identifying Instances Scheduled for Retirement ............................................................... Working with Instances Scheduled for Retirement ............................................................ Terminate ......................................................................................................................... Instance Termination .................................................................................................. Terminating an Instance .............................................................................................. Enabling Termination Protection .................................................................................... Changing the Shutdown Behavior ................................................................................. API Version 2014-10-01 v

128 132 132 132 133 145 161 180 185 185 186 191 202 213 218 228 254 256 257 259 260 260 262 267 268 270 279 280 286 286 287 287 287 288 288 289 290 295 296 297 299 299 303 308 309 309 310 311 312 312 312 313 313 315 315 315 316 317

Amazon Elastic Compute Cloud User Guide for Linux

Preserving Amazon EBS Volumes on Instance Termination ............................................... Troubleshooting ......................................................................................................... Configure Instances ................................................................................................................... Common Configuration Scenarios ......................................................................................... Managing Software ............................................................................................................ Updating Instance Software ......................................................................................... Adding Repositories ................................................................................................... Finding Software Packages .......................................................................................... Installing Software Packages ........................................................................................ Preparing to Compile Software ..................................................................................... Managing Users ................................................................................................................ Setting the Time ................................................................................................................. Changing the Time Zone ............................................................................................. Configuring Network Time Protocol (NTP) ...................................................................... Changing the Hostname ...................................................................................................... Changing the System Hostname ................................................................................... Changing the Shell Prompt Without Affecting the Hostname .............................................. Setting Up Dynamic DNS .................................................................................................... Running Commands at Launch ............................................................................................ Prerequisites ............................................................................................................. User Data and Shell Scripts ......................................................................................... User Data and cloud-init Directives ................................................................................ Monitoring ................................................................................................................................ Automated and Manual Monitoring ........................................................................................ Automated Monitoring Tools ......................................................................................... Manual Monitoring Tools .............................................................................................. Best Practices for Monitoring ................................................................................................ Monitoring the Status of Your Instances .................................................................................. Monitoring Instances with Status Checks ....................................................................... Monitoring Events for Your Instances ............................................................................. Monitoring Your Instances with CloudWatch ............................................................................ Enabling or Disabling Detailed Monitoring on an Amazon EC2 Instance ............................... View Amazon EC2 Metrics .......................................................................................... Get Statistics for Metrics ............................................................................................. Graphing Metrics ....................................................................................................... Create a CloudWatch Alarm ......................................................................................... Create Alarms That Stop or Terminate an Instance ........................................................... Monitoring Scripts for Amazon EC2 Instances ......................................................................... Amazon CloudWatch Monitoring Scripts for Linux ............................................................ Network and Security ................................................................................................................. Key Pairs .......................................................................................................................... Creating Your Key Pair Using Amazon EC2 ..................................................................... Importing Your Own Key Pair to Amazon EC2 .................................................................. Retrieving the Public Key for Your Key Pair ...................................................................... Verifying Your Key Pair's Fingerprint .............................................................................. Deleting Your Key Pair ................................................................................................. Connecting to Your Linux Instance if You Lose Your Private Key .......................................... Security Groups ................................................................................................................. Security Groups for EC2-Classic ................................................................................... Security Groups for EC2-VPC ...................................................................................... Security Group Rules ................................................................................................. Default Security Groups .............................................................................................. Custom Security Groups ............................................................................................. Creating a Security Group ........................................................................................... Describing Your Security Groups ................................................................................... Adding Rules to a Security Group ................................................................................. Deleting Rules from a Security Group ............................................................................ Deleting a Security Group ............................................................................................ API Version 2014-10-01 vi

318 320 321 321 322 322 326 327 328 329 330 332 332 333 335 335 336 337 339 340 340 341 343 344 344 345 346 346 346 351 354 355 358 364 380 384 391 405 405 412 413 413 415 416 417 418 418 421 422 422 423 424 424 425 426 426 427 428

Amazon Elastic Compute Cloud User Guide for Linux

API and Command Overview ....................................................................................... Controlling Access ............................................................................................................. Network Access to Your Instance .................................................................................. Amazon EC2 Permission Attributes ............................................................................... IAM and Amazon EC2 ................................................................................................ IAM Policies .............................................................................................................. IAM Roles ................................................................................................................. Network Access ......................................................................................................... Amazon VPC .................................................................................................................... Benefits of Using a VPC .............................................................................................. Differences Between EC2-Classic and EC2-VPC ............................................................. Amazon VPC Documentation ....................................................................................... Supported Platforms ................................................................................................... Migrating from EC2-Classic to a VPC ............................................................................ Instance IP Addressing ....................................................................................................... Private IP Addresses and Internal DNS Hostnames ......................................................... Public IP Addresses and External DNS Hostnames ......................................................... Elastic IP Addresses ................................................................................................... Differences Between EC2-Classic and EC2-VPC ............................................................. Determining Your Public, Private, and Elastic IP Addresses ............................................... Assigning a Public IP Address ...................................................................................... Multiple Private IP Addresses ....................................................................................... Elastic IP Addresses ........................................................................................................... Elastic IP Addresses in EC2-Classic .............................................................................. Elastic IP Addresses in a VPC ...................................................................................... Differences Between EC2-Classic and EC2-VPC ............................................................. Allocating an Elastic IP Address ................................................................................... Describing Your Elastic IP Addresses ............................................................................. Associating an Elastic IP Address with a Running Instance ............................................... Associating an Elastic IP Address with a Different Running Instance ................................... Releasing an Elastic IP Address ................................................................................... Using Reverse DNS for Email Applications ..................................................................... Elastic IP Address Limit .............................................................................................. Elastic Network Interfaces ................................................................................................... Private IP Addresses Per ENI Per Instance Type .............................................................. Creating a Management Network .................................................................................. Use Network and Security Appliances in Your VPC .......................................................... Creating Dual-homed Instances with Workloads/Roles on Distinct Subnets .......................... Create a Low Budget High Availability Solution ................................................................ Best Practices for Configuring Network Interfaces ............................................................ Configuring Your Network Interface Using ec2-net-utils ..................................................... Creating a Network Interface ........................................................................................ Deleting a Network Interface ........................................................................................ Viewing Details about a Network Interface ...................................................................... Attaching a Network Interface When Launching an Instance .............................................. Attaching a Network Interface to a Stopped or Running Instance ........................................ Detaching a Network Interface from an Instance .............................................................. Changing the Security Group of a Network Interface ........................................................ Changing the Source/Destination Checking of a Network Interface ..................................... Associating an Elastic IP Address with a Network Interface ............................................... Disassociating an Elastic IP Address from a Network Interface ........................................... Changing Termination Behavior for a Network Interface .................................................... Adding or Editing a Description for a Network Interface ..................................................... Adding or Editing Tags for a Network Interface ................................................................ Enhanced Networking ......................................................................................................... Requirements ............................................................................................................ Testing Whether Enhanced Networking Is Enabled ........................................................... Enabling Enhanced Networking on Amazon Linux ........................................................... API Version 2014-10-01 vii

428 429 429 429 430 431 461 467 468 468 482 470 471 473 480 480 481 482 482 482 484 485 489 490 490 491 491 492 492 492 493 494 494 494 495 497 497 497 498 498 498 499 500 500 501 502 502 503 504 504 505 505 506 506 507 507 508 510

Amazon Elastic Compute Cloud User Guide for Linux

Enabling Enhanced Networking on Ubuntu ..................................................................... Enabling Enhanced Networking on Other Linux Distributions ............................................. Troubleshooting Connectivity Issues .............................................................................. Storage .................................................................................................................................... Amazon EBS .................................................................................................................... Features of Amazon EBS ............................................................................................ EBS Volumes ............................................................................................................ EBS Snapshots ......................................................................................................... EBS Encryption ......................................................................................................... EBS Performance ...................................................................................................... API and Command Overview ....................................................................................... Instance Store ................................................................................................................... Instance Storage Concepts ......................................................................................... Instance Stores Available on Instance Types ................................................................... Instance Store Swap Volumes ...................................................................................... Instance Store Device Names ...................................................................................... Instance Store Usage Scenarios .................................................................................. Adding Instance Store Volumes to an AMI ...................................................................... Optimizing Disk Performance ....................................................................................... Amazon S3 ....................................................................................................................... Amazon S3 and Amazon EC2 ...................................................................................... Block Device Mapping ........................................................................................................ Block Device Mapping Concepts ................................................................................... AMI Block Device Mapping .......................................................................................... Instance Block Device Mapping .................................................................................... Using Public Data Sets ....................................................................................................... Public Data Set Concepts ............................................................................................ Finding Public Data Sets ............................................................................................. Creating a Public Data Set Volume from a Snapshot ........................................................ Attaching and Mounting the Public Data Set Volume ......................................................... Resources and Tags ................................................................................................................... Resource Locations ............................................................................................................ Listing and Filtering Your Resources ...................................................................................... Advanced Search ....................................................................................................... Listing Resources Using the Console ............................................................................ Filtering Resources Using the Console .......................................................................... Listing and Filtering Using the CLI and API ..................................................................... Tagging Your Resources ...................................................................................................... Tag Basics ................................................................................................................ Tag Restrictions ......................................................................................................... Tagging Your Resources for Billing ................................................................................ Working with Tags in the Console .................................................................................. API and CLI Overview ................................................................................................. Service Limits .................................................................................................................... Viewing Your Current Limits ......................................................................................... Requesting a Limit Increase ......................................................................................... Usage Reports .................................................................................................................. Available Reports ....................................................................................................... Getting Set Up for Usage Reports ................................................................................. Granting IAM Users Access to the Amazon EC2 Usage Reports ........................................ Instance Usage ......................................................................................................... Reserved Instance Utilization ....................................................................................... Troubleshooting ......................................................................................................................... Launching Your Instance ..................................................................................................... Getting the Reason for Instance Termination ................................................................... Connecting to Your Instance ................................................................................................. Error connecting to your instance: Connection timed out ................................................... Error: User key not recognized by server ........................................................................ API Version 2014-10-01 viii

512 515 517 518 519 520 521 559 564 567 578 581 581 582 584 586 586 588 589 589 590 591 592 595 597 602 602 602 603 604 605 605 606 607 608 608 609 610 610 611 612 612 617 618 618 619 619 619 619 621 621 625 631 631 632 632 633 634

Amazon Elastic Compute Cloud User Guide for Linux

Error: Host key not found, Permission denied (publickey), or Authentication failed, permission denied ..................................................................................................................... Error: Unprotected Private Key File ............................................................................... Error: Server refused our key or No supported authentication methods available ................... Error using MindTerm on Safari Browser ........................................................................ Error Using Mac OS X RDP Client ................................................................................ Stopping Your Instance ........................................................................................................ Terminating Your Instance .................................................................................................... Delayed Instance Termination ....................................................................................... Automatically Launch or Terminate Instances .................................................................. Failed Status Checks .......................................................................................................... Initial Steps You Can Take ............................................................................................ Troubleshooting Instance Status Checks for Linux-Based Instances .................................... Out of memory: kill process .......................................................................................... ERROR: mmu_update failed (Memory management update failed) ..................................... I/O error (Block device failure) ...................................................................................... IO ERROR: neither local nor remote disk (Broken distributed block device) .......................... request_module: runaway loop modprobe (Looping legacy kernel modprobe on older Linux versions) .................................................................................................................. "FATAL: kernel too old" and "fsck: No such file or directory while trying to open /dev" (Kernel and AMI mismatch) ................................................................................................... "FATAL: Could not load /lib/modules" or "BusyBox" (Missing kernel modules) ........................ ERROR Invalid kernel (EC2 incompatible kernel) ............................................................. request_module: runaway loop modprobe (Looping legacy kernel modprobe on older Linux versions) .................................................................................................................. fsck: No such file or directory while trying to open... (File system not found) .......................... General error mounting filesystems (Failed mount) ........................................................... VFS: Unable to mount root fs on unknown-block (Root filesystem mismatch) ........................ Error: Unable to determine major/minor number of root device... (Root file system/device mismatch) .................................................................................................................... XENBUS: Device with no driver... .................................................................................. ... days without being checked, check forced (File system check required) ............................ fsck died with exit status... (Missing device) ..................................................................... GRUB prompt (grubdom>) ........................................................................................... Bringing up interface eth0: Device eth0 has different MAC address than expected, ignoring. (Hard-coded MAC address) ........................................................................................ Unable to load SELinux Policy. Machine is in enforcing mode. Halting now. (SELinux misconfiguration) ................................................................................................................. XENBUS: Timeout connecting to devices (Xenbus timeout) ............................................... Instance Capacity .............................................................................................................. Error: InsufficientInstanceCapacity ................................................................................ Error: InstanceLimitExceeded ....................................................................................... General ............................................................................................................................ Instance Reboot ........................................................................................................ Instance Console Output ............................................................................................. Instance Recovery When its Host Computer Fails ............................................................ Making API Requests ................................................................................................................. Required Knowledge .......................................................................................................... Available APIs for Amazon EC2 ............................................................................................ Query Requests ................................................................................................................ Structure of a GET Request ......................................................................................... Endpoints ................................................................................................................. Query Parameters ...................................................................................................... Query API Authentication ............................................................................................ Query Response Structures ......................................................................................... Troubleshooting API Request Errors ...................................................................................... Query API Request Rate ............................................................................................. Eventual Consistency ................................................................................................. API Version 2014-10-01 ix

635 636 636 637 637 637 638 638 639 639 639 640 641 641 642 643 644 645 646 647 648 649 651 653 654 655 656 657 658 660 661 661 662 662 662 663 663 663 664 665 665 665 666 667 668 668 668 669 670 670 671

Amazon Elastic Compute Cloud User Guide for Linux

Unauthorized Operation .............................................................................................. Ensuring Idempotency ........................................................................................................ Idempotency Support ................................................................................................. Example Idempotent Command .................................................................................... Example Idempotent Query ......................................................................................... SOAP Requests ................................................................................................................ Logging API Calls .............................................................................................................. Amazon EC2 Information in CloudTrail ........................................................................... Understanding Amazon EC2 Log File Entries .................................................................. Document History ...................................................................................................................... AWS Glossary ...........................................................................................................................

API Version 2014-10-01 x

671 672 673 673 674 674 674 675 675 677 688

Amazon Elastic Compute Cloud User Guide for Linux Features of Amazon EC2

What Is Amazon EC2? Amazon Elastic Compute Cloud (Amazon EC2) provides scalable computing capacity in the Amazon Web Services (AWS) cloud. Using Amazon EC2 eliminates your need to invest in hardware up front, so you can develop and deploy applications faster. You can use Amazon EC2 to launch as many or as few virtual servers as you need, configure security and networking, and manage storage. Amazon EC2 enables you to scale up or down to handle changes in requirements or spikes in popularity, reducing your need to forecast traffic. For more information about cloud computing, see What is Cloud Computing?

Features of Amazon EC2 Amazon EC2 provides the following features: • Virtual computing environments, known as instances • Preconfigured templates for your instances, known as Amazon Machine Images (AMIs), that package the bits you need for your server (including the operating system and additional software) • Various configurations of CPU, memory, storage, and networking capacity for your instances, known as instance types • Secure login information for your instances using key pairs (AWS stores the public key, and you store the private key in a secure place) • Storage volumes for temporary data that's deleted when you stop or terminate your instance, known as instance store volumes • Persistent storage volumes for your data using Amazon Elastic Block Store (Amazon EBS), known as Amazon EBS volumes • Multiple physical locations for your resources, such as instances and Amazon EBS volumes, known as regions and Availability Zones • A firewall that enables you to specify the protocols, ports, and source IP ranges that can reach your instances using security groups • Static IP addresses for dynamic cloud computing, known as Elastic IP addresses • Metadata, known as tags, that you can create and assign to your Amazon EC2 resources • Virtual networks you can create that are logically isolated from the rest of the AWS cloud, and that you can optionally connect to your own network, known as virtual private clouds (VPCs) For more information about the features of Amazon EC2, see the Amazon EC2 product page. API Version 2014-10-01 1

Amazon Elastic Compute Cloud User Guide for Linux How to Get Started with Amazon EC2

For more information about running your website on AWS, see Websites & Website Hosting.

How to Get Started with Amazon EC2 The first thing you need to do is get set up to use Amazon EC2. After you are set up, you are ready to complete the Getting Started tutorial for Amazon EC2. Whenever you need more information about a feature of Amazon EC2, you can read the technical documentation.

Get Up and Running • Setting Up with Amazon EC2 (p. 20) • Getting Started with Amazon EC2 Linux Instances (p. 26)

Basics • Instances and AMIs (p. 4) • Regions and Availability Zones (p. 7) • Instance Types (p. 103) • Tags (p. 610)

Networking and Security • Amazon EC2 Key Pairs (p. 413) • Security Groups (p. 421) • Elastic IP Addresses (EIP) (p. 489) • Amazon EC2 and Amazon VPC (p. 468)

Storage • Amazon EBS (p. 519) • Instance Store (p. 581)

Working with Linux Instances • Tutorial: Installing a LAMP Web Server (p. 38) • Getting Started with AWS Web Application Hosting for Linux

If you have questions about whether AWS is right for you, contact AWS Sales. If you have technical questions about Amazon EC2, use the Amazon EC2 forum.

Related Services You can provision Amazon EC2 resources, such as instances and volumes, directly using Amazon EC2. You can also provision Amazon EC2 resources using other services in AWS. For more information, see the following documentation:

API Version 2014-10-01 2

Amazon Elastic Compute Cloud User Guide for Linux Accessing Amazon EC2

• Auto Scaling Developer Guide • AWS CloudFormation User Guide • AWS Elastic Beanstalk Developer Guide • AWS OpsWorks User Guide To automatically distribute incoming application traffic across multiple instances, use Elastic Load Balancing. For more information, see Elastic Load Balancing Developer Guide. To monitor basic statistics for your instances and Amazon EBS volumes, use Amazon CloudWatch. For more information, see the Amazon CloudWatch Developer Guide. To monitor the calls made to the Amazon EC2 API for your account, including calls made by the AWS Management Console, command line tools, and other services, use AWS CloudTrail. For more information, see the AWS CloudTrail User Guide. To get a managed relational database in the cloud, use Amazon Relational Database Service (Amazon RDS) to launch a database instance. Although you can set up a database on an EC2 instance, Amazon RDS offers the advantage of handling your database management tasks, such as patching the software, backing up, and storing the backups. For more information, see Amazon Relational Database Service Developer Guide.

Accessing Amazon EC2 Amazon EC2 provides a web-based user interface, the Amazon EC2 console. If you've signed up for an AWS account, you can access the Amazon EC2 console by signing into the AWS Management Console and selecting EC2 from the console home page. If you prefer to use a command line interface, you have several options: AWS Command Line Interface (CLI) Provides commands for a broad set of AWS products, and is supported on Windows, Mac, and Linux. To get started, see AWS Command Line Interface User Guide. For more information about the commands for Amazon EC2, see ec2 in the AWS Command Line Interface Reference. Amazon EC2 Command Line Interface (CLI) Tools Provides commands for Amazon EC2, Amazon EBS, and Amazon VPC, and is supported on Windows, Mac, and Linux. To get started, see Setting Up the Amazon EC2 Command Line Interface Tools on Linux and Commands (CLI Tools) in the Amazon EC2 Command Line Reference. AWS Tools for Windows PowerShell Provides commands for a broad set of AWS products for those who script in the PowerShell environment. To get started, see the AWS Tools for Windows PowerShell User Guide. For more information about the cmdlets for Amazon EC2, see the AWS Tools for Windows PowerShell Reference. Amazon EC2 provides a Query API. These requests are HTTP or HTTPS requests that use the HTTP verbs GET or POST and a Query parameter named Action. For more information about the API actions for Amazon EC2, see Actions in the Amazon EC2 API Reference. If you prefer to build applications using language-specific APIs instead of submitting a request over HTTP or HTTPS, AWS provides libraries, sample code, tutorials, and other resources for software developers. These libraries provide basic functions that automate tasks such as cryptographically signing your requests, retrying requests, and handling error responses, making it is easier for you to get started. For more information, see AWS SDKs and Tools.

API Version 2014-10-01 3

Amazon Elastic Compute Cloud User Guide for Linux Pricing for Amazon EC2

Pricing for Amazon EC2 When you sign up for AWS, you can get started with Amazon EC2 for free using the AWS Free Tier. Amazon EC2 provides the following purchasing options for instances: On-Demand Instances Pay for the instances that you use by the hour, with no long-term commitments or up-front payments. Reserved Instances Make a low, one-time, up-front payment for an instance, reserve it for a one- or three-year term, and pay a significantly lower hourly rate for these instances. Spot Instances Specify the maximum hourly price that you are willing to pay to run a particular instance type. The Spot Price fluctuates based on supply and demand, but you never pay more than the maximum price you specified. If the Spot Price moves higher than your maximum price, Amazon EC2 shuts down your Spot Instances. For a complete list of charges and specific prices for Amazon EC2, see Amazon EC2 Pricing. To calculate the cost of a sample provisioned environment, see AWS Economics Center. To see your bill, go to your AWS Account Activity page. Your bill contains links to usage reports that provide details about your bill. To learn more about AWS account billing, see AWS Account Billing. If you have questions concerning AWS billing, accounts, and events, contact AWS Support. For an overview of Trusted Advisor, a service that helps you optimize the costs, security, and performance of your AWS environment, see AWS Trusted Advisor.

Instances and AMIs An Amazon Machine Image (AMI) is a template that contains a software configuration (for example, an operating system, an application server, and applications). From an AMI, you launch an instance, which is a copy of the AMI running as a virtual server in the cloud. You can launch multiple instances of an AMI, as shown in the following figure.

Your instances keep running until you stop or terminate them, or until they fail. If an instance fails, you can launch a new one from the AMI.

API Version 2014-10-01 4

Amazon Elastic Compute Cloud User Guide for Linux Instances

Instances You can launch different types of instances from a single AMI. An instance type essentially determines the hardware of the host computer used for your instance. Each instance type offers different compute and memory capabilities. Select an instance type based on the amount of memory and computing power that you need for the application or software that you plan to run on the instance. For more information about the hardware specifications for each Amazon EC2 instance type, see Instance Type Details. After you launch an instance, it looks like a traditional host, and you can interact with it as you would any computer. You have complete control of your instances; you can use sudo to run commands that require root privileges. Your AWS account has a limit on the number of instances that you can have running. For more information about this limit, and how to request an increase, see How many instances can I run in Amazon EC2 in the Amazon EC2 General FAQ. In addition to the limit on running instances, there is a limit on the overall number of instances that you can have (whether running, stopped, or in any other state except for terminated). This overall instance limit is two times your running instance limit.

Storage for Your Instance The root device for your instance contains the image used to boot the instance. For more information, see Amazon EC2 Root Device Volume (p. 14). Your instance may include local storage volumes, known as instance store volumes, which you can configure at launch time with block device mapping. For more information, see Block Device Mapping (p. 591). After these volumes have been added to and mapped on your instance, they are available for you to mount and use. If your instance fails, or if your instance is stopped or terminated, the data on these volumes is lost; therefore, these volumes are best used for temporary data. For important data, you should use a replication strategy across multiple instances in order to keep your data safe, or store your persistent data in Amazon S3 or Amazon EBS volumes. For more information, see Storage (p. 518).

Security Best Practices • Use AWS Identity and Access Management (IAM) to control access to your AWS resources, including your instances. You can create IAM users and groups under your AWS account, assign security credentials to each, and control the access that each has to resources and services in AWS. For more information, see Controlling Access to Amazon EC2 Resources (p. 429). • Restrict access by only allowing trusted hosts or networks to access ports on your instance. For example, you can restrict SSH access by restricting incoming traffic on port 22. For more information, see Amazon EC2 Security Groups (p. 421). • Review the rules in your security groups regularly, and ensure that you apply the principle of least privilege—only open up permissions that you require. You can also create different security groups to deal with instances that have different security requirements. Consider creating a bastion security group that allows external logins, and keep the remainder of your instances in a group that does not allow external logins. • Disable password-based logins for instances launched from your AMI. Passwords can be found or cracked, and are a security risk. For more information, see Disable Password-Based Logins for Root (p. 67). For more information about sharing AMIs safely, see Shared AMIs (p. 60).

Stopping, Starting, and Terminating Instances Stopping an instance

API Version 2014-10-01 5

Amazon Elastic Compute Cloud User Guide for Linux AMIs

When an instance is stopped, the instance performs a normal shutdown, and then transitions to a stopped state. All of its Amazon EBS volumes remain attached, and you can start the instance again at a later time. You are not charged for additional instance hours while the instance is in a stopped state. A full instance hour will be charged for every transition from a stopped state to a running state, even if this happens multiple times within a single hour. If the instance type was changed while the instance was stopped, you will be charged the rate for the new instance type after the instance is started. All of the associated Amazon EBS usage of your instance, including root device usage, is billed using typical Amazon EBS prices. When an instance is in a stopped state, you can attach or detach Amazon EBS volumes. You can also create an AMI from the instance, and you can change the kernel, RAM disk, and instance type. Terminating an instance When an instance is terminated, the instance performs a normal shutdown, then the attached Amazon EBS volumes are deleted unless the volume's deleteOnTermination attribute is set to false. The instance itself is also deleted, and you can't start the instance again at a later time. To prevent accidental termination, you can disable instance termination. If you do so, ensure that the disableApiTermination attribute is set to true for the instance. To control the behavior of an instance shutdown, such as shutdown -h in Linux or shutdown in Windows, set the instanceInitiatedShutdownBehavior instance attribute to stop or terminate as desired. Instances with Amazon EBS volumes for the root device default to stop, and instances with instance-store root devices are always terminated as the result of an instance shutdown. For more information, see Instance Lifecycle (p. 286).

AMIs Amazon Web Services (AWS) publishes many Amazon Machine Images (AMIs) that contain common software configurations for public use. In addition, members of the AWS developer community have published their own custom AMIs. You can also create your own custom AMI or AMIs; doing so enables you to quickly and easily start new instances that have everything you need. For example, if your application is a website or a web service, your AMI could include a web server, the associated static content, and the code for the dynamic pages. As a result, after you launch an instance from this AMI, your web server starts, and your application is ready to accept requests. All AMIs are categorized as either backed by Amazon EBS, which means that the root device for an instance launched from the AMI is an Amazon EBS volume, or backed by instance store, which means that the root device for an instance launched from the AMI is an instance store volume created from a template stored in Amazon S3. The description of an AMI indicates the type of root device (either ebs or instance store). This is important because there are significant differences in what you can do with each type of AMI. For more information about these differences, see Storage for the Root Device (p. 55).

API Version 2014-10-01 6

Amazon Elastic Compute Cloud User Guide for Linux Regions and Availability Zones

Regions and Availability Zones Amazon EC2 is hosted in multiple locations world-wide. These locations are composed of regions and Availability Zones. Each region is a separate geographic area. Each region has multiple, isolated locations known as Availability Zones. Amazon EC2 provides you the ability to place resources, such as instances, and data in multiple locations. Resources aren't replicated across regions unless you do so specifically. Amazon operates state-of-the-art, highly-available data centers. Although rare, failures can occur that affect the availability of instances that are in the same location. If you host all your instances in a single location that is affected by such a failure, none of your instances would be available.

Note Some AWS resources might not be available in all regions and Availability Zones. Ensure that you can create the resources you need in the desired regions or Availability Zone before deploying your applications. Topics • Region and Availability Zone Concepts (p. 7) • Describing Your Regions and Availability Zones (p. 9) • Specifying the Region for a Resource (p. 11) • Launching Instances in an Availability Zone (p. 12) • Migrating an Instance to Another Availability Zone (p. 13)

Region and Availability Zone Concepts Each region is completely independent. Each Availability Zone is isolated, but the Availability Zones in a region are connected through low-latency links. The following diagram illustrates the relationship between regions and Availability Zones.

Amazon EC2 resources are either global, tied to a region, or tied to an Availability Zone. For more information, see Resource Locations (p. 605).

Regions Each Amazon EC2 region is designed to be completely isolated from the other Amazon EC2 regions. This achieves the greatest possible fault tolerance and stability. Amazon EC2 provides multiple regions so that you can launch Amazon EC2 instances in locations that meet your requirements. For example, you might want to launch instances in Europe to be closer to your European customers or to meet legal requirements. The following table lists the regions that provide support for Amazon EC2.

API Version 2014-10-01 7

Amazon Elastic Compute Cloud User Guide for Linux Region and Availability Zone Concepts

Code

Name

ap-northeast-1

Asia Pacific (Tokyo)

ap-southeast-1

Asia Pacific (Singapore)

ap-southeast-2

Asia Pacific (Sydney)

eu-central-1

EU (Frankfurt)

eu-west-1

EU (Ireland)

sa-east-1

South America (Sao Paulo)

us-east-1

US East (N. Virginia)

us-west-1

US West (N. California)

us-west-2

US West (Oregon)

When you view your resources, you'll only see the resources tied to the region you've specified. This is because regions are isolated from each other, and we don't replicate resources across regions automatically. When you work with an instance using the command line interface or API actions, you must specify its regional endpoint. For more information about the regions and endpoints for Amazon EC2, see Regions and Endpoints in the Amazon Web Services General Reference. For more information about endpoints and protocols in AWS GovCloud (US), see AWS GovCloud (US) Endpoints in the AWS GovCloud (US) User Guide. When you launch an instance, you must select an AMI that's in the same region. If the AMI is in another region, you can copy the AMI to the region you're using. For more information, see Copying an AMI (p. 85). All communications between regions is across the public Internet. Therefore, you should use the appropriate encryption methods to protect your data. Data transfer between regions is charged at the Internet data transfer rate for both the sending and the receiving instance. For more information, see Amazon EC2 Pricing - Data Transfer.

Availability Zones You can list the Availability Zones that are available to your account. For more information, see Describing Your Regions and Availability Zones (p. 9). When you launch an instance, you can select an Availability Zone or let us choose one for you. If you distribute your instances across multiple Availability Zones and one instance fails, you can design your application so that an instance in another Availability Zone can handle requests. You can also use Elastic IP addresses to mask the failure of an instance in one Availability Zone by rapidly remapping the address to an instance in another Availability Zone. For more information, see Elastic IP Addresses (EIP) (p. 489). To ensure that resources are distributed across the Availability Zones for a region, we independently map Availability Zones to identifiers for each account. For example, your Availability Zone us-east-1a might not be the same location as us-east-1a for another account. Note that there's no way for you to coordinate Availability Zones between accounts. As Availability Zones grow over time, our ability to expand them can become constrained. If this happens, we might restrict you from launching an instance in a constrained Availability Zone unless you already have an instance in that Availability Zone. Eventually, we might also remove the constrained Availability

API Version 2014-10-01 8

Amazon Elastic Compute Cloud User Guide for Linux Describing Your Regions and Availability Zones

Zone from the list of Availability Zones for new customers. Therefore, your account might have a different number of available Availability Zones in a region than another account.

Describing Your Regions and Availability Zones You can use the AWS Management Console or the command line interface to determine which regions and Availability Zones are available for your use. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3).

To find your regions and Availability Zones using the AWS Management Console 1. 2.

Open the AWS Management Console. From the navigation bar, view the options in the region selector.

3.

Open the Amazon EC2 console. Your Availability Zones are listed on the dashboard under Service Health, under Availability Zone Status.

API Version 2014-10-01 9

Amazon Elastic Compute Cloud User Guide for Linux Describing Your Regions and Availability Zones

To find your regions and Availability Zones using the AWS CLI 1.

Use the describe-regions command as follows to describe your regions. $ aws ec2 describe-regions { "Regions": [ { "Endpoint": "ec2.us-east-1.amazonaws.com", "RegionName": "us-east-1" }, { "Endpoint": "ec2.ap-southeast-1.amazonaws.com", "RegionName": "ap-southeast-1" }, { "Endpoint": "ec2.ap-southeast-2.amazonaws.com", "RegionName": "ap-southeast-2" }, ... ] }

2.

Use the describe-availability-zones command as follows to describe your Availability Zones within the us-east-1 region. $ aws ec2 describe-availability-zones --region us-east-1 { "AvailabilityZones": [ { "State": "available", "RegionName": "us-east-1", "Messages": [], "ZoneName": "us-east-1b" },

API Version 2014-10-01 10

Amazon Elastic Compute Cloud User Guide for Linux Specifying the Region for a Resource

{ "State": "available", "RegionName": "us-east-1", "Messages": [], "ZoneName": "us-east-1c" }, { "State": "available", "RegionName": "us-east-1", "Messages": [], "ZoneName": "us-east-1d" } ] }

To find your regions and Availability Zones using the Amazon EC2 CLI 1.

Use the ec2-describe-regions command as follows to describe your regions. PROMPT> ec2-describe-regions REGION us-east-1 ec2.us-east-1.amazonaws.com REGION ap-northeast-1 ec2.ap-northeast-1.amazonaws.com REGION ap-southeast-1 ec2.ap-southeast-1.amazonaws.com ..

2.

Use the ec2-describe-availability-zones command as follows to describe your Availability Zones within the us-east-1 region. PROMPT> ec2-describe-availability-zones --region us-east-1 AVAILABILITYZONE us-east-1a available us-east-1 AVAILABILITYZONE us-east-1b available us-east-1 AVAILABILITYZONE us-east-1c available us-east-1 AVAILABILITYZONE us-east-1d available us-east-1

Specifying the Region for a Resource Every time you create an Amazon EC2 resource, you can specify the region for the resource. You can specify the region for a resource using the AWS Management Console or the command line.

To specify the region for a resource using the console 1. 2.

Open the Amazon EC2 console. Use the region selector in the navigation bar.

API Version 2014-10-01 11

Amazon Elastic Compute Cloud User Guide for Linux Launching Instances in an Availability Zone

To specify the default region using the command line You can set the value of an environment variable to the desired regional endpoint (for example, https://ec2.us-west-1.amazonaws.com): • AWS_DEFAULT_REGION (AWS CLI) • EC2_URL (Amazon EC2 CLI) Alternatively, you can use the --region command line option with each individual command. For example, --region us-west-1. For more information about the endpoints for Amazon EC2, see Amazon Elastic Compute Cloud Endpoints.

Launching Instances in an Availability Zone When you launch an instance, select a region that puts your instances closer to specific customers, or meets the legal or other requirements you have. By launching your instances in separate Availability Zones, you can protect your applications from the failure of a single location. When you launch an instance, you can optionally specify an Availability Zone in the region that you are using. If you do not specify an Availability Zone, we select one for you. When you launch your initial instances, we recommend that you accept the default Availability Zone, because this enables us to select the best Availability Zone for you based on system health and available capacity. If you launch additional instances, only specify an Availability Zone if your new instances must be close to, or separated from, your running instances.

To specify an Availability Zone for your instance using the console 1.

Open the Amazon EC2 console.

2.

On the dashboard, click Launch Instance. API Version 2014-10-01 12

Amazon Elastic Compute Cloud User Guide for Linux Migrating an Instance to Another Availability Zone

3.

Follow the directions for the wizard. On the Configure Instance Details page, do the following: • [EC2-Classic] Select one of the Availability Zone options from the list, or select No Preference to enable us to select the best one for you.

• [EC2-VPC] Select one of the subnet options from the list, or select No preference (default subnet in any Availability Zone) to enable us to select the best one for you.

To specify an Availability Zone for your instance using the AWS CLI You can use the run-instances command with one of the following options: • [EC2-Classic] --placement • [EC2-VPC] --subnet-id

To specify an Availability Zone for your instance using the Amazon EC2 CLI You can use the ec2-run-instances command with one of the following options: • [EC2-Classic] --availability-zone • [EC2-VPC] --subnet

Migrating an Instance to Another Availability Zone If you need to, you can migrate an instance from one Availability Zone to another. For example, if you are trying to modify the instance type of your instance and we can't launch an instance of the new instance type in the current Availability Zone, you could migrate the instance to an Availability Zone where we can launch an instance of that instance type. The migration process involves creating an AMI from the original instance, launching an instance in the new Availability Zone, and updating the configuration of the new instance, as shown in the following procedure.

To migrate an instance to another Availability Zone 1.

Create an AMI from the instance. The procedure depends on the operating system and the type of root device volume for the instance. For more information, see the documentation that corresponds to your operating system and root device volume: • Creating an Amazon EBS-Backed Linux AMI (p. 74) • Creating an Instance Store-Backed Linux AMI (p. 77) • Creating an Amazon EBS-Backed Windows AMI • Creating an Instance Store-Backed Windows AMI

2.

[EC2-VPC] If you need to preserve the private IP address of the instance, you must delete the subnet in the current Availability Zone and then create a subnet in the new Availability Zone with the same IP address range as the original subnet. Note that you must terminate all instances in a subnet before you can delete it. Therefore, you should move all instances in the current subnet to the new subnet. API Version 2014-10-01 13

Amazon Elastic Compute Cloud User Guide for Linux Root Device Volume

3.

4. 5.

6.

Launch an instance from the AMI that you just created, specifying the new Availability Zone or subnet. You can use the same instance type as the original instance, or select a new instance type. For more information, see Launching Instances in an Availability Zone (p. 12). If the original instance has an associated Elastic IP address, associate it with the new instance. For more information, see Associating an Elastic IP Address with a Different Running Instance (p. 492). If the original instance is a Reserved Instance, change the Availability Zone for your reservation. (If you also changed the instance type, you can also change the instance type for your reservation.) For more information, see Submitting Modification Requests (p. 224). (Optional) Terminate the original instance. For more information, see Terminating an Instance (p. 315).

Amazon EC2 Root Device Volume When you launch an instance, the root device volume contains the image used to boot the instance. When we introduced Amazon EC2, all AMIs were backed by Amazon EC2 instance store, which means the root device for an instance launched from the AMI is an instance store volume created from a template stored in Amazon S3. After we introduced Amazon EBS, we introduced AMIs that are backed by Amazon EBS. This means that the root device for an instance launched from the AMI is an Amazon EBS volume created from an Amazon EBS snapshot.You can choose between AMIs backed by Amazon EC2 instance store and AMIs backed by Amazon EBS. We recommend that you use AMIs backed by Amazon EBS, because they launch faster and use persistent storage. Topics • Root Device Storage Concepts (p. 14) • Choosing an AMI by Root Device Type (p. 16) • Determining the Root Device Type of Your Instance (p. 17) • Changing the Root Device Volume to Persist (p. 17)

Root Device Storage Concepts You can launch an instance from one of two types of AMIs: an instance store-backed AMI or an Amazon EBS-backed AMI. The description of an AMI includes which type of AMI it is; you'll see the root device referred to in some places as either ebs (for Amazon EBS-backed) or instance store (for instance store-backed). This is important because there are significant differences between what you can do with each type of AMI. For more information about these differences, see Storage for the Root Device (p. 55). Instance Store-backed Instances Instances that use instance stores for the root device automatically have instance store volumes available, with one serving as the root device volume. When an instance is launched, the image that is used to boot the instance is copied to the root volume (typically sda1). Any data on the instance store volumes persists as long as the instance is running, but this data is deleted when the instance is terminated (instance storebacked instances do not support the Stop action) or if it fails (such as if an underlying drive has issues).

API Version 2014-10-01 14

Amazon Elastic Compute Cloud User Guide for Linux Root Device Storage Concepts

After an instance store-backed instance fails or terminates, it cannot be restored. If you plan to use Amazon EC2 instance store-backed instances, we highly recommend that you distribute the data on your instance stores across multiple Availability Zones. You should also back up the data on your instance store volumes to persistent storage on a regular basis. For more information, see Amazon EC2 Instance Store (p. 581). Amazon EBS-backed Instances Instances that use Amazon EBS for the root device automatically have an Amazon EBS volume attached. When you launch an Amazon EBS-backed instance, we create an Amazon EBS volume for each Amazon EBS snapshot referenced by the AMI you use. You can optionally use other Amazon EBS volumes or instance store volumes.

An Amazon EBS-backed instance can be stopped and later restarted without affecting data stored in the attached volumes. There are various instance– and volume-related tasks you can do when an Amazon EBS-backed instance is in a stopped state. For example, you can modify the properties of the instance, you can change the size of your instance or update the kernel it is using, or you can attach your root volume to a different running instance for debugging or any other purpose. By default, the root device volume and the other Amazon EBS volumes attached when you launch an Amazon EBS-backed instance are automatically deleted when the instance terminates. For information about how to change this behavior when you launch an instance, see Changing the Root Device Volume to Persist (p. 17). By default, any Amazon EBS volumes that you attach to a running instance are detached with their data intact when the instance terminates. You can attach a detached volume to any running instance. If an Amazon EBS-backed instance fails, you can restore your session by following one of these methods: • Stop and then start again.

API Version 2014-10-01 15

Amazon Elastic Compute Cloud User Guide for Linux Choosing an AMI by Root Device Type

• Automatically snapshot all relevant volumes and create a new AMI. For more information, see Creating an Amazon EBS-Backed Linux AMI (p. 74). • Attach the volume to the new instance by following these steps: 1. Create a snapshot of the root volume. 2. Register a new AMI using the snapshot. 3. Launch a new instance from the new AMI. 4. Detach the remaining Amazon EBS volumes from the old instance. 5. Reattach the Amazon EBS volumes to the new instance.

We recommend using either the first or the second method for failed instances with normal volume size, and the third method for failed instances with large volumes.

Choosing an AMI by Root Device Type The AMI that you specify when you launch your instance determines the type of root device volume that your instance has.

To choose an Amazon EBS-backed AMI using the console 1. 2. 3. 4. 5.

Open the Amazon EC2 console. In the navigation pane, click AMIs. From the filter lists, select the image type (such as Public images), the operating system (such as Amazon Linux), and EBS images. (Optional) To get additional information to help you make your choice, click the Show/Hide Columns icon, update the columns to display, and click Close. Choose an AMI and write down its AMI ID.

To choose an instance store-backed AMI using the console 1. 2. 3. 4. 5.

Open the Amazon EC2 console. In the navigation pane, click AMIs. From the filter lists, select the image type (such as Public images), the operating system (such as Amazon Linux), and Instance store images. (Optional) To get additional information to help you make your choice, click the Show/Hide Columns icon, update the columns to display, and click Close. Choose an AMI and write down its AMI ID.

To verify the type of the root device volume of an AMI using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • describe-images (AWS CLI) • ec2-describe-images (Amazon EC2 CLI) • Get-EC2Image (AWS Tools for Windows PowerShell)

API Version 2014-10-01 16

Amazon Elastic Compute Cloud User Guide for Linux Determining the Root Device Type of Your Instance

Determining the Root Device Type of Your Instance To determine the root device type of an instance using the console 1.

Open the Amazon EC2 console.

2. 3.

In the navigation pane, click Instances, and select the instance. Check the value of Root device type in the Description tab as follows: • If the value is ebs, this is an Amazon EBS-backed instance. • If the value is instance store, this is an instance store-backed instance.

To determine the root device type of an instance using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • describe-instances (AWS CLI) • ec2-describe-instances (Amazon EC2 CLI) • Get-EC2Instance (AWS Tools for Windows PowerShell)

Changing the Root Device Volume to Persist By default, the root device volume for an AMI backed by Amazon EBS is deleted when the instance terminates. To change the default behavior, set the DeleteOnTermination attribute to false using a block device mapping.

Changing the Root Volume to Persist Using the Console Using the console, you can change the DeleteOnTermination attribute when you launch an instance. To change this attribute for a running instance, you must use the command line.

To change the root device volume of an instance to persist at launch using the console 1.

Open the Amazon EC2 console.

2.

From the Amazon EC2 console dashboard, click Launch Instance.

3. 4. 5.

On the Choose an Amazon Machine Image (AMI) page, choose the AMI to use and click Select. Follow the wizard to complete the Choose an Instance Type and Configure Instance Details pages. On the Add Storage page, deselect the Delete On Termination check box for the root volume.

6.

Complete the remaining wizard pages, and then click Launch.

You can verify the setting by viewing details for the root device volume on the instance's details pane. Next to Block devices, click the entry for the root device volume. By default, Delete on termination is True. If you change the default behavior, Delete on termination is False.

API Version 2014-10-01 17

Amazon Elastic Compute Cloud User Guide for Linux Changing the Root Device Volume to Persist

Changing the Root Volume of an Instance to Persist Using the AWS CLI Using the AWS CLI, you can change the DeleteOnTermination attribute when you launch an instance or while the instance is running. The root device is typically /dev/sda1 (Linux) or xvda (Windows).

Example at Launch Use the run-instances command to preserve the root volume by including a block device mapping that sets its DeleteOnTermination attribute for to false. $ aws ec2 run-instances --image-id ami-1a2b3c4d --block-device-mappings '[{"DeviceName":"/dev/sda1","Ebs":{"DeleteOnTermination":false}}]" other para meters...

You can confirm that DeleteOnTermination is false by using the describe-instances command and looking for the BlockDeviceMappings entry for /dev/sda1 in the command output, as shown here. ... "BlockDeviceMappings": [ { "DeviceName": "/dev/sda1", "Ebs": { "Status": "attached", "DeleteOnTermination": false, "VolumeId": "vol-877166c8", "AttachTime": "2013-07-19T02:42:39.000Z" } } ...

Example While the Instance is Running Use the modify-instance-attribute command to preserve the root volume by including a block device mapping that sets its DeleteOnTermination attribute to false. $ aws ec2 modify-instance-attribute --instance-id i-5203422c --block-devicemappings '[{"DeviceName":"/dev/sda1","Ebs":{"DeleteOnTermination":false}}]'

Changing the Root Volume of an Instance to Persist Using the Amazon EC2 CLI Using the Amazon EC2 CLI, you can change the DeleteOnTermination attribute when you launch an instance or while the instance is running. The root device is typically /dev/sda1 (Linux) or xvda (Windows).

Example at Launch Use the ec2-run-instances command to include a block device mapping that sets the DeleteOnTermination flag for the root device to false. Include the -v option to run the command in verbose mode. $ ec2-run-instances ami-1a2b3c4d -v

-b "/dev/sda1=::false" other parameters...

API Version 2014-10-01 18

Amazon Elastic Compute Cloud User Guide for Linux Changing the Root Device Volume to Persist

By running the command in verbose mode, you can see the underlying request and response, and confirm that DeleteOnTermination is false, as shown here. ... /dev/sda1 false ...

Example While the Instance is Running Use the ec2-modify-instance-attribute command to preserve the root volume by setting its DeleteOnTermination attribute to false. $ ec2-modify-instance-attribute i-5203422c -b "/dev/sda1=::false"

API Version 2014-10-01 19

Amazon Elastic Compute Cloud User Guide for Linux Sign Up for AWS

Setting Up with Amazon EC2 If you've already signed up for Amazon Web Services (AWS), you can start using Amazon EC2 immediately. You can open the Amazon EC2 console, click Launch Instance, and follow the steps in the launch wizard to launch your first instance. If you haven't signed up for AWS yet, or if you need assistance launching your first instance, complete the following tasks to get set up to use Amazon EC2: 1. Sign Up for AWS (p. 20) 2. Create an IAM User (p. 21) 3. Create a Key Pair (p. 22) 4. Create a Virtual Private Cloud (VPC) (p. 24) 5. Create a Security Group (p. 24)

Sign Up for AWS When you sign up for Amazon Web Services (AWS), your AWS account is automatically signed up for all services in AWS, including Amazon EC2. You are charged only for the services that you use. With Amazon EC2, you pay only for what you use. If you are a new AWS customer, you can get started with Amazon EC2 for free. For more information, see AWS Free Tier. If you have an AWS account already, skip to the next task. If you don't have an AWS account, use the following procedure to create one.

To create an AWS account 1.

Open 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 phone keypad.

Note your AWS account number, because you'll need it for the next task.

API Version 2014-10-01 20

Amazon Elastic Compute Cloud User Guide for Linux Create an IAM User

Create an IAM User Services in AWS, such as Amazon EC2, require that you provide credentials when you access them, so that the service can determine whether you have permission to access its resources. The console requires your password. You can create access keys for your AWS account to access the command line interface or API. However, we don't recommend that you access AWS using the credentials for your AWS account; we recommend that you use AWS Identity and Access Management (IAM) instead. Create an IAM user, and then add the user to an IAM group with administrative permissions or and grant this user administrative permissions. You can then access AWS using a special URL and the credentials for the IAM user. If you signed up for AWS but have not created an IAM user for yourself, you can create one using the IAM console.

To create the Administrators group 1.

Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/.

2. 3.

In the navigation pane, click Groups and then click Create New Group. In the Group Name box, type Administrators and then click Next Step.

4. 5.

In the Select Policy Template section, click Select next to the Administrator Access policy template. Click Next Step and then click Create Group.

Your new group is listed under Group Name.

To create the IAM user, add the user to the Administrators group, and create a password for the user 1. 2. 3.

In the navigation pane, click Users and then click Create New Users. In box 1, type a user name and then click Create. Click Download Credentials and save your access key in a secure place.You will need your access key for programmatic access to AWS using the AWS CLI, the AWS SDKs, or the HTTP APIs.

Note You cannot retrieve the secret access key after you complete this step; if you misplace it you must create a new one. After you have downloaded your access key, click Close. 4. 5. 6.

In the content pane, under User Name, click the name of the user you just created. (You might need to scroll down to find the user in the list.) In the content pane, in the Groups section, click Add User to Groups. Select the Administrators group and then click Add to Groups.

7.

In the content pane, in the Security Credentials section (you might need to scroll down to find this section), under Sign-In Credentials, click Manage Password.

8.

Select Assign a custom password and then type and confirm a password. When you are finished, click Apply.

To sign in as this new IAM user, sign out of the AWS console, then use the following URL, where your_aws_account_id is your AWS account number without the hyphens (for example, if your AWS account number is 1234-5678-9012, your AWS account ID is 123456789012): https://your_aws_account_id.signin.aws.amazon.com/console/

API Version 2014-10-01 21

Amazon Elastic Compute Cloud User Guide for Linux Create a Key Pair

Enter the IAM user name and password that you just created. When you're signed in, the navigation bar displays "your_user_name @ your_aws_account_id". If you don't want the URL for your sign-in page to contain your AWS account ID, you can create an account alias. From the IAM dashboard, click Create Account Alias and enter an alias, such as your company name. To sign in after you create an account alias, use the following URL: https://your_account_alias.signin.aws.amazon.com/console/

To verify the sign-in link for IAM users for your account, open the IAM console and check under IAM users sign-in link on the dashboard. For more information about IAM, see IAM and Amazon EC2 (p. 430).

Create a Key Pair AWS uses public-key cryptography to secure the login information for your instance. A Linux instance has no password; you use a key pair to log in to your instance securely. You specify the name of the key pair when you launch your instance, then provide the private key when you log in using SSH. If you haven't created a key pair already, you can create one using the Amazon EC2 console. Note that if you plan to launch instances in multiple regions, you'll need to create a key pair in each region. For more information about regions, see Regions and Availability Zones (p. 7).

To create a key pair 1. 2.

Open the Amazon EC2 console. From the navigation bar, select a region for the key pair. You can select any region that's available to you, regardless of your location. However, key pairs are specific to a region; for example, if you plan to launch an instance in the US West (Oregon) region, you must create a key pair for the instance in the US West (Oregon) region.

API Version 2014-10-01 22

Amazon Elastic Compute Cloud User Guide for Linux Create a Key Pair

3. 4.

Click Key Pairs in the navigation pane. Click Create Key Pair.

5.

Enter a name for the new key pair in the Key pair name field of the Create Key Pair dialog box, and then click Create. Choose a name that is easy for you to remember, such as your IAM user name, followed by -key-pair, plus the region name. For example, me-key-pair-uswest2.

6.

The private key file is automatically downloaded by your browser. The base file name is the name you specified as the name of your key pair, and the file name extension is .pem. Save the private key file in a safe place.

Important This is the only chance for you to save the private key file. You'll need to provide the name of your key pair when you launch an instance and the corresponding private key each time you connect to the instance. 7.

If you will use an SSH client on a Mac or Linux computer to connect to your Linux instance, use the following command to set the permissions of your private key file so that only you can read it. $ chmod 400 your_user_name-key-pair-region_name.pem

For more information, see Amazon EC2 Key Pairs (p. 413). To connect to your instance using your key pair To your Linux instance from a computer running Mac or Linux, you'll specify the .pem file to your SSH client with the -i option and the path to your private key. To connect to your Linux instance from a computer running Windows, you can use either MindTerm or PuTTY. If you plan to use PuTTY, you'll need to install it and use the following procedure to convert the .pem file to a .ppk file.

(Optional) To prepare to connect to a Linux instance from Windows using PuTTY 1. 2. 3.

Download and install PuTTY from http://www.chiark.greenend.org.uk/~sgtatham/putty/. Be sure to install the entire suite. Start PuTTYgen (for example, from the Start menu, click All Programs > PuTTY > PuTTYgen). Under Type of key to generate, select SSH-2 RSA.

4.

Click Load. By default, PuTTYgen displays only files with the extension .ppk. To locate your .pem file, select the option to display files of all types.

5.

Select the private key file that you created in the previous procedure and click Open. Click OK to dismiss the confirmation dialog box.

6.

Click Save private key. PuTTYgen displays a warning about saving the key without a passphrase. Click Yes. Specify the same name for the key that you used for the key pair. PuTTY automatically adds the .ppk file extension.

7.

API Version 2014-10-01 23

Amazon Elastic Compute Cloud User Guide for Linux Create a Virtual Private Cloud (VPC)

Create a Virtual Private Cloud (VPC) Amazon VPC enables you to launch AWS resources into a virtual network that you've defined. If you have a default VPC, you can skip this section and move to the next task, Create a Security Group (p. 24). To determine whether you have a default VPC, see Supported Platforms in the Amazon EC2 Console (p. 471). Otherwise, you can create a nondefault VPC in your account using the steps below.

Important If your account supports EC2-Classic in a region, then you do not have a default VPC in that region. T2 instances must be launched into a VPC.

To create a nondefault VPC 1. 2.

Open the Amazon VPC console at https://console.aws.amazon.com/vpc/. From the navigation bar, select a region for the VPC. VPCs are specific to a region, so you should select the same region in which you created your key pair.

3. 4.

On the VPC dashboard, click Start VPC Wizard. On the Step 1: Select a VPC Configuration page, ensure that VPC with a Single Public Subnet is selected, and click Select. On the Step 2: VPC with a Single Public Subnet page, enter a friendly name for your VPC in the VPC name field. Leave the other default configuration settings, and click Create VPC. On the confirmation page, click OK.

5.

For more information about Amazon VPC, see What is Amazon VPC? in the Amazon VPC User Guide.

Create a Security Group Security groups act as a firewall for associated instances, controlling both inbound and outbound traffic at the instance level. You must add rules to a security group that enable you to connect to your instance from your IP address using SSH. You can also add rules that allow inbound and outbound HTTP and HTTPS access from anywhere. Note that if you plan to launch instances in multiple regions, you'll need to create a security group in each region. For more information about regions, see Regions and Availability Zones (p. 7).

Tip You'll need the public IP address of your local computer, which you can get using a service. For example, we provide the following service: http://checkip.amazonaws.com/. To locate another service that provides your IP address, use the search phrase "what is my IP address." If you are connecting through an Internet service provider (ISP) or from behind a firewall without a static IP address, you need to find out the range of IP addresses used by client computers.

To create a security group with least privilege 1.

Open the Amazon EC2 console.

2.

From the navigation bar, select a region for the security group. Security groups are specific to a region, so you should select the same region in which you created your key pair.

API Version 2014-10-01 24

Amazon Elastic Compute Cloud User Guide for Linux Create a Security Group

3. 4. 5.

6.

Click Security Groups in the navigation pane. Click Create Security Group. Enter a name for the new security group and a description. Choose a name that is easy for you to remember, such as your IAM user name, followed by _SG_, plus the region name. For example, me_SG_uswest2. In the VPC list, ensure that your default VPC is selected; it's marked with an asterisk (*).

Note If your account supports EC2-Classic, select the VPC that you created in the previous task. 7.

On the Inbound tab, create the following rules (click Add Rule for each new rule), and then click Create: • Select HTTP from the Type list, and make sure that Source is set to Anywhere (0.0.0.0/0). • Select HTTPS from the Type list, and make sure that Source is set to Anywhere (0.0.0.0/0). • Select SSH from the Type list. In the Source box, ensure Custom IP is selected, and specify the public IP address of your computer or network in CIDR notation.To specify an individual IP address in CIDR notation, add the routing prefix /32. For example, if your IP address is 203.0.113.25, specify 203.0.113.25/32. If your company allocates addresses from a range, specify the entire range, such as 203.0.113.0/24.

Caution For security reasons, we don't recommend that you allow SSH access from all IP addresses (0.0.0.0/0) to your instance, except for testing purposes and only for a short time.

For more information, see Amazon EC2 Security Groups (p. 421).

API Version 2014-10-01 25

Amazon Elastic Compute Cloud User Guide for Linux

Getting Started with Amazon EC2 Linux Instances Let's get started with Amazon Elastic Compute Cloud (Amazon EC2) by launching, connecting to, and using a Linux instance. We'll use the AWS Management Console, a point-and-click web-based interface, to launch and connect to a Linux instance.

Important Before you begin, be sure that you've completed the steps in Setting Up with Amazon EC2. The instance is an Amazon EBS-backed instance (meaning that the root volume is an Amazon EBS volume). We'll also create and attach an additional Amazon EBS volume. You can either specify the Availability Zone in which to launch your instance, or let us select an Availability Zone for you. When you launch your instance, you secure it by specifying a key pair and security group. (You created these when getting set up.) When you connect to your instance, you must specify the private key of the key pair that you specified when launching your instance.

To complete this exercise, perform the following tasks: 1. Launch an Amazon EC2 Instance (p. 27) 2. Connect to Your Instance (p. 28) 3. (Optional) Add a Volume to Your Instance (p. 31) 4. Clean Up Your Instance and Volume (p. 34)

API Version 2014-10-01 26

Amazon Elastic Compute Cloud User Guide for Linux Step 1: Launch an Instance

Related Topics • If you'd prefer to launch a Windows instance, see this tutorial in the Amazon EC2 User Guide for Microsoft Windows Instances: Getting Started with Amazon EC2 Windows Instances. • If you'd prefer to use the AWS CLI, see this tutorial in the AWS Command Line Interface User Guide: Using Amazon EC2 through the AWS CLI. • If you'd prefer to use the Amazon EC2 CLI, see this tutorial in the Amazon EC2 Command Line Reference: Launching an Instance Using the Amazon EC2 CLI.

Launch an Amazon EC2 Instance You can launch a Linux instance using the AWS Management Console as described in this topic. Before you begin, be sure that you've completed the steps in Get Set Up for Amazon EC2. After you've launched your instance, you can connect to it and use it. For more information, see Connect to Your Instance (p. 28). If you'd prefer to launch and connect to a Windows instance, see Getting Started with Amazon EC2 Windows Instances.

Important When you sign up for AWS, you can get started with Amazon EC2 for free using the AWS Free Tier. If you created your AWS account less than 12 months ago, and have not already exceeded the free tier benefits for Amazon EC2 and Amazon EBS, it will not cost you anything to complete this tutorial, because we help you select options that are within the free tier benefits. Otherwise, you'll incur the standard Amazon EC2 usage fees from the time that you launch the instance until you terminate the instance (which is the final task of this tutorial), even if it remains idle. The total charges to complete this tutorial are minimal (typically only a few dollars). The following procedure is intended to help you launch your first instance quickly and doesn't go through all possible options. For more information about the advanced options, see Launching an Instance.

To launch an instance 1. 2. 3.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. From the console dashboard, click Launch Instance. The Choose an Amazon Machine Image (AMI) page displays a list of basic configurations called Amazon Machine Images (AMIs) that serve as templates for your instance. Select the 64-bit Amazon Linux AMI. Notice that this configuration is marked "Free tier eligible."

4.

On the Choose an Instance Type page, you can select the hardware configuration of your instance. The t2.micro instance type is selected by default. Alternatively, select All generations from the filter list, and then select the t1.micro instance type. Note that these are the only instance types eligible for the free tier.

Note T2 instances must be launched into a VPC. If your AWS account supports EC2-Classic and you do not have any VPCs, the launch wizard creates a VPC for you. Otherwise, if you have one or more VPCs, click Next: Configure Instance Details to select a VPC and subnet. 5. 6.

Click Review and Launch to let the wizard complete the other configuration settings for you. On the Review Instance Launch page, under Security Groups, you'll see that the wizard created and selected a security group for you. Instead, select the security group that you created when getting set up using the following steps: a.

Click Edit security groups.

b.

On the Configure Security Group page, ensure the Select an existing security group option is selected. Select your security group from the list of existing security groups, and click Review and Launch.

c.

API Version 2014-10-01 27

Amazon Elastic Compute Cloud User Guide for Linux Step 2: Connect to Your Instance

7. 8.

On the Review Instance Launch page, click Launch. In the Select an existing key pair or create a new key pair dialog box, select Choose an existing key pair, then select the key pair you created when getting set up. Alternatively, you can create a new key pair. Select Create a new key pair, enter a name for the key pair, and then click Download Key Pair. This is the only chance for you to save the private key file, so be sure to download it. Save the private key file in a safe place. You'll need to provide the name of your key pair when you launch an instance and the corresponding private key each time you connect to the instance. A key pair enables you to connect to a Linux instance through SSH. Therefore, don't select the Proceed without a key pair option. If you launch your instance without a key pair, then you can't connect to it. When you are ready, select the acknowledgment check box, and then click Launch Instances.

9.

A confirmation page lets you know that your instance is launching. Click View Instances to close the confirmation page and return to the console.

10. On the Instances screen, you can view the status of your instance. It takes a short time for an instance to launch. When you launch an instance, its initial state is pending. After the instance starts, its state changes to running, and it receives a public DNS name. (If the Public DNS column is hidden, click the Show/Hide icon and select Public DNS.)

Connect to Your Instance After you launch your instance, you can connect to it and use it the way that you'd use a computer sitting in front of you.

Note It may take a couple of minutes after launch for your running instance to finish provisioning so that you can connect to it. Check that your instance has passed its status checks - you can view this information in the Status Checks column on the Instances page. If you receive an error while attempting to connect to your instance, see Troubleshooting Connecting to Your Instance. Before you try to connect to your instance, be sure that you've completed the following tasks: • Get the public DNS name of the instance You can get the public DNS for your instance using the Amazon EC2 console (check the Public DNS column; if this column is hidden, click the Show/Hide icon and select Public DNS). If you prefer, you can use the describe-instances (AWS CLI) or ec2-describe-instances (Amazon EC2 CLI) command. • Locate the private key You'll need the fully-qualified path of the .pem file for the key pair that you specified when you launched the instance. • Enable inbound SSH traffic from your IP address to your instance Ensure that the security group associated with your instance allows incoming SSH traffic from your IP address. For more information, see Authorizing Network Access to Your Instances.

Important Your default security group does not allow incoming SSH traffic by default.

There are several ways to connect to a Linux instance. Choose the method that meets your needs: • Option 1: Connect Using Your Browser (p. 29) • Option 2: Connect from Windows Using PuTTY (p. 30) • Option 3: Connect from Mac or Linux Using an SSH Client (p. 31) API Version 2014-10-01 28

Amazon Elastic Compute Cloud User Guide for Linux Option 1: Connect Using Your Browser

Next Step After you've successfully launched and connected to your instance, you can do any of the following: • Continue to the next step in this tutorial, Add a Volume to Your Instance (p. 31). • Continue using this instance with a different tutorial, such as Installing a LAMP Web Server or Hosting a WordPress Blog. • Skip to the last step in this tutorial, Clean Up Your Instance and Volume (p. 34), to terminate the instance so that you don't continue to incur charges.

Option 1: Connect Using Your Browser You must have Java installed and enabled in the browser. If you don't have Java already, you can contact your system administrator to get it installed, or follow the steps outlined in the following pages: Install Java and Enable Java in your web browser.

To connect to your Linux instance using a web browser 1. 2. 3. 4.

From the Amazon EC2 console, click Instances in the navigation pane. Select the instance, and then click Connect. Click A Java SSH client directly from my browser (Java required). Amazon EC2 automatically detects the public DNS name of your instance and populates Public DNS for you. It also detects the key pair that you specified when you launched the instance. Complete the following, and then click Launch SSH Client. a.

In User name, enter ec2-user.

Tip For Amazon Linux, the user name is ec2-user. For RHEL5, the user name is either root or ec2-user. For Ubuntu, the user name is ubuntu. For Fedora, the user name is either fedora or ec2-user. For SUSE Linux, the user name is root. Otherwise, if ec2-user and root don't work, check with your AMI provider. b.

In Private key path, enter the fully qualified path to your private key (.pem) file, including the key pair name; for example: C:\KeyPairs\my-key-pair.pem

c.

5. 6.

7. 8.

(Optional) Click Store in browser cache to store the location of the private key in your browser cache. This enables Amazon EC2 to detect the location of the private key in subsequent browser sessions, until you clear your browser's cache.

If necessary, click Yes to trust the certificate, and click Run to run the MindTerm client. If this is your first time running MindTerm, a series of dialog boxes asks you to accept the license agreement, to confirm setup for your home directory, and to confirm setup of the known hosts directory. Confirm these settings. A dialog prompts you to add the host to your set of known hosts. If you do not want to store the host key information on your local computer, click No. A window opens and you are connected to your instance.

Note If you clicked No in the previous step, you'll see the following message, which is expected: Verification of server key disabled in this session.

API Version 2014-10-01 29

Amazon Elastic Compute Cloud User Guide for Linux Option 2: Connect from Windows Using PuTTY

Option 2: Connect from Windows Using PuTTY PuTTY doesn't use .pem files, it uses .ppk files. If you haven't already generated a .ppk file, do so now. For more information, see To prepare to connect to a Linux instance from Windows using PuTTY.

To connect to your Linux instance using PuTTY 1.

Start PuTTY (from the Start menu, click All Programs > PuTTY > PuTTY).

2.

In the Category pane, select Session and complete the following fields:

3.

a.

In the Host Name box, enter ec2-user@public_dns_name.

b. c.

Under Connection type, select SSH. Ensure that Port is 22.

In the Category pane, expand Connection, expand SSH, and then select Auth. Complete the following: a. b.

Click Browse. Select the .ppk file that you generated for your key pair, and then click Open.

c.

Click Open to start the PuTTY session.

API Version 2014-10-01 30

Amazon Elastic Compute Cloud User Guide for Linux Option 3: Connect from Mac or Linux Using an SSH Client

4.

If this is the first time you have connected to this instance, PuTTY displays a security alert dialog box that asks whether you trust the host you are connecting to. Click Yes. A window opens and you are connected to your instance.

Option 3: Connect from Mac or Linux Using an SSH Client Your Mac or Linux computer most likely includes an SSH client by default. You can check for an SSH client by typing ssh at the command line. If your computer doesn't recognize the command, the OpenSSH project provides a free implementation of the full suite of SSH tools. For more information, see http://www.openssh.org. Open your command shell and run the following command: $ ssh -i /path/key_pair.pem ec2-user@public_dns_name

Tip For Amazon Linux, the user name is ec2-user. For RHEL5, the user name is either root or ec2-user. For Ubuntu, the user name is ubuntu. For Fedora, the user name is either fedora or ec2-user. For SUSE Linux, the user name is root. Otherwise, if ec2-user and root don't work, check with your AMI provider.

Add a Volume to Your Instance Now that you've launched and connected to your Linux instance, you can run the following command on your instance to view its mounted volumes. [ec2-user ~]$ df -h

For a micro instance, your output should look something like this.

API Version 2014-10-01 31

Amazon Elastic Compute Cloud User Guide for Linux Step 3: Add a Volume

Filesystem /dev/xvda1 tmpfs

Size 8.0G 298M

Used 1.1G 0

Avail Use% Mounted on 6.9G 14% / 298M 0% /dev/shm

The /dev/xvda1 volume is the root device volume. It contains the image used to boot the instance. Notice that there's some room to install additional software on your instance (only 14% of the file system is being used above). For example, you can use the yum command to download and install packages. If you need additional storage for your data, a simple solution is to add Amazon EBS volumes to your instance. An Amazon EBS volume serves as network-attached storage for your instance. Let's add a volume to the Linux instance that you've launched. First we'll use the EC2 console to create the volume and attach it to the instance, and then we'll mount the volume to make it available.

To create and attach an Amazon EBS volume 1. 2.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. In the navigation bar, select the region in which you created your instance, and then click Instances in the navigation pane. The console displays the list of current instances in that region. Select your Linux instance. In the Description tab in the bottom pane note the Availability Zone for the instance.

3.

In the navigation pane, under Elastic Block Store, click Volumes.

4.

Click Create Volume.

5.

Configure the following, and then click Create: • Select the General Purpose (SSD) volume type to create a General Purpose (SSD) EBS volume.

Note Some AWS accounts created before 2012 might have access to Availability Zones in useast-1, us-west-1, or ap-northeast-1 that do not support SSD volumes such as Provisioned IOPS (SSD) and General Purpose (SSD). If you are unable to create an SSD volume (or launch an instance with an SSD volume in its block device mapping) in one of these regions, try a different Availability Zone in the region. You can verify that an Availability Zone supports General Purpose (SSD) and Provisioned IOPS (SSD) volumes by creating a 1 GiB General Purpose (SSD) volume in that zone. • Enter the size of the volume you want to create. The free tier benefits for Amazon EBS include up to 30 GiB of storage; therefore, to avoid being charged for this tutorial, choose a volume size that will keep you from exceeding that limit. For example, if the boot volume for the instance you created uses an 8 GiB Amazon EBS volume, then make sure to create a volume that is less than or equal to 22 GiB. • Select the same Availability Zone that you used when you created your instance. Otherwise, you can't attach the volume to your instance.

6.

In the navigation pane, under Elastic Block Store, click Volumes. Notice that your newly created volume appears there and the state of the volume is available, so it's ready to be attached to an instance.

7.

Right-click the newly created volume and select Attach Volume.

8.

In the Attach Volume dialog box, configure the following, and then click Attach: • Start typing in the name or ID of your instance, then select it from the list of suggested options. • Specify an unused device name for that instance. We'll use /dev/sdf in this tutorial. If you select a different device name, be sure to note it as you'll need this information in the next procedure.

API Version 2014-10-01 32

Amazon Elastic Compute Cloud User Guide for Linux Step 3: Add a Volume

You'll notice that in the Details pane for your volume, the state of the volume is in-use, and the volume is attached to your instance with the device name /dev/sdf. However, if you return to your instance and run the df -h command again, you won't see the volume yet. That's because we need to mount the volume for df -h to see it. The lsblk command, however, can see all block devices attached to the instance.

Note Some Linux distributions do not provide the lsblk command by default. If the lsblk command does not work, you can use sudo fdisk -l | grep Disk instead. [ec2-user ~]$ lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT xvdf 202:80 0 22G 0 disk xvda1 202:1 0 8G 0 disk /

In the above example, lsblk reports that there are two block devices attached to the instance; xvda1 is mounted as the root file system (note the MOUNTPOINT value of /) and xvdf is not mounted at all.

To make a volume available 1.

Identify the device to mount. In the previous procedure, the new volume was attached to /dev/sdf. Depending on the block device drivers on your instance's operating system, the device may appear at a different location (such as /dev/xvdf in the previous example) than what you specified in the console (/dev/sdf); in some cases, even the trailing letter may change (for example, /dev/xvdj). Amazon Linux instances always create links from the device path that you specified in the console to the new device path, but other distributions (such as Ubuntu or Red Hat) are not as predictable. Use the lsblk command to list the available devices.

Note Some Linux distributions do not provide the lsblk command by default. If the lsblk command does not work, you can use sudo fdisk -l | grep Disk instead. [ec2-user ~]$ lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT xvdf 202:80 0 22G 0 disk xvda1 202:1 0 8G 0 disk /

In the above example, the xvdf device is not mounted. Sometimes when you create a volume from a snapshot, the data on the volume is contained in a partition (such as /dev/xvdf1) instead of the root of the volume. In such a case, you would mount the /dev/xvdf1 partition (the lsblk command output omits the /dev/ portion of the file path). In this example, there is an empty volume with no partition, so you will mount /dev/xvdf. 2.

Because you created an empty volume instead of restoring a volume from a snapshot in the previous procedure, you need to format the volume using mkfs before you can mount it. Use the following command to create an ext4 file system on the volume. Substitute the device name you used if you did not use /dev/xvdf when you attached the volume.

Caution This step assumes that you're mounting an empty volume. If you're mounting a volume that already has data on it (for example, a volume that was restored from a snapshot), don't use mkfs before mounting the volume (skip to the next step instead). Otherwise, you'll format the volume and delete the existing data. For more information, see Making the Volume Available on Linux.

Note SUSE Linux Enterprise Server 11 does not fully support ext4 file systems. If you chose a SLES 11 AMI for your instance, use ext3 in the following command instead.

API Version 2014-10-01 33

Amazon Elastic Compute Cloud User Guide for Linux Step 4: Clean Up

[ec2-user ~]$ sudo mkfs -t ext4 /dev/xvdf

3.

To mount the device as /mnt/my-data, run the following commands. [ec2-user ~]$ sudo mkdir /mnt/my-data [ec2-user ~]$ sudo mount /dev/xvdf /mnt/my-data

Be sure to specify the device name you identified in Step 1 (p. 33); otherwise, you might receive the following error when you run this mount command: "mount: you must specify the filesystem type". If you see this error, repeat Step 1 (p. 33) and use the correct device path (remember to add the /dev/ to the device name you get from the lsblk command). 4.

Now when you run the df -h command, you'll see output like the following. [ec2-user ~]$ df -h Filesystem /dev/xvda1 tmpfs /dev/xvdf

5.

Size 7.9G 298M 22G

Used Avail Use% Mounted on 1.1G 6.8G 14% / 0 298M 0% /dev/shm 0 22G 0% /mnt/my-data

To view the contents of the new volume, run the following command. [ec2-user ~]$ ls /mnt/my-data

At this point, you have completed the example architecture for this tutorial.You can continue to customize and use your instance for as long as you wish.

Important Remember, if you stayed within the free tier benefits, there are no charges. Otherwise, as soon as your instance starts to boot, you're billed for each hour or partial hour that you keep the instance running, even if the instance is idle. You'll stop incurring charges for a regular instance as soon as the instance status changes to shutting down or terminated. When you're finished with your instance, don't forget to clean up any resources you've used and terminate the instance, as shown in the next step, Clean Up Your Instance and Volume (p. 34).

Clean Up Your Instance and Volume After you've finished with the instance and the Amazon EBS volume that you created for this tutorial, you should clean up. First, terminate the instance, which detaches the volume from the instance, and then delete the volume. Terminating an instance effectively deletes it because you can't reconnect to an instance after you've terminated it. This differs from stopping the instance; when you stop an instance, it is shut down and you are not billed for hourly usage or data transfer (but you are billed for any Amazon EBS volume storage). Also, you can restart a stopped instance at any time. For more information about the differences between stopping and terminating an instance, see Stopping Instances.

To terminate the instance 1.

Locate your instance in the list of instances on the Instances page. If you can't find your instance, verify that you have selected the correct region. API Version 2014-10-01 34

Amazon Elastic Compute Cloud User Guide for Linux Step 4: Clean Up

2. 3.

Right-click the instance, and then click Terminate. Click Yes, Terminate when prompted for confirmation.

EBS volumes can persist even after your instance is terminated. If you created and attached an EBS volume in the previous step, it was detached when you terminated the instance. However, you must delete the volume, or you'll be charged for volume storage if the storage amount exceeds the benefits of the free tier. After you delete a volume, its data is gone and the volume can't be attached to any instance.

To delete the volume 1.

Locate the volume that you created in the list of volumes on the Volumes page. If you can't find your volume, verify that you have selected the correct region.

2. 3.

Right-click the volume, and then click Delete Volume. Click Yes, Delete when prompted for confirmation. Amazon EC2 begins deleting the volume.

API Version 2014-10-01 35

Amazon Elastic Compute Cloud User Guide for Linux

Best Practices for Amazon EC2 This checklist is intended to help you get the maximum benefit from and satisfaction with Amazon EC2.

Security and Network • Manage access to AWS resources and APIs using identity federation, IAM users, and IAM roles. Establish credential management policies and procedures for creating, distributing, rotating, and revoking AWS access credentials. For more information, see IAM Best Practices in the Using IAM guide. • Implement the least permissive rules for your security group. For more information, see Security Group Rules (p. 423). • Regularly patch, update, and secure the operating system and applications on your instance. For more information about updating Amazon Linux, see Managing Software on Your Linux Instance (p. 322). • Launch your instances into a VPC instead of EC2-Classic. Note that if you created your AWS account after 2013-12-04, we automatically launch your instances into a VPC. For more information about the benefits, see Amazon EC2 and Amazon Virtual Private Cloud (VPC) (p. 468).

Storage • Understand the implications of the root device type for data persistence, backup, and recovery. For more information, see Storage for the Root Device (p. 55). • Use separate Amazon EBS volumes for the operating system versus your data. Ensure that the volume with your data persists after instance termination. • Use the instance store available for your instance to store temporary data. Remember that the data stored in instance store is deleted when you stop or terminate your instance. If you use instance store for database storage, ensure that you have a cluster with a replication factor that ensures fault tolerance.

Resource Management • Use instance metadata and custom resource tags to track and identify your AWS resources. For more information, see Instance Metadata and User Data (p. 256) and Tagging Your Amazon EC2 Resources (p. 610). • View your current limits for Amazon EC2. Plan to request any limit increases in advance of the time that you'll need them. For more information, see Amazon EC2 Service Limits (p. 618).

Backup and Recovery • Regularly back up your instance using Amazon EBS snapshots (p. 559) or a backup tool. API Version 2014-10-01 36

Amazon Elastic Compute Cloud User Guide for Linux

• Deploy critical components of your application across multiple Availability Zones, and replicate your data appropriately. • Design your applications to handle dynamic IP addressing when your instance restarts. For more information, see Amazon EC2 Instance IP Addressing (p. 480). • Monitor and respond to events. For more information, see Monitoring Amazon EC2 (p. 343). • Ensure that you are prepared to handle failover. For a basic solution, you can manually attach a network interface or Elastic IP address to a replacement instance. For more information, see Elastic Network Interfaces (ENI) (p. 494). For an automated solution, you can use Auto Scaling. For more information, see the Auto Scaling Developer Guide. • Regularly test the process of recovering your instances and Amazon EBS volumes if they fail.

API Version 2014-10-01 37

Amazon Elastic Compute Cloud User Guide for Linux

Tutorial: Installing a LAMP Web Server The following procedures help you install the Apache web server with PHP and MySQL support on your Amazon EC2 instance (sometimes called a LAMP web server or LAMP stack). You can use this server to host a static website or deploy a dynamic PHP application that reads and writes information to a database. Prerequisites This tutorial assumes that you have already launched an instance with a public DNS name that is reachable from the Internet. For more information, see Launch an Amazon EC2 Instance (p. 27). You must also have configured your security group to allow SSH (port 22), HTTP (port 80), and HTTPS (port 443) connections. For more information about these prerequisites, see Setting Up with Amazon EC2 (p. 20).

Important These procedures are intended for use with Amazon Linux, but the commands and file locations are similar for Red Hat and CentOS. For more information about other distributions, see their specific documentation. If you are trying to set up a LAMP web server on an Ubuntu instance, this tutorial will not work for you. For information about LAMP web servers on Ubuntu, go to the Ubuntu community documentation ApacheMySQLPHP topic.

To install and start the LAMP web server 1.

Connect to your instance (p. 28).

2.

To ensure that all of your software packages are up to date, perform a quick software update on your instance. This process may take a few minutes, but it is important to make sure you have the latest security updates and bug fixes.

Note The -y option installs the updates without asking for confirmation. If you would like to examine the updates before installing, you can omit this option. [ec2-user ~]$ sudo yum update -y

3.

Now that your instance is current, you can install the Apache web server, MySQL, and PHP software packages. Use the yum groupinstall command to install multiple software packages and all related dependencies at the same time.

API Version 2014-10-01 38

Amazon Elastic Compute Cloud User Guide for Linux

[ec2-user ~]$ sudo yum groupinstall -y "Web Server" "MySQL Database" "PHP Support"

Note Non-Amazon Linux instances may have subtle differences in their group names. If the above command fails because of an invalid group name, use the yum grouplist command and scan the output for similar groups, such as "MySQL Database server" instead of "MySQL Database", and use the appropriate group name for your distribution. 4.

Install the php-mysql package. [ec2-user ~]$ sudo yum install -y php-mysql

5.

Start the Apache web server. [ec2-user ~]$ sudo service httpd start Starting httpd:

6.

[

OK

]

Use the chkconfig command to configure the Apache web server to start at each system boot. [ec2-user ~]$ sudo chkconfig httpd on

Tip The chkconfig command does not provide any confirmation message when you successfully enable a service. You can verify that httpd is on by running the following command. [ec2-user ~]$ chkconfig --list httpd httpd 0:off 1:off 2:on

3:on

4:on

5:on

6:off

Here, httpd is on in runlevels 2, 3, 4, and 5 (which is what you want to see). 7.

Test your web server. In a web browser, enter the public DNS address (or the public IP address) of your instance; you should see the Apache test page. You can get the public DNS for your instance using the Amazon EC2 console (check the Public DNS column; if this column is hidden, click the Show/Hide icon and select Public DNS).

Tip If you are unable to see the Apache test page, check that the security group you are using contains a rule to allow HTTP (port 80) traffic. For information about adding an HTTP rule to your security group, see Adding Rules to a Security Group (p. 426).

Important If you are not using Amazon Linux, you may also need to configure the firewall on your instance to allow these connections. For more information about how to configure the firewall, see the documentation for your specific distribution.

API Version 2014-10-01 39

Amazon Elastic Compute Cloud User Guide for Linux

Note This test page appears only when there is no content in /var/www/html. When you add content to the document root, your content appears at the public DNS address of your instance instead of this test page.

Apache httpd serves files that are kept in a directory called the Apache document root. The Amazon Linux Apache document root is /var/www/html, which is owned by root by default. [ec2-user ~]$ ls -l /var/www total 16 drwxr-xr-x 2 root root 4096 Jul 12 01:00 cgi-bin drwxr-xr-x 3 root root 4096 Aug 7 00:02 error drwxr-xr-x 2 root root 4096 Jan 6 2012 html drwxr-xr-x 3 root root 4096 Aug 7 00:02 icons

To allow ec2-user to manipulate files in this directory, you need to modify the ownership and permissions of the directory. There are many ways to accomplish this task; in this tutorial, you add a www group to your instance, and you give that group ownership of the /var/www directory and add write permissions for the group. Any members of that group will then be able to add, delete, and modify files for the web server.

To set file permissions 1.

Add the www group to your instance. [ec2-user ~]$ sudo groupadd www

2.

Add your user (in this case, ec2-user) to the www group. [ec2-user ~]$ sudo usermod -a -G www ec2-user

API Version 2014-10-01 40

Amazon Elastic Compute Cloud User Guide for Linux

Important You need to log out and log back in to pick up the new group.You can use the exit command, or close the terminal window. 3.

Log out and then log back in again, and verify your membership in the www group. a.

Log out. [ec2-user ~]$ exit

b.

Reconnect to your instance, and then run the following command to verify your membership in the www group. [ec2-user ~]$ groups ec2-user wheel www

4.

Change the group ownership of /var/www and its contents to the www group. [ec2-user ~]$ sudo chown -R root:www /var/www

5.

Change the directory permissions of /var/www and its subdirectories to add group write permissions and to set the group ID on future subdirectories. [ec2-user ~]$ sudo chmod 2775 /var/www [ec2-user ~]$ find /var/www -type d -exec sudo chmod 2775 {} +

6.

Recursively change the file permissions of /var/www and its subdirectories to add group write permissions. [ec2-user ~]$ find /var/www -type f -exec sudo chmod 0664 {} +

Now ec2_user (and any future members of the www group) can add, delete, and edit files in the Apache document root. Now you are ready to add content, such as a static website or a PHP application.

To test your LAMP web server If your server is installed and running, and your file permissions are set correctly, your ec2-user account should be able to create a simple PHP file in the /var/www/html directory that will be available from the Internet. 1.

Create a simple PHP file in the Apache document root. [ec2-user ~]$ echo "" > /var/www/html/phpinfo.php

Tip If you get a "Permission denied" error when trying to run this command, try logging out and logging back in again to pick up the proper group permissions that you configured in To set file permissions (p. 40).

API Version 2014-10-01 41

Amazon Elastic Compute Cloud User Guide for Linux

2.

In a web browser, enter the URL of the file you just created. This URL is the public DNS address of your instance followed by a forward slash and the file name. For example: http://my.public.dns.amazonaws.com/phpinfo.php

You should see the PHP information page.

Note If you do not see the above image, but instead see the phpinfo() source code, verify that the php package was installed properly. Your output may look slightly different, but look for php in the Installed Packages section. [ec2-user wordpress]$ yum list installed php Loaded plugins: priorities, security, update-motd, upgrade-helper amzn-main | 2.1 kB 00:00 amzn-updates | 2.3 kB 00:00 Installed Packages php.x86_64 5.3.27-1.0.amzn1 @amzn-updates

If this package is not listed as installed, install it with the following command, restart the httpd service, and reload the phpinfo.php page. [ec2-user wordpress]$ sudo yum install -y php [ec2-user wordpress]$ sudo service httpd restart

3.

Delete the phpinfo.php file. Although this can be useful information to you, it should not be broadcast to the Internet for security reasons. [ec2-user ~]$ rm /var/www/html/phpinfo.php

API Version 2014-10-01 42

Amazon Elastic Compute Cloud User Guide for Linux

To secure the MySQL server The default installation of the MySQL server has several features that are great for testing and development, but they should be disabled or removed for production servers.The mysql_secure_installation command walks you through the process of setting a root password and removing the insecure features from your installation. Even if you are not planning on using the MySQL server, performing this procedure is a good idea. 1.

Start the MySQL server so that you can run mysql_secure_installation. [ec2-user ~]$ sudo service mysqld start Initializing MySQL database: Installing MySQL system tables... OK Filling help tables... OK To start mysqld at boot time you have to copy support-files/mysql.server to the right place for your system PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER ! ... Starting mysqld:

2.

[

OK

]

Run mysql_secure_installation. [ec2-user ~]$ sudo mysql_secure_installation

a.

When prompted, enter a password for the root account. i. ii.

3.

Enter the current root password. By default, the root account does not have a password set, so press Enter. Type Y to set a password, and enter a secure password twice. For more information about creating a secure password, go to http://www.pctools.com/guides/password/. Make sure to store this password in a safe place.

b.

Type Y to remove the anonymous user accounts.

c.

Type Y to disable remote root login.

d. e.

Type Y to remove the test database. Type Y to reload the privilege tables and save your changes.

(Optional) Stop the MySQL server if you do not plan to use it right away. You can restart the server when you need it again. [ec2-user ~]$ sudo service mysqld stop Stopping mysqld:

4.

[

OK

]

(Optional) If you want the MySQL server to start at every boot, enter the following command. [ec2-user ~]$ sudo chkconfig mysqld on

API Version 2014-10-01 43

Amazon Elastic Compute Cloud User Guide for Linux

You should now have a fully functional LAMP web server. If you add content to the Apache document root at /var/www/html, you should be able to view that content at the public DNS address for your instance.

Related Topics For more information on transferring files to your instance or installing a WordPress blog on your web server, see the following topics: • Transferring Files to Your Linux Instance Using WinSCP (p. 306) • Transferring Files to Linux Instances from Linux Using SCP (p. 301) • Tutorial: Hosting a WordPress Blog with Amazon EC2 (p. 45) For more information about the Apache web server, go to http://httpd.apache.org/. For more information about the MySQL database server, go to http://www.mysql.com/. For more information about the PHP programming language, go to http://php.net/. If you are interested in registering a domain name for your web server, or transferring an existing domain name to this host, see Creating and Migrating Domains and Subdomains to Amazon Route 53 in the Amazon Route 53 Developer Guide.

API Version 2014-10-01 44

Amazon Elastic Compute Cloud User Guide for Linux

Tutorial: Hosting a WordPress Blog with Amazon EC2 The following procedures will help you install, configure, and secure a WordPress blog on your Amazon EC2 instance.

Important These procedures are intended for use with Amazon Linux, but the commands and file locations are similar for Red Hat and CentOS. For more information about other distributions, see their specific documentation. This tutorial is a good introduction to using Amazon EC2 in that you have full control over a web server that hosts your WordPress blog, which is not typical with a traditional hosting service. Of course, that means that you are responsible for updating the software packages and maintaining security patches for your server as well. For a more automated WordPress installation that does not require direct interaction with the web server configuration, the AWS CloudFormation service provides a WordPress template that can also get you started quickly. For more information, see Get Started in the AWS CloudFormation User Guide. If you'd prefer to host your WordPress blog on a Windows instance, see Deploying a WordPress Blog on Your Amazon EC2 Windows Instance in the Amazon EC2 User Guide for Microsoft Windows Instances. Prerequisites This tutorial assumes that you have launched an instance with a functional web server with PHP and MySQL support. Your Amazon EC2 security group should also allow HTTP and HTTPS traffic. If you do not already have a functional web server, see Tutorial: Installing a LAMP Web Server (p. 38) to create one and then return to this tutorial to install WordPress. For information about adding rules to your security group, see Adding Rules to a Security Group (p. 426).

To download and unzip the WordPress installation package 1.

Download the latest WordPress installation package with the wget command.The following command should always download the latest release. [ec2-user ~]$ wget https://wordpress.org/latest.tar.gz --2013-08-09 17:19:01-- https://wordpress.org/latest.tar.gz Resolving wordpress.org (wordpress.org)... 66.155.40.249, 66.155.40.250 Connecting to wordpress.org (wordpress.org)|66.155.40.249|:443... connected. HTTP request sent, awaiting response... 200 OK

API Version 2014-10-01 45

Amazon Elastic Compute Cloud User Guide for Linux

Length: 4028740 (3.8M) [application/x-gzip] Saving to: latest.tar.gz 100%[======================================>] 4,028,740

20.1MB/s

in 0.2s

2013-08-09 17:19:02 (20.1 MB/s) - latest.tar.gz saved [4028740/4028740]

2.

Unzip and unarchive the installation package. The installation folder is unzipped to a folder called wordpress. [ec2-user ~]$ tar -xzf latest.tar.gz [ec2-user ~]$ ls latest.tar.gz wordpress

To create a MySQL user and database for your WordPress installation Your WordPress installation needs to store information, such as blog post entries and user comments, in a database. This procedure will help you create a database for your blog and a user that is authorized to read and save information to that database. 1.

Start the MySQL server. [ec2-user ~]$ sudo service mysqld start

2.

Log in to the MySQL server as the root user. Enter your MySQL root password when prompted; this may be different than your root system password, or it may even be empty if you have not secured your MySQL server.

Important If you have not secured your MySQL server yet, it is very important that you do so. For more information, see To secure the MySQL server (p. 43). [ec2-user ~]$ mysql -u root -p Enter password:

3.

Create a user and password for your MySQL database. Your WordPress installation uses these values to communicate with your MySQL database. Enter the following command, substituting a unique user name and password. mysql> CREATE USER 'wordpress-user'@'localhost' IDENTIFIED BY 'your_strong_password'; Query OK, 0 rows affected (0.00 sec)

Make sure that you create a strong password for your user. Do not use the single quote character ( ' ) in your password, because this will break the preceding command. For more information about creating a secure password, go to http://www.pctools.com/guides/password/. Do not reuse an existing password, and make sure to store this password in a safe place. 4.

Create your database. Give your database a descriptive, meaningful name, such as wordpressdb.

API Version 2014-10-01 46

Amazon Elastic Compute Cloud User Guide for Linux

Note The punctuation marks surrounding the database name in the command below are called backticks. The backtick (`) key is usually located above the Tab key on a standard keyboard. Backticks are not always required, but they allow you to use otherwise illegal characters, such as hyphens, in database names. mysql> CREATE DATABASE `wordpress-db`; Query OK, 1 row affected (0.01 sec)

5.

Grant full privileges for your database to the WordPress user you created earlier. mysql> GRANT ALL PRIVILEGES ON `wordpress-db`.* TO "wordpress-user"@"local host"; Query OK, 0 rows affected (0.00 sec)

6.

Flush the MySQL privileges to pick up all of your changes. mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.01 sec)

7.

Exit the mysql client. mysql> exit Bye

To create and edit the wp-config.php file The WordPress installation folder contains a sample configuration file called wp-config-sample.php. In this procedure, you copy this file and edit it to fit your specific configuration. 1.

Copy the wp-config-sample.php file to a file called wp-config.php. This creates a new configuration file and keeps the original sample file intact as a backup. [ec2-user ~]$ cd wordpress/ [ec2-user wordpress]$ cp wp-config-sample.php wp-config.php

2.

Edit the wp-config.php file with your favorite text editor (such as nano or vim) and enter values for your installation. If you do not have a favorite text editor, nano is much easier for beginners to use. [ec2-user wordpress]$ nano wp-config.php

a.

Find the line that defines DB_NAME and change database_name_here to the database name you created in Step 4 (p. 46) of To create a MySQL user and database for your WordPress installation (p. 46). define('DB_NAME', 'wordpress-db');

API Version 2014-10-01 47

Amazon Elastic Compute Cloud User Guide for Linux

b.

Find the line that defines DB_USER and change username_here to the database user you created in Step 3 (p. 46) of To create a MySQL user and database for your WordPress installation (p. 46). define('DB_USER', 'wordpress-user');

c.

Find the line that defines DB_PASSWORD and change password_here to the strong password you created in Step 3 (p. 46) of To create a MySQL user and database for your WordPress installation (p. 46). define('DB_PASSWORD', 'your_strong_password');

d.

Find the section called Authentication Unique Keys and Salts. These KEY and SALT values provide a layer of encryption to the browser cookies that WordPress users store on their local machines. Basically, adding long, random values here makes your site more secure. Visit https://api.wordpress.org/secret-key/1.1/salt/ to randomly generate a set of key values that you can copy and paste into your wp-config.php file. To paste text into a PuTTY terminal, place the cursor where you want to paste the text and right-click your mouse inside the PuTTY terminal. For more information about security keys, go to http://codex.wordpress.org/Editing_wp-config.php#Security_Keys.

Note The values below are for example purposes only; do not use these values for your installation. define('AUTH_KEY', ' #U$$+[RXN8:b^-L 0(WU_+ c+WFkI~c]o]bHw+)/Aj[wTwSiZ)Y |;(^[Iw]Pi+LG#A4R?7N`YB3'); define('NONCE_KEY', 'P(g62HeZxEes|LnI^i=H,[XwK9I&[2s|:?0N}VJM%?;v2v]v+;+^9eXUahg@::Cj'); define('AUTH_SALT', 'C$DpB4Hj[JK:?{ql`sRVa:{:7yShy(9A@5wg+`JJVb1fk%_-Bx*M4(qc[Qg%JT!h'); define('SECURE_AUTH_SALT', 'd!uRu#}+q#{f$Z?Z9uFPG.${+S{n~1M&%@~gL>U>NV.|Y%Ug4#I^*LVd9QeZ^&XmK|e(76miC+&W&+^0P/'); define('NONCE_SALT', '-97r*V/cgxLmp?Zy4zUU4r99QQ_rGs2LTd%P;|_e1tS)8_B/,.6[=UK ec2-describe-reserved-instances-offerings -t m1.small -z sa-east-1b -d Linux/UNIX --headers

Amazon EC2 returns output similar to the following example:

API Version 2014-10-01 207

Amazon Elastic Compute Cloud User Guide for Linux Buying Reserved Instances

PROMPT> ec2-describe-reserved-instances-offerings Type Source ReservedInstancesOfferingId AvailabilityZone InstanceType Duration FixedPrice UsagePrice ProductDescription Currency InstanceTenancy Offering Type OFFERING AWS 4b2293b4-3236-49f5-978d-a74c3example sa-east-1b m1.small 3y 574.0 0.0 Linux/UNIX USD default Heavy Utilization Type Frequency Amount RECURRING-CHARGE Hourly 0.021 OFFERING AWS 3a98bf7d-07e1-4b33-8e11-e5314example sa-east-1b m1.small 3y 473.0 0.031 Linux/UNIX USD default Medium Utilization OFFERING AWS 438012d3-5fc5-4e49-a88e-273edexample sa-east-1b m1.small 3y 203.0 0.055 Linux/UNIX USD default Light Utilization OFFERING AWS d586503b-bb92-41fa-9065-e5b90example sa-east-1b m1.small 1y 372.94 0.0 Linux/UNIX USD default Heavy Utilization Type Frequency Amount RECURRING-CHARGE Hourly 0.03 OFFERING AWS ceb6a579-b235-41e2-9aad-15a23example sa-east-1b m1.small 1y 307.13 0.04 Linux/UNIX USD default Medium Utilization OFFERING AWS 649fd0c8-4ffb-443d-824d-eae3fexample sa-east-1b m1.small 1y 131.63 0.07 Linux/UNIX USD default Light Utilization OFFERING 3rd Party b6121943-9faf-4350-8047-bc6d4example sa-east-1b m1.small 10m - 0.032 Linux/UNIX USD default Medium Utilization Type Count Price PRICING_DETAIL 2 $1.2 OFFERING 3rd Party 08edcff2-8143-4c1d-b23c-e4c11example sa-east-1b m1.small 5m - 0.032 Linux/UNIX USD default Medium Utilization Type Count Price PRICING_DETAIL 19 $1.2 PRICING_DETAIL 4 $1.23

The preceding output shows a part of the overall offerings that are available.

Tip You can filter this list to return only certain types of Reserved Instances offerings of interest to you. For more information about how to filter the results, see ec2-describe-reserved-instances-offerings in the Amazon EC2 Command Line Reference. 2.

From the list of available Reserved Instances, purchase the Reserved Instances that meet your requirements. To purchase a Reserved Instance, use the following command. PROMPT> ec2-purchase-reserved-instances-offering --offering offering --in stance-count count

Amazon EC2 returns output similar to the following: PURCHASE af9f760e-c1c1-449b-8128-1342dexample a209cexample

The response includes the offering ID and a reservation ID. 3. 4.

Write down and save the reservation ID for future reference. Verify the purchase. PROMPT> ec2-describe-reserved-instances

Amazon EC2 returns output similar to the following:

API Version 2014-10-01 208

438012d3-80c7-42c6-9396-

Amazon Elastic Compute Cloud User Guide for Linux Buying Reserved Instances

RESERVEDINSTANCE af9f760e-c1c1-449b-8128-1342dexample sa-east-1b m1.small 1y 227.5 0.03 Linux/UNIX Active

You can run your Reserved Instance any time after your purchase is complete. To run your Reserved Instance, you launch it in the same way you launch an On-Demand instance. Make sure to specify the same criteria that you specified for your Reserved Instance. AWS will automatically charge you the lower hourly rate.

Amazon EC2 API To find and purchase a Reserved Instance 1.

Use DescribeReservedInstancesOfferings to get a list of Reserved Instance offerings that match your specifications. In this example, we'll check to see the available Linux/UNIX, Heavy Utilization Reserved Instances. https://ec2.amazonaws.com/?Action=DescribeReservedInstancesOfferings &MaxResults=50 &ProductDescription=Linux%2FUNIX &OfferingType=Heavy+Utilization &AUTHPARAMS

Note When using the Query API the “/” is denoted as “%2F”. Following is an example response. 768e52ac-20f5-42b1-8559-e70e9example d0280f9e-afc1-47f3-9899c3a2cexample m1.xlarge us-east-1a 25920000 195.0 0.0 Linux/UNIX dedicated USD Heavy Utilization Hourly 0.2 true 195.0 1

API Version 2014-10-01 209

Amazon Elastic Compute Cloud User Guide for Linux Buying Reserved Instances

310.0 1 377.0 1 380.0 1 649fd0c8-7846-46b8-8f84-a6400ex ample m1.large us-east-1a 94608000 1200.0 0.0 Linux/UNIX default USD Heavy Utilization Hourly 0.052 false QUUVo/0S3X6nEBjSQZR/pRRlCPP/5Lrx79Wyxexample

2.

From the list of available Reserved Instances in the previous example, select the Reserved Instance you want and specify a limit price. https://ec2.amazonaws.com/?Action=PurchaseReservedInstancesOffering &ReservedInstancesOfferingId=d0280f9e-afc1-47f3-9899-c3a2cexample &InstanceCount=1 &LimitPrice.Amount=200 &AUTHPARAMS

Following is an example response. 59dbff89-35bd-4eac-99ed-be587example e5a2ff3b-7d14-494f-90af-0b5d0example

3.

To verify the purchase, check for your new Reserved Instance. http://ec2.amazonaws.com/?Action=DescribeReservedInstances &AUTHPARAMS

Following is an example response: ebe3410a-8f37-441d-ae11-2e78eexample e5a2ff3b-7d14-494f-90af-0b5d0example m1.xlarge us-east-1a 2012-08-23T15:19:31.071Z 25920000 195.0 0.0 1 Linux/UNIX active dedicated USD Heavy Utilization Hourly 0.2

You can run your Reserved Instance any time after your purchase is complete. To run your Reserved Instance, you launch it in the same way you launch an On-Demand EC2 instance. Make sure to specify the same criteria that you specified for your Reserved Instance. AWS will automatically charge you the lower hourly rate.

Reading Your Statement (Invoice) Account Activity You can find out about the charges and fees to your account by viewing your Account Activity page in the AWS Management Console. You can access it by clicking the drop-down arrow beside your account name.

API Version 2014-10-01 211

Amazon Elastic Compute Cloud User Guide for Linux Buying Reserved Instances

The Account Activity page will show all charges against your account—such as upfront and one-time fees and recurring charges. You can get both a summary of all your charges and a detailed list of your charges. The upfront charges from your purchase of third-party Reserved Instances in the Reserved Instance Marketplace will be listed in the AWS Marketplace Charges section, with the name of the seller displayed beside it. However, all recurring or usage charges for these Reserved Instances will be listed in the AWS Service Charges section.

You can view the charges online, and you can also download a PDF rendering of the charge information.

API Version 2014-10-01 212

Amazon Elastic Compute Cloud User Guide for Linux Obtaining Information About Your Reserved Instances

The Detail section contains information about the Reserved Instance—such as the Availability Zone, instance type, cost, and number of instances. It also includes the name of the seller of the Reserved Instances that you purchased.

Obtaining Information About Your Reserved Instances Information about your Reserved Instances, such as state, instance type, Availability Zone, and term is useful when you decide to use the capacity reservation. You can check information about the Reserved Instances that are available to your account using any of the Amazon EC2 tools that you've used either for purchasing or selling.

Reserved Instance States Reserved Instances can be in one of the following states: • Active—The Reserved Instance is available for use. • Payment-Pending—Amazon Web Services (AWS) is processing your payment for the Reserved Instance. You will be able to use the Reserved Instance when the state becomes Active. • Retired—The Reserved Instance has been terminated. It could have reached this state because of any of the following reasons: • AWS did not receive your payment. For example, the credit card transaction did not go through. • The Reserved Instance term expired. • The Reserved Instance was canceled.

API Version 2014-10-01 213

Amazon Elastic Compute Cloud User Guide for Linux Obtaining Information About Your Reserved Instances

Status information displayed in the State column in the Reserved Instance page is different from the status information displayed in the Listing State in the My Listings tab. The State column displays status of the Reserved Instance; the Listing State displays status of the Reserved Instance Listing. The My Listings tab shows information only if you are a seller in the Reserved Instance Marketplace. For more information, see Reserved Instance Listing States (p. 253).

AWS Management Console To view your listing 1. 2.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. Click Reserved Instances in the Navigation pane. The Reserved Instances page displays a list of your account's instances.

3.

Select a Reserved Instance. The Details tab displays details about the instance you selected.

4.

If you are a seller in the Reserved Instance Marketplace and you want information about your Reserved Instance listing, click the My Listings tab. You will see details about the Reserved Instance listing you selected.

Amazon EC2 CLI To view your listing •

Run ec2-describe-reserved-instances-listing to get details about your listing. PROMPT> ec2-describe-reserved-instances-listings

API Version 2014-10-01 214

Amazon Elastic Compute Cloud User Guide for Linux Obtaining Information About Your Reserved Instances

Amazon EC2 returns output similar to the following: PROMPT> ec2-describe-reserved-instances-listings Type ReservedInstancesListingId ReservedInstancesId CreateDate UpdateDate Status StatusMessage LISTING 615d8a10-8224-4c19-ba7d-b9aa0example 1ba8e2e3-d20d-44ec-b202fcb6aexample Wed Aug 22 09:02:58 PDT 2012 Wed Aug 22 14:24:26 PDT 2012 can celled cancelled INSTANCE-COUNT available 0 INSTANCE-COUNT sold 0 INSTANCE-COUNT cancelled 1 INSTANCE-COUNT pending 0 PRICE-SCHEDULE 10 $1.2 PRICE-SCHEDULE 9 $1.08 PRICE-SCHEDULE 8 $0.96 PRICE-SCHEDULE 7 $0.84 PRICE-SCHEDULE 6 $0.72 PRICE-SCHEDULE 5 $0.6 PRICE-SCHEDULE 4 $0.48 PRICE-SCHEDULE 3 $0.36 PRICE-SCHEDULE 2 $0.24 PRICE-SCHEDULE 1 $0.12 LISTING d5fa5166-83c3-40e4-abb2-b7298example 1ba8e2e3-d20d-44ec-b202fcb6aexample Wed Aug 22 14:31:55 PDT 2012 Wed Aug 22 14:42:40 PDT 2012 closed closed INSTANCE-COUNT available 0 INSTANCE-COUNT sold 1 INSTANCE-COUNT cancelled 0 INSTANCE-COUNT pending 0 PRICE-SCHEDULE 10 $0.9 PRICE-SCHEDULE 9 $0.81 PRICE-SCHEDULE 8 $0.72 PRICE-SCHEDULE 7 $0.63 PRICE-SCHEDULE 6 $0.54 PRICE-SCHEDULE 5 $0.45 PRICE-SCHEDULE 4 $0.36 PRICE-SCHEDULE 3 $0.27 PRICE-SCHEDULE 2 $0.18 PRICE-SCHEDULE 1 $0.09 .... LISTING 095c0e18-c9e6-4692-97e5-653e0example b847fa93-c736-4eae-bca1e3147example Tue Aug 28 18:21:07 PDT 2012 Tue Aug 28 18:21:07 PDT 2012 active active INSTANCE-COUNT available 1 INSTANCE-COUNT sold 0 INSTANCE-COUNT cancelled 0 INSTANCE-COUNT pending 0 PRICE-SCHEDULE 5 $1.2 PRICE-SCHEDULE 4 $1.2 PRICE-SCHEDULE 3 $1.2 PRICE-SCHEDULE 2 $1.2 PRICE-SCHEDULE 1 $1.2

API Version 2014-10-01 215

Amazon Elastic Compute Cloud User Guide for Linux Obtaining Information About Your Reserved Instances

Amazon EC2 API To view your listing •

Call DescribeReservedInstancesListings to get details about your listing. The call should look like this example: http://ec2.amazonaws.com/?Action=DescribeReservedInstancesListings &AUTHPARAMS

Following is an example response. cec5c904-8f3a-4de5-8f5a-ff7f9example 5ec28771-05ff-4b9b-aa319e57dexample f127bd27-cee4-443a-a76b-a5af9example 2012-08-30T17:11:09.449Z 2012-08-30T21:00:42.300Z active active Available 2 Sold 1 Cancelled 0 Pending 0 11 2.5 USD true 10 2.5 USD false

API Version 2014-10-01 216

Amazon Elastic Compute Cloud User Guide for Linux Obtaining Information About Your Reserved Instances

9 2.5 USD false 8 2.0 USD false 7 2.0 USD false 6 2.0 USD false 5 1.5 USD false 4 1.5 USD false 3 0.7 USD false 2 0.7 USD false 1 0.1 USD false listRI1

API Version 2014-10-01 217

Amazon Elastic Compute Cloud User Guide for Linux Modifying Your Reserved Instances

Modifying Your Reserved Instances When your computing needs change, you can modify your Reserved Instances and continue to benefit from your capacity reservation. You can move your Reserved Instances between Availability Zones within the same region, and you can change the network platform between EC2-Classic and EC2-VPC. Availability Zone and network platform modifications are supported for all product platform types. In addition, starting with Amazon EC2 API version 2013-10-01, you can change the instance type of your reservation to a larger or smaller instance type in the same family (e.g., the M1 instance family), if capacity is available, and if you are modifying a Reserved Instance associated with the Linux/UNIX product platform. Instance type modifications are not supported for other platform types. Modification does not change the remaining term of your Reserved Instances. Their end dates remain the same. There is no fee for modifying your Reserved Instances, and you do not receive any new bills or invoices. Instances covered by Reserved Instances continue to run even if you modify your reservation. However, after modification, the pricing benefit of the Reserved Instances starts applying to instances that match the new parameters of your Reserved Instances. You are charged at the On-Demand rate for the EC2 instances no longer receiving the benefits of the modified Reserved Instances, unless your account has other applicable reservations, in which case you will be charged at the rate of these other Reserved Instances. Modification does not affect how you use, purchase, or sell Reserved Instances. When you purchase Reserved Instances, you still need to specify the product platform, instance type, network platform, tenancy, term length, offering type, and Availability Zone.

Note To purchase and modify Reserved Instances, ensure that your account has the appropriate permissions, such as the ability to describe Availability Zones. For information, see the IAM Best Practices and the Permissions and Policies sections in the Using IAM guide. You can view the status of your request in the AWS Management Console, or when you call the DescribeReservedInstancesModifications API action or ec2-describe-reserved-instancesmodifications CLI command. This section discusses the modification process: • Understanding the Modification Process (p. 218)—What happens when I submit a modification request? • Determining the Status of Your Modification (p. 220)—How do I track my modification requests? • Requirements for Modification (p. 221)—Which Reserved Instances can I modify? • Changing the Instance Type of Your Reservations (p. 222)—When can I change the instance size of my Reserved Instances? • Submitting Modification Requests (p. 224)—How do I modify my Reserved Instances?

Understanding the Modification Process You can modify your Reserved Instances in one or more of the following ways: • Move them between Availability Zones within the same region.

API Version 2014-10-01 218

Amazon Elastic Compute Cloud User Guide for Linux Modifying Your Reserved Instances

If you modify the Availability Zone of your Reserved Instances, the capacity reservation and pricing benefit stop applying to instance usage in the original zone, and start applying to usage in the new Availability Zone. • Change the network platform of the Reserved Instances between EC2-VPC and EC2-Classic. If you modify the network platform of your Reserved Instances, the capacity reservation stops applying to instance usage with the original network platform, and starts applying to usage with the new network platform. However, the pricing benefit continues to apply to both EC2-Classic and EC2-VPC instance usage matching the remaining Reserved Instances parameters. • Upgrade or downgrade the instance type of your Reserved Instances within the same instance family (e.g., the M1 instance family). If you modify the instance type of your Reserved Instances, you must ensure that the instance family of your reservation has a larger or smaller instance type available and that you have enough applicable Reserved Instances to make the change. You can modify your whole reservation or a subset of your reservation. When you modify a subset of your reservation, Amazon EC2 splits your original Reserved Instances into two or more new Reserved Instances. For example, if you have Reserved Instances for 10 instances in us-east-1a, and decide to move 5 instances to us-east-1b, the modification request results in two new Reserved Instances—one for 5 instances in us-east-1a (the original zone), and the other for 5 instances in us-east-1b. Amazon EC2 fulfills your modification request as soon as possible, depending on available capacity. Until your modification request completes, the capacity reservation and pricing benefit associated with your Reserved Instances continue to be based on the original parameters of your reservation.

Note You cannot cancel or change a pending modification request after you submit it. While your modification is being processed, the status of the Reserved Instances that you're modifying is active (pending modification). After the modification has completed successfully, you can submit another modification request to roll back any changes you made. If your Reserved Instances modification request succeeds: • The modified reservation becomes effective immediately and the pricing benefit of the Reserved Instances is applied to the new instances beginning at the hour of the modification request. For example, if you successfully modify your Reserved Instances at 9:15PM, the pricing benefit transfers to your new instance at 9:00PM. (You can get the effective date of the modified Reserved Instances by using the DescribeReservedInstances API action or the ec2-describe-reserved-instances CLI command.) • The end date of the modified Reserved Instances is the same as the original end date of the reservation. If you successfully modify a three-year reservation that had 16 months left in its term, the resulting modified reservation is a 16-month Reserved Instance with the same end date as the original Reserved Instances. For example, in the following table, Modification #1 shows RI af9f760... was modified successfully and retired on 2013-08-30 16:00 UTC-7 and a new RI 46a408c... was created as a result of the modification on the same date-time that RI af9f760... was retired. Modification #2 shows RI 46a408c... was modified successfully and retired on 2013-09-03 14:00 UTC-7 and a new RI b847fa9... was created as a result of the modification on the same date-time that RI 46a408c... was retired.

API Version 2014-10-01 219

Amazon Elastic Compute Cloud User Guide for Linux Modifying Your Reserved Instances

• The original reservation is retired. Its end date is the start date of the new reservation, and the end date of the new reservation is the same as the end date of the original Reserved Instance when it was active. • The modified Reserved Instances shows $0 fixed price and not the fixed price of the original Reserved Instances.

Note The fixed price of the modified reservation does not affect the discount tier calculations applied to your account, which are based on the fixed price of the original reservation.

If your modification request fails: • Your Reserved Instances maintain the original properties that they had prior to your request. • Your Reserved Instances are available for another modification request. You can determine the status of your request by looking at the state of the Reserved Instances that you are modifying. For information, see Determining the Status of Your Modification (p. 220).

Determining the Status of Your Modification The state of your modification request is displayed in the State field in the AWS Management Console. You can also use the DescribeReservedInstancesModifications API action to get detailed information about your modification request: The state returned shows your request as in-progress, fulfilled, or failed. You can only modify your Reserved Instances if they are active. You are not able to modify Reserved Instances that are in any other state. You also cannot modify your Reserved Instances if they are listed in the Reserved Instance Marketplace. For more information, see Requirements for Modification (p. 221). If your Reserved Instances are not in the active state or cannot be modified, the Modify Reserved Instances button in the AWS Management Console is not enabled. If you use the API to modify Reserved Instances that are not active, you will get an error. In cases when you select Reserved Instances whose Availability Zone and network platform can be modified, but whose instance types cannot be changed, the Modify Reserved Instances button is enabled and you can proceed to the Modify Reserved Instances page. However, you do not have the option to modify the instance type. For more information, see Changing the Instance Type of Your Reservations (p. 222). Modification States The modification request is being processed. While the modification request is being processed, the status of the Reserved Instances being modified show as active (pending modification). The Reserved Instances are in this state only for a short period. The state reverts to active or becomes retired, depending

API Version 2014-10-01 220

Amazon Elastic Compute Cloud User Guide for Linux Modifying Your Reserved Instances

on the success of the modification. (If you use the DescribeReservedInstancesModifications API action, the status of your modification request should show processing.) The modification succeeded. If the modification is successful, the Reserved Instances being modified are retired, and new Reserved Instances are created with the modification configuration that you requested. The status of these new Reserved Instances is active. (If you use the DescribeReservedInstancesModifications API action, the status of your modification request should show fulfilled.)

Note For the brief period that the new Reserved Instances are being activated, the original Reserved Instances show as retired (pending modification). The modification failed. If the modification did not complete, the Reserved Instances being modified return to the active state. (If you use the DescribeReservedInstancesModifications API action, the status of your modification request should show failed.) For information about why some Reserved Instances cannot be modified, see Requirements for Modification (p. 221).

Requirements for Modification Amazon EC2 processes your modification request if the following conditions are met: • We have sufficient Reserved Instances capacity for your target configuration. • The Reserved Instances you are modifying are active. • The Reserved Instances are not pending another modification request. You may modify your Reserved Instances as frequently as you like. However, you cannot submit a modification request for Reserved Instances that are still pending a previous modification request; that is, if the previous modification request is in the active (pending modification) state. For information about modification states, see Determining the Status of Your Modification (p. 220). • The Reserved Instances are not listed in the Reserved Instance Marketplace. To modify Reserved Instances that are listed in the Reserved Instance Marketplace, cancel the listing, modify the Reserved Instances, and then list them again. In addition, you cannot modify a Reserved Instance Marketplace offering before or at the same time that you purchase it. However, you can submit a modification request after you purchase a Marketplace offering. For more information, see Reserved Instance Marketplace (p. 200). • Only the following attributes are being modified: Availability Zone in the same Region, instance type in the same instance family (e.g., the M1 instance family), and network platform. • When combining Reserved Instances, the end dates of the Reserved Instances must have the same hour digits in 24-hour format, but they do not need to have the same minutes or seconds. This means you can combine Reserved Instances if they end on the same day at 13:01 and 13:59, but not if they end at 12:59 and 13:01. • When modifying the instance type attribute • The Reserved Instances you are modifying must be for the Amazon Linux/UNIX product platform (currently the only product platform for which instance type modifications are allowed). • The new instance type of the Reserved Instances must be in the same instance family (e.g., the M1 instance family) as the original reservation. • If you are upgrading the instance type of your Reserved Instances, the normalized instance count for the target Reserved Instance configuration must equal the normalized instance count of the original reservation. If you select multiple Reserved Instances for modification and one or more of these Reserved Instances are for a product platform that does not allow instance type modification, the Modify Reserved Instances page will not show the option of changing the instance type for any of the selected Reserved Instances. For information about modifying instance types, see Changing the Instance Type of Your Reservations (p. 222). API Version 2014-10-01 221

Amazon Elastic Compute Cloud User Guide for Linux Modifying Your Reserved Instances

• The attributes for the target Reserved Instance configuration must result in a unique combination of Availability Zone, instance type, and network platform. For information about how to modify Reserved Instances, see Submitting Modification Requests (p. 224).

Changing the Instance Type of Your Reservations Under certain conditions, you can adjust the instance type of your Reserved Instances. If you have capacity reservations for Amazon Linux/UNIX in instance families with multiple instance sizes, you can request to modify your Reserved Instances to include different instance types within the same family. Your request proceeds successfully if the capacity exists and the modification does not change the instance size footprint of your Reserved Instances. For example, you can divide a reservation for one m1.large instance into four m1.small instances, or you can combine a reservation for four m1.small instances into one m1.large instance. In either case, the instance size footprint of the reservation does not change. On the other hand, you cannot change your reservation for two m1.small instances into one m1.large instance because the existing instance size footprint of your current reservation is smaller than the proposed reservation. Instance size footprints are determined by the normalization factor of the instance type and the number of instances in the reservation. This section discusses the two ways you can change the instance type of your Reserved Instances, and how you use the instance type's normalization factor to figure out what instance type modifications you can make. • Understanding the Instance Normalization Factor (p. 223) • Upgrading Your Instance Type (p. 223) • Downgrading Your Instance Type (p. 224)

Exceptions The following instance type sizes cannot be modified because there are no other sizes in their families. • • • • • •

t1.micro cc1.4xlarge cc2.8xlarge cg1.8xlarge cr1.8xlarge hi1.4xlarge

• hs1.8xlarge • g2.2xlarge In addition, instance type modifications are currently supported only for Linux/UNIX platform types. For more information, see Requirements for Modification (p. 221). When you try to modify Reserved Instances that have instance types or product platforms that cannot be modified, you can proceed to the Modify Reserved Instances page, but the Amazon EC2 console limits the modification options to Network and Availability Zone. Keep in mind that instance type modifications are allowed only if other Reserved Instances specification details match—such as region, utilization type, tenancy, product, end date and hour—and capacity is available. In addition, such modifications do not change the discounted hourly usage fee that you are billed, or the end date of your reservation.

API Version 2014-10-01 222

Amazon Elastic Compute Cloud User Guide for Linux Modifying Your Reserved Instances

Understanding the Instance Normalization Factor Each Reserved Instance has an instance size footprint. When you modify the instance type of Reserved Instances, the footprint is maintained even if the instance type is downsized or upsized. A modification request is not processed if the footprint of the target configuration does not match the size of the original configuration. The size of an instance type's footprint can be calculated by using its normalization factor, which is based on the type's size within the instance family (e.g., the M1 instance family). Normalization factors are only meaningful within the same instance family; instance types cannot be modified from one family to another. The following table illustrates the normalization factor that applies within an instance family. For example, an m1.small instance has a normalization factor of 1, an m1.medium instance has a factor of 2, and an m1.large instance has a factor of 4. Instance Size

Normalization Factor

micro

0.5

small

1

medium

2

large

4

xlarge

8

2xlarge

16

4xlarge

32

8xlarge

64

Each Reserved Instance has a total number of normalized instance units, which is equal to the instance count multiplied by the normalization factor of the instance type. For example, an m1.medium has a normalization factor of 2 so a Reserved Instance for four m1.medium instances is worth eight normalized instance units. You arrive at the value this way: 4 [count] x 2 [normalization factor] You can allocate your Reserved Instances into different instance sizes across the same instance family (e.g., the M1 instance family) as long as the total normalized instance units of your Reserved Instances remain the same. If you have Reserved Instances for four m1.medium instances, you can turn it into a reservation for eight m1.small instances (m1.small instances have a normalization factor of 1, thus 8 x 1). The resulting Reserved Instances would have the same normalized instance units or instance size footprint.

Upgrading Your Instance Type You can consolidate a reservation of multiple smaller instance types that belong to one instance family (e.g., the M1 instance family) into a reservation for a larger instance type in the same family. To upgrade or upsize your reservation, you must have enough of the smaller instance types in the same reservation to consolidate into larger instance types, and your reservation's overall instance size footprint does not change. For example, you can convert four m1.small instances, which is equivalent to four normalized instance units (4 x 1), into one m1.large instance, which is also equivalent to four normalized units (1 x 4). However, you cannot convert a reservation for a single m1.small instance (1 x 1) into a reservation for an m1.large instance (1 x 4). The two reservations are not equal. API Version 2014-10-01 223

Amazon Elastic Compute Cloud User Guide for Linux Modifying Your Reserved Instances

Instance families that have multiple instance sizes, and are not listed in the Exceptions (p. 222) list, can be changed or upgraded to larger instance type sizes.

Downgrading Your Instance Type You can change Reserved Instances for a large instance type to several Reserved Instances of smaller instance types of the same family (e.g., the M1 instance family). When you downgrade or downsize your Reserved Instances, you are actually dividing a large reservation into multiple smaller reservations. Just as with upsizing instance types, you can downsize successfully only if your reservation's overall instance size footprint does not change. For example, a reservation for two m1.large instances equals eight normalized instance units (2 x 4). Assuming there is capacity, they can be converted to a Reserved Instance for four m1.medium instances, which is also equivalent to eight normalized instance units (4 x 2). Instance families that have multiple instance sizes, and are not listed in the Exceptions (p. 222) list, can be changed or downgraded to smaller instance type sizes. For information about Amazon EC2 instance types, see Instance Types (p. 103). For information about Reserved Instances modification requests, see Submitting Modification Requests (p. 224).

Submitting Modification Requests You can use the AWS Management Console to modify your Reserved Instances in the following ways: • Move all or some of your capacity reservation to another Availability Zone in the same region. • Change the network platform of all or some of your Reserved Instances from EC2-Classic to EC2-VPC, or vice versa. • Upgrade or downgrade all or some of the instance types of your Reserved Instances within the same instance family (e.g., the M1 instance family) as long as there is capacity and the change maintains the footprint of your capacity reservation. You can also complete these modification tasks programmatically by using the AWS CLI (modify-reservedinstances), Amazon EC2 CLI (ec2-modify-reserved-instances), Amazon EC2 API (ModifyReservedInstances), and the AWS SDK for Java. For information about programming tools you can use to modify Reserved Instances, see Tools for Working with Reserved Instances (p. 189).

Using the Modifying Reserved Instances Page In this section, you will learn how to use the Modify Reserved Instances page in the Amazon EC2 Console to make modifications. We will also discuss the following: • Count and Units Values (p. 224) • Messages About Your Modification Requests (p. 227)

Count and Units Values The Modify Reserved Instances page in the EC2 console keeps track of the total count and units of the Reserved Instances that you have allocated for the target (or new) configurations versus the total number of Reserved Instances available for you to modify. Count is the literal number of instances for the current instance type. Units represent the total instance size of your reservation relative to its instance family (e.g., the M1 instance family). The value of the units equals the count multiplied by the normalization factor of the instance type. For information about the instance normalization factor, see Understanding the Instance Normalization Factor (p. 223).

API Version 2014-10-01 224

Amazon Elastic Compute Cloud User Guide for Linux Modifying Your Reserved Instances

Each target configuration row for your Reserved Instances has a count and units value. The allocated total is displayed in red if you have specified either more or fewer Reserved Instances than are available for modification.You cannot click Continue if the total units you have specified for your target configurations do not equal the total number of units of Reserved Instances available to modify. The units displayed will change to green after you have specified changes for all the Reserved Instances that were available for modification.

To modify your Reserved Instances 1.

On the Reserved Instances page, select one or more Reserved Instances to modify, and click Modify Reserved Instances.

The Modify Reserved Instances page opens with the Reserved Instances you selected and their current configuration.

2.

Decide how to modify your Reserved Instances. For this example, you want to modify your Reserved Instances so that 2 are not changed, 2 are moved to another Availability Zone, 2 are converted from EC2-Classic to EC2-VPC, and 2 are upgraded from m1.medium to m1.large instance type. Keep in mind that to upgrade, you will need 2 m1.medium instances for every 1 m1.large instance. The following table illustrates the changes that you want to implement: Modification Network

Availability Instance Zone Type

No change EC2-Classic us-east-1a (Keep some of the original RIs)

Pre-Change Post-Change Units Count Count

m1.medium

2

2

4

Change Availability Zone

EC2-Classic us-east-1b m1.medium

2

2

4

Change network platform

EC2-VPC

us-east-1a

2

2

4

m1.medium

API Version 2014-10-01 225

Amazon Elastic Compute Cloud User Guide for Linux Modifying Your Reserved Instances

Modification Network Change instance type

Availability Instance Zone Type

EC2-Classic us-east-1a

m1.large

Total

3.

Pre-Change Post-Change Units Count Count 4

2

8

10

8

20

To keep the original configuration (no change) for two Reserved Instances, type 2 for Count. Network, Availability Zone, and Instance Type stay the same. Units automatically updates to 4/20. Use the Add button to add a row so that each change you want to make to your Reserved Instances is displayed in a separate row.

4.

To change the Availability Zone, click Add and select us-east-1b in the Availability Zone list. For Count, type 2. Network and Instance Type stay the same. Units automatically updates to 8/20.

5.

To change the network platform, first click Add. Then select EC2-VPC in the Network list. For Count, type 2. The Availability Zone and Instance Type stay the same. Units automatically updates to 12/20.

6.

To change the instance type, click Add and select m1.large in the Instance Type list, and, for Count, type 2. The Availability Zone and Network stay the same. Units automatically updates to 20/20.

If you want to change an instance type, be sure that it can be converted to a larger or smaller set of instance types. For more information about changing instance types, see Changing the Instance Type of Your Reservations (p. 222).

API Version 2014-10-01 226

Amazon Elastic Compute Cloud User Guide for Linux Modifying Your Reserved Instances

In our example, you are upgrading from an m1.medium to an m1.large instance type, which has a larger footprint. The normalization factor for m1.large instance types is 4; to get one m1.large instance type you'll need 4 m1.small or 2 m1.medium instance types. Therefore, the remaining 4 m1.medium instance types, which have a normalized value of 8, can be upgraded to 2 m1.large instance types, which also have a normalized value of 8. Units will be 20/20 in green, which means that you have specified changes for all the Reserved Instances that were available for modification in this exercise and you can proceed with your modification request.

7.

For more information about the instance normalization factor, see Understanding the Instance Normalization Factor (p. 223). If you want to delete a configuration that you specified, such as the instance upgrade, click X for that row.

Note If the Modify Reserved Instances page contains only one row for configuration changes, you cannot delete that row. 8.

To confirm your modification choices when you finish specifying your target configurations, click Submit Modifications. Amazon EC2 checks your modification request. If the configuration settings you requested were unique, the instance count that you specified matches the total number of Reserved Instances available for you to modify, you will be informed that Amazon EC2 is processing your request.

Note At this point, Amazon EC2 has only determined that the parameters of your modification request are valid, and Amazon EC2 can now process the request. Only during the processing of the modification request, after you get this screen, is the capacity check made. Your modification request can still fail, but at a later point, due to capacity not available.

Messages About Your Modification Requests In some situations, you might get a message indicating incomplete or failed modification requests instead of a confirmation. Use the information in such messages as a starting point for resubmitting another modification request. • Not all selected Reserved Instances can be processed for modification. In the following message, Amazon EC2 identifies and lists the Reserved Instances that cannot be modified. If you receive a message like this, go to the Reserved Instances page in the EC2 console and check the information details about these capacity reservations.

• Error in processing your modification request. You submitted one or more Reserved Instances for modification and none of your requests can be processed. Depending on the number of Reserved Instances you are modifying, you can get different versions of the message.

API Version 2014-10-01 227

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

In these messages, Amazon EC2 displays the reasons why your request cannot be processed. For example, you might have specified the same target configuration—a combination of Availability Zone and platform—for one or more subsets of the Reserved Instances you are modifying. Try submitting these modification requests again, but ensure that instance details of the Reserved Instances match, and that the target configurations for all subsets of the Reserved Instances being modified are unique. What do you want to do next? • Obtaining Information About Your Reserved Instances (p. 213) • Buying Reserved Instances (p. 202) • Selling in the Reserved Instance Marketplace (p. 228)

Selling in the Reserved Instance Marketplace The Reserved Instance Marketplace gives you the flexibility to sell the remainder of your Reserved Instances as your needs change—for example, if you want to move instances to a different Amazon Web Services (AWS) region, change to another instance type, or sell capacity for projects that end before the Reserved Instance term expires. (Some restrictions—such as what is required to become a seller and when you can sell your reserved capacity apply. For information about restrictions and requirements for Reserved Instances and the Reserved Instance Marketplace, see Requirements Checklist for Reserved Instances (p. 254).) As soon as you list your Reserved Instances, they will be included in a list that other AWS customers can view. AWS groups Reserved Instances based on the type of instance being listed, the duration of the term remaining, and the hourly price. This grouping makes it easier for buyers to find the Reserved Instances they want to purchase. From the list, customers choose to purchase the instance that best matches their criteria and decide on the best tradeoff between quoted upfront price and hourly price. To fulfill a buyer's request, AWS first sells the Reserved Instance with the lowest upfront price in the specified grouping; then it sells the Reserved Instance with the next lowest price, until the buyer’s entire purchase order is fulfilled. AWS processes the transaction and transfers ownership of the Reserved Instance to the buyer. Sellers will receive a cash disbursem*nt for their Reserved Instances through a wire transfer directly into their bank account. When you sell in the Reserved Instance Marketplace, the buyer’s ZIP code and country information will be provided to you through a disbursem*nt report. With this information, you will be able to calculate any necessary tax you need to remit to the government. Your business name (as the seller) will also be provided on the purchase invoice of the buyer. AWS charges an administrative fee (12 percent of the total upfront price) for selling in the Reserved Instance Marketplace. For more information, see Reserved Instance Marketplace in the Amazon EC2 Reserved Instances product page. You retain control of your Reserved Instance until it's sold. When you sell, what you are giving up is the capacity reservation and the discounted recurring fees. You can continue to use your instance after you have sold the reserved capacity, but AWS will now charge you the On-Demand price. The On-Demand

API Version 2014-10-01 228

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

price will start from the time that your Reserved Instance was sold. Thus, if you don't want to be charged On-Demand prices for instances that you use, purchase more reserved capacity or terminate your instances when your capacity reservation is sold (or expires). This topic walks you through the steps to selling in the Reserved Instance Marketplace: • Registering as a Seller (p. 229)—Register as a seller and specify a bank that has a US address. If you plan on 200 or more transactions or if you plan to sell $20,000 or more worth of Reserved Instances over the course of a year, you also have to provide tax information. • Selling Your Reserved Instances (p. 233)—List an active Reserved Instance that has more than one month left in its term. You also must own the Reserved Instance for longer than a month. • After Your Reserved Instance Is Sold (p. 252)—Find out when your Reserved Instance is sold, and how you get paid. • Quick Start: Selling in the Reserved Instance Marketplace Video (p. 202)—Pick up the information you need to quickly get started selling in the Reserved Instance Marketplace. For information about buying Reserved Instances in the Reserved Instance Marketplace, see Buying Reserved Instances (p. 202). For basic information about Reserved Instances, see Reserved Instances (p. 185).

Important Notes About Selling in the Reserved Instance Marketplace • To become a seller in the Reserved Instance Marketplace, you must register as a seller, and specify a bank that has a US address. For information, see Registering as a Seller (p. 229). • Reserved Instances can be sold after they have been active for at least 30 days and when AWS has received the upfront payment. • You can sell up to $50,000 in Reserved Instances per year. If you need to sell more Reserved Instances, complete the Request to Raise Sales Limit on Amazon EC2 Reserved Instances form. • Amazon EC2 Reserved Instances purchased at a reduced cost resulting from tiered discount cannot be sold in the Reserved Instance Marketplace. For more information about discount pricing tiers, see Understanding Reserved Instance Pricing Tiers (p. 193). For a checklist that summarizes requirements for working with Reserved Instances and the Reserved Instance Marketplace, see Requirements Checklist for Reserved Instances (p. 254).

Registering as a Seller Topics • Your Bank (p. 230) • Tax Information (p. 231) • Seller Registration Confirmation (p. 232) • Sharing Information with the Buyer (p. 232) • Next Steps (p. 232) To be able to sell in the Reserved Instance Marketplace, your first task is to register as a seller.

API Version 2014-10-01 229

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

If you haven't created an AWS account yet, you need to do this first before you register for Reserved Instance Marketplace. Complete the instructions described in Getting Started with Amazon EC2 Linux Instances (p. 26), which provides information about creating your Amazon EC2 account and credentials. You can access the registration process through the Reserved Instance Marketplace Seller Registration web page. If you try to create a listing and you have not registered, AWS will direct you to this seller registration page. Registering means providing the name of your business, information about your bank, and your business's tax identification number. Usually, you only have to provide your information once. However, you can update personal and banking information through the Reserved Instance Marketplace Seller Registration web page. Log in to AWS using the account you used when you first registered and the page will send you directly to the personal and banking information pages.

Your Bank AWS must have your bank information in order to disburse funds collected when you sell your Reserved Instance. The bank you specify must have a US address. On the Manage Bank Account page, provide the following information about the bank through which you will receive payment: • Bank account holder name • Routing number • Account number

API Version 2014-10-01 230

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

• Bank account type

Note If you are using a corporate bank account, you will be prompted to send via fax (1-206-7653424) the information about the bank account.

You can change the default bank account through which you receive disbursem*nts. Just go to the Reserved Instance Marketplace Seller Registration web page using the account you used when you first registered and the page will send you directly to the personal and banking information pages. After you have completed the registration, AWS verifies your bank account and sets it as the default bank. You will not be able to receive disbursem*nts until AWS has verified your account with the bank. Verification with the bank can take up to two weeks, so if your account is a new one, you will not get the disbursem*nt as a result of a sale for up to two weeks. For an established account, it will usually take about two days for disbursem*nts to complete.

Tax Information Your sale of Reserved Instances on the Reserved Instance Marketplace might be subject to a transactional tax, such as sales tax or value-added tax.You should check with your business's tax, legal, finance, or accounting department to determine if transaction-based taxes are applicable. You are responsible for collecting and sending the transaction-based taxes to the appropriate tax authority. As part of the seller registration process, you have the option of completing a tax interview. We encourage you to complete this process if any of the following apply: • You want AWS to generate a Form 1099-K. • You anticipate having either 200 or more transactions or $20,000 or more in sales of Reserved Instances in a calendar year. A transaction can involve one or more Reserved Instances. If you choose to skip this step during registration, and later you reach transaction 199, you will get a message saying, "You have reached the transaction limit for pre-tax. Please complete the tax interview at http://portal.aws.amazon.com/ec2/ri/seller_registration?action=taxInterview ." • You are a non-US seller. In this case, you must electronically complete Form W-8BEN. If you complete the tax interview, the tax information you enter will differ depending on whether your business is a US or non-US legal entity. If you are a US seller, you must provide AWS with your tax identification number along with your business contact information.

API Version 2014-10-01 231

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

After you complete the tax registration process, AWS will file Form 1099-K, and you will receive a copy of it through the US mail on or before January 31 in the year after the year that your tax account reaches the threshold levels. As you fill out the tax interview, keep in mind the following: • Information provided by AWS, including the information in this topic, does not constitute tax, legal, or other professional advice. To find out how the IRS reporting requirements might affect your business, or if you have other questions, please contact your tax, legal, or other professional advisor. • In order to fulfill the IRS reporting requirements as efficiently as possible, answer all questions and enter all information requested during the interview. • Check your answers. Avoid misspellings or entering incorrect tax identification numbers. They can result in an invalidated tax form. For more information about IRS requirements and the Form 1099-K, go to the IRS website.

Seller Registration Confirmation After we receive your completed seller registration, you will get an email confirming your registration and informing you that you can get started selling in the Reserved Instance Marketplace.

Sharing Information with the Buyer When you sell your Reserved Instances in the Reserved Instance Marketplace, AWS will share your company’s legal name on the buyer’s statement to comply with US regulations. In addition, if the buyer calls AWS customer service because the buyer needs to contact you for an invoice or for some other taxrelated reason, AWS may need to provide the buyer with your email address so that the buyer can contact you directly. For similar reasons, the buyer’s ZIP code and country information will be provided to the seller in the disbursem*nt report. As a seller, you might need this information to accompany any necessary transaction taxes that you remit to the government (such as sales tax and value-added tax). AWS cannot offer tax advice, but if your tax specialist determines that you need specific additional information, contact AWS Customer Support.

Next Steps After you have successfully registered as a seller in the Reserved Instance Marketplace, you can begin selling your Reserved Instances. Selling in the Reserved Instance Marketplace requires the following steps: 1. Deciding which Reserved Instances you want to sell.

API Version 2014-10-01 232

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

Identify the active Reserved Instances that you want to sell and select the upfront price at which you want to sell them. For more information, see Pricing Your Reserved Instances (p. 234). 2. Listing your Reserved Instances. Include your Reserved Instances in the Reserved Instance Marketplace listings. For more information, see Listing Your Reserved Instance (p. 234). 3. Viewing your listings. You can monitor your Reserved Instances and view your listings. For more information, see Obtaining Information About Your Reserved Instances (p. 213). 4. Canceling and changing your listings. You can change your listings by first canceling and then relisting. For more information, see Canceling and Changing Your Listings (p. 243). For information about selling your Reserved Instances, see Selling Your Reserved Instances (p. 233).

Selling Your Reserved Instances Topics • Pricing Your Reserved Instances (p. 234) • Listing Your Reserved Instance (p. 234) • Canceling and Changing Your Listings (p. 243) This section walks you through how to list and sell your Reserved Instances in the Reserved Instance Marketplace. If you haven't registered as a seller yet, you must do so first. For information, see Selling Your Reserved Instances (p. 233). As a registered seller, you can choose to sell one or more of your Reserved Instances, and you can choose to sell all of them in one listing. In addition, you can list any type of Reserved Instance—including any configuration of instance type, platform, region, and Availability Zone—as long as the following requirements are met: • You have already paid the upfront cost for the Reserved Instance you are listing. This means that you can list your Reserved Instance when it is in the Active state. However, keep in mind that a Reserved Instance can be in the Active state before AWS actually receives your payment. If this is the case, the Reserved Instance Marketplace will not allow you to list your Reserved Instance until the payment for the upfront fee is collected. • You have owned the Reserved Instance for at least a month. • There is at least a month remaining in the term of the Reserved Instance you are listing. You can list the remainder of the Reserved Instance term rounded down to the nearest month. For example, if you have 9 months and 13 days remaining on your Reserved Instance, you can list 9 months for your Reserved Instance. • The Reserved Instance you are selling is not a discounted or private Reserved Instance. You cannot list these types of Reserved Instances in the Reserved Instance Marketplace. For a checklist that summarizes requirements for working with Reserved Instances and the Reserved Instance Marketplace, see Requirements Checklist for Reserved Instances (p. 254). To get details about your existing Reserved Instances, you can use any of the following tools: • The Reserved Instances page in the EC2 console of the AWS Management Console (p. 189).

API Version 2014-10-01 233

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

• The ec2-describe-reserved-instances CLI command. • The DescribeReservedInstances API action. For more information about Reserved Instances, see Reserved Instances (p. 185).

Pricing Your Reserved Instances When you're a seller on the Reserved Instance Marketplace, the upfront fee is the only fee that you can specify for the Reserved Instance. The upfront fee is the one-time fee that the buyer pays when the buyer purchases a Reserved Instance. The seller cannot specify the usage fee or the recurring fee. The buyer of your Reserved Instance will be paying the same usage or recurring fees that were set when the Reserved Instances were originally purchased. This usage fee applies to Light Utilization and Medium Utilization Reserved Instances, and the fee differs depending on which Reserved Instance offering you're using. The recurring fee is the hourly fee that you pay for Heavy Utilization, whether or not you're using the Reserved Instance. For more information about the availability of Reserved Instances offerings based on utilization, see Choosing Reserved Instances Based on Your Usage Plans (p. 191). Setting a Pricing Schedule You can set different upfront fees (prices) that are based on when your Reserved Instance sells. You can specify one price if the Reserved Instance sells immediately, and you can specify another price if the Reserved Instance were to sell in any subsequent month. Since the value of Reserved Instances decreases over time, by default, AWS will set prices to decrease linearly—that is, the price drops in equal increments month over month. You can choose to set the prices differently. For example, if your Reserved Instance has nine months of its term remaining, you can specify the amount you would accept if a customer were to purchase that Reserved Instance with nine months remaining, and you could set another price with five months remaining, and yet another price with one month remaining.

Listing Your Reserved Instance You can list the Reserved Instances you want to sell in the Reserved Instance Marketplace by using the AWS Management Console, the Amazon EC2 CLI, or the Amazon EC2 API.

AWS Management Console To list a Reserved Instance in the Reserved Instance Marketplace 1.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

2.

Click Reserved Instances in the Navigation pane.

3.

The Reserved Instances page displays a list of your account's instances. Select the Reserved Instances you want to list on the marketplace, and click Sell Reserved Instances.

Note If you have not completed the Reserved Instance Marketplace seller registration process, you will be prompted to complete this process now. For information about the seller registration process, see Registering as a Seller (p. 229).

API Version 2014-10-01 234

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

4.

5.

6.

In the Configure Your Reserved Instance Listing page, for Number to List, set the number of instances to sell and, for Your Price, set the upfront price for the remaining time period.

You can see how the value of your Reserved Instance will change over the remainder of the term by clicking the arrow on the left of the Months Remaining column. By default, AWS sets the price to decrease linearly. This means the price drops by equal increments each month. If you are an advanced user and you want to customize the pricing, you can enter different values for the subsequent months. To return to the default linear price drop, click Reset. Click Continue when you are finished configuring your listing.

When you are satisfied with the details of your listing as displayed by the Confirm Your Reserved Instance Listing page, click List Reserved Instance.

API Version 2014-10-01 235

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

You will get a confirmation that your listing is being processed.

7.

To view the details of your Reserved Instance listing, on the Reserved Instances page, select the Reserved Instance you want to view, and click the My Listings tab.

Amazon EC2 CLI To list a Reserved Instance in the Reserved Instance Marketplace 1.

Get a list of your Reserved Instances by calling ec2-describe-reserved-instances. PROMPT> ec2-describe-reserved-instances --headers

Amazon EC2 returns output similar to the following: PROMPT> ec2-describe-reserved-instances --headers Type ReservedInstancesId AvailabilityZone InstanceType ProductDescription Duration FixedPrice UsagePrice InstanceCount Start State Currency Instan ceTenancy OfferingType RESERVEDINSTANCES f127bd27-9f30-41d3-bf45-9af45example sa-east-1a m1.large Linux/UNIX 10m 1.0 0.0 1 2012-08-22T21:41:51+0000 active USD default Medium Utilization RESERVEDINSTANCES 1ba8e2e3-d20d-44ec-b202-fcb6aexample sa-east-1b m1.small Linux/UNIX 10m 1.2 0.032 3 2012-08-21T14:02:00+0000 retired USD default Medium Utilization RESERVEDINSTANCES 4357912c-6f69-4966-a407-6f0cbexample sa-east-1b m1.small Linux/UNIX 10m 1.2 0.032 3 2012-08-21T14:02:00+0000 active USD default Medium Utilization

API Version 2014-10-01 236

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

RESERVEDINSTANCES 4357912c-d032-4a97-9b49-5eb3aexample sa-east-1b m1.small Linux/UNIX 10m 1.2 0.032 1 2012-08-21T14:02:00+0000 retired USD default Medium Utilization ...

2.

Select the Reserved Instance ID of the Reserved Instance you want to list in the Reserved Instance Marketplace. Specify the Reserved Instance ID of the Reserved Instance you want to list and call ec2-createreserved-instances-listing. You have to specify the following required parameters: • Reserved Instance ID • Instance count • MONTH:PRICE The command should look like this example: PROMPT> ec2-create-reserved-instances-listing --reserved-instance b847fa93c736-4eae-bca1-3147example --instance-count 1 05:01.20 04:01.00 01:00.75 -headers

Amazon EC2 returns output similar to the following: PROMPT>LISTING 2a0ff720-f62e-4824-8ed1-7dd0aexample b847fa93-c736-4eae-bca1e3147example Wed Aug 29 13:59:11 PDT 2012 Wed Aug 29 13:59:11 PDT 2012 active active INSTANCE-COUNT available 1 INSTANCE-COUNT sold 0 INSTANCE-COUNT cancelled 0 INSTANCE-COUNT pending 0 PRICE-SCHEDULE 5 $1.2 PRICE-SCHEDULE 4 $1.0 PRICE-SCHEDULE 3 $1.0 PRICE-SCHEDULE 2 $1.0 PRICE-SCHEDULE 1 $0.75

3.

To view the details of your Reserved Instance listing, run ec2-describe-reserved-instanceslistings with the listing ID 095c0e18-c9e6-4692-97e5-653e0example. PROMPT> ec2-describe-reserved-instances-listings 095c0e18-c9e6-4692-97e5653e0example

Amazon EC2 returns output similar to the following: PROMPT> ec2-describe-reserved-instances-listings 095c0e18-c9e6-4692-97e5653e0example Type ReservedInstancesListingId ReservedInstancesId CreateDate UpdateDate Status StatusMessage LISTING 095c0e18-c9e6-4692-97e5-653e0example b847fa93-c736-4eae-bca1e3147example Tue Aug 28 18:21:07 PDT 2012 Tue Aug 28 18:21:07 PDT 2012 active active INSTANCE-COUNT available 1 INSTANCE-COUNT sold 0

API Version 2014-10-01 237

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

INSTANCE-COUNT INSTANCE-COUNT PRICE-SCHEDULE PRICE-SCHEDULE PRICE-SCHEDULE PRICE-SCHEDULE PRICE-SCHEDULE

cancelled 0 pending 0 5 $1.2 4 $1.2 3 $1.2 2 $1.2 1 $1.2

Amazon EC2 API To list a Reserved Instance in the Reserved Instance Marketplace 1.

Get a list of your Reserved Instances by calling DescribeReservedInstances. https://ec2.amazonaws.com/ ?Action=DescribeReservedInstances &AUTHPARAMS

Following is an example response. ebe3410a-8f37-441d-ae11-2e78eexample f127bd27-cee4-443a-a76b-a5af9example m1.large us-east-1a 2012-08-07T15:19:31.071Z 31536000 276.0 0.156 5 Linux/UNIX active default USD Light Utilization

Note the Reserved Instance ID of the Reserved Instance that you want to list in the Reserved Instance Marketplace. 2.

Create a listing for three Reserved Instances from Reserved Instance ID f127bd27-cee4-443a-a76ba5af9example and specify the following pricing schedule.

API Version 2014-10-01 238

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

Term (remaining months)

11

Price specified for period

2.5

Price

2.5

10

9

8

7

6

2.0 2.5

2.5

2.0

5

4

1.5 2.0

2.0

1.5

3

2

0.7 1.5

0.7

1 0.1

0.7

0.1

The call should look like this example: https://ec2.amazonaws.com/?Action=CreateReservedInstancesListing &ClientToken=myIdempToken1 &ReservedInstancesId=f127bd27-cee4-443a-a76b-a5af9example &InstanceCount=3 &PriceSchedules.0.Price=2.5&PriceSchedules.0.Term=11 &PriceSchedules.1.Price=2.0&PriceSchedules.1.Term=8 &PriceSchedules.2.Price=1.5&PriceSchedules.2.Term=5 &PriceSchedules.3.Price=0.7&PriceSchedules.3.Term=3 &PriceSchedules.4.Price=0.1&PriceSchedules.4.Term=1 &AUTHPARAMS

Following is an example response. a42481af-335a-4e9e-b291-bd18dexample 5ec28771-05ff-4b9b-aa319e57dexample f127bd27-cee4-443a-a76b-a5af9example 2012-08-30T17:11:09.449Z 2012-08-30T17:11:09.468Z active active Available 3 Sold 0 Cancelled 0 Pending 0

API Version 2014-10-01 239

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

11 2.5 USD true 10 2.5 USD false 9 2.5 USD false 8 2.00 USD false 7 2.0 USD false 6 2.0 USD false 5 1.5 USD false 4 1.5 USD false 3 0.7 USD false 2 0.7 USD

API Version 2014-10-01 240

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

false 1 0.1 USD false listRI1

3.

To view the details of your Reserved Instance listing, run DescribeReservedInstancesListings. The command should look like this example: http://ec2.amazonaws.com/?Action=DescribeReservedInstancesListings &AUTHPARAMS

Following is an example response. cec5c904-8f3a-4de5-8f5a-ff7f9example 5ec28771-05ff-4b9b-aa319e57dexample f127bd27-cee4-443a-a76b-a5af9example 2012-08-30T17:11:09.449Z 2012-08-30T17:11:09.468Z active active Available 3 Sold 0 Cancelled 0 Pending 0

API Version 2014-10-01 241

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

11 2.5 USD true 10 2.5 USD false 9 2.5 USD false 8 2.0 USD false 7 2.0 USD false 6 2.0 USD false 5 1.5 USD false 4 1.5 USD false 3 0.7 USD false 2 0.7 USD false

API Version 2014-10-01 242

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

1 0.1 USD false listRI1

Canceling and Changing Your Listings After listing your Reserved Instances in the Reserved Instance Marketplace, you can manage your listing using the AWS Management Console (p. 243), the Amazon EC2 CLI (p. 244), or the Amazon EC2 API (p. 246). You can view details of your listing. You also can cancel your listing, as long as it hasn't been purchased yet. Currently, you cannot modify your listing directly. However, you can change your listing by first canceling it and then creating another listing with new parameters. In this section, we will show you how to perform the tasks of viewing, canceling and changing your Reserved Instance Marketplace listings, using the console, the CLI, and the API.

AWS Management Console To view your listing 1. 2. 3. 4.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. Click Reserved Instances in the Navigation pane. Right-click your Reserved Instance. Click the My Listings tab. You will see details about the Reserved Instance listing you selected.

To cancel your listing You can cancel your listing at any time, as long as it's in the active state. You cannot cancel the listing if it's already matched or being processed for a sale. If some of the instances in your listing are matched and you cancel the listing, only the remaining unmatched instances will be removed from the listing.

API Version 2014-10-01 243

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

1. 2.

Go to the Reserved Instances page in the Amazon EC2 console, and right-click your Reserved Instance. On the My Listings tab, click Cancel Listing.

To change your listing Currently, you cannot modify your listing directly. However, you can change your listing by first canceling it and then creating another listing with new parameters. 1. 2.

Cancel your active Reserved Instance listing. For more information, see the previous procedure. Create a new listing. For more information, see Listing Your Reserved Instance (p. 234).

Amazon EC2 CLI To view your listing •

Run ec2-describe-reserved-instances-listing to get details about your listing. PROMPT> ec2-describe-reserved-instances-listings

Amazon EC2 returns output similar to the following: PROMPT> ec2-describe-reserved-instances-listings Type ReservedInstancesListingId ReservedInstancesId CreateDate UpdateDate Status StatusMessage LISTING 615d8a10-8224-4c19-ba7d-b9aa0example 1ba8e2e3-d20d-44ec-b202fcb6aexample Wed Aug 22 09:02:58 PDT 2012 Wed Aug 22 14:24:26 PDT 2012 can celled cancelled INSTANCE-COUNT available 0 INSTANCE-COUNT sold 0 INSTANCE-COUNT cancelled 1 INSTANCE-COUNT pending 0 PRICE-SCHEDULE 10 $1.2 PRICE-SCHEDULE 9 $1.08 PRICE-SCHEDULE 8 $0.96 PRICE-SCHEDULE 7 $0.84 PRICE-SCHEDULE 6 $0.72 PRICE-SCHEDULE 5 $0.6 PRICE-SCHEDULE 4 $0.48 PRICE-SCHEDULE 3 $0.36 PRICE-SCHEDULE 2 $0.24 PRICE-SCHEDULE 1 $0.12 LISTING d5fa5166-83c3-40e4-abb2-b7298example 1ba8e2e3-d20d-44ec-b202fcb6aexample Wed Aug 22 14:31:55 PDT 2012 Wed Aug 22 14:42:40 PDT 2012 closed

API Version 2014-10-01 244

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

closed INSTANCE-COUNT available 0 INSTANCE-COUNT sold 1 INSTANCE-COUNT cancelled 0 INSTANCE-COUNT pending 0 PRICE-SCHEDULE 10 $0.9 PRICE-SCHEDULE 9 $0.81 PRICE-SCHEDULE 8 $0.72 PRICE-SCHEDULE 7 $0.63 PRICE-SCHEDULE 6 $0.54 PRICE-SCHEDULE 5 $0.45 PRICE-SCHEDULE 4 $0.36 PRICE-SCHEDULE 3 $0.27 PRICE-SCHEDULE 2 $0.18 PRICE-SCHEDULE 1 $0.09 .... LISTING 095c0e18-c9e6-4692-97e5-653e0example b847fa93-c736-4eae-bca1e3147example Tue Aug 28 18:21:07 PDT 2012 Tue Aug 28 18:21:07 PDT 2012 active active INSTANCE-COUNT available 1 INSTANCE-COUNT sold 0 INSTANCE-COUNT cancelled 0 INSTANCE-COUNT pending 0 PRICE-SCHEDULE 5 $1.2 PRICE-SCHEDULE 4 $1.2 PRICE-SCHEDULE 3 $1.2 PRICE-SCHEDULE 2 $1.2 PRICE-SCHEDULE 1 $1.2

To cancel your listing You can cancel your listing at any time, as long as it's in the active state. You cannot cancel the listing if it's already matched or being processed for a sale. •

Run ec2-cancel-reserved-instances-listing to cancel your listing. PROMPT> ec2-cancel-reserved-instances-listing 095c0e18-c9e6-4692-97e5653e0example

Amazon EC2 returns output similar to the following: PROMPT> ec2-cancel-reserved-instances-listing Type ReservedInstancesListingId ReservedInstancesId CreateDate UpdateDate Status StatusMessage LISTING 095c0e18-c9e6-4692-97e5-653e0example b847fa93-c736-4eae-bca1e3147example Tue Aug 28 18:21:07 PDT 2012 Tue Aug 28 18:21:07 PDT 2012 can celled cancelled INSTANCE-COUNT available 0 INSTANCE-COUNT sold 0 INSTANCE-COUNT cancelled 1 INSTANCE-COUNT pending 0 PRICE-SCHEDULE 5 $1.2 PRICE-SCHEDULE 4 $1.2 PRICE-SCHEDULE 3 $1.2

API Version 2014-10-01 245

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

PRICE-SCHEDULE 2 $1.2 PRICE-SCHEDULE 1 $1.2

To change your listing Currently, you cannot modify your listing directly. However, you can change your listing by first canceling it and then creating another listing with new parameters. 1. 2.

Cancel your active Reserved Instance listing. For more information, see the previous procedure. Create a new listing. For more information, see Listing Your Reserved Instance (p. 234).

Amazon EC2 API To view your listing •

Call DescribeReservedInstancesListings to get details about your listing. The command should look like this example: http://ec2.amazonaws.com/?Action=DescribeReservedInstancesListings &AUTHPARAMS

Following is an example response. cec5c904-8f3a-4de5-8f5a-ff7f9example 5ec28771-05ff-4b9b-aa319e57dexample f127bd27-cee4-443a-a76b-a5af9example 2012-08-30T17:11:09.449Z 2012-08-30T21:00:42.300Z active active Available 2 Sold 1 Cancelled 0 Pending 0

API Version 2014-10-01 246

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

11 2.5 USD true 10 2.5 USD false 9 2.5 USD false 8 2.0 USD false 7 2.0 USD false 6 2.0 USD false 5 1.5 USD false 4 1.5 USD false 3 0.7 USD false 2

API Version 2014-10-01 247

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

0.7 USD false 1 0.1 USD false listRI1

To cancel your listing You can cancel your listing at any time, as long as it's in the active state. You cannot cancel the listing if it's already matched or being processed for a sale. •

Run CancelReservedInstancesListing to cancel your listing 5ec28771-05ff-4b9b-aa319e57dexample and remove it from the Reserved Instance Marketplace. The command should look like this example: https://ec2.amazonaws.com/?Action=CancelReservedInstancesListing &ReservedInstancesListingId.0=5ec28771-05ff-4b9b-aa31-9e57dexample &AUTHPARAMS

Following is an example response. bec2cf62-98ef-434a-8a15-886fcexample 5ec28771-05ff-4b9b-aa319e57dexample f127bd27-cee4-443a-a76b-a5af9example 2012-08-30T17:11:09.449Z 2012-08-31T14:12:23.468Z cancelled cancelled Available 0 Sold 1

API Version 2014-10-01 248

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

Cancelled 2 Pending 0 11 2.5 USD false 10 2.5 USD false 9 2.5 USD false 8 2.0 USD false 7 2.0 USD false 6 2.0 USD false 5 1.5 USD false 4 1.5 USD false

API Version 2014-10-01 249

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

3 0.7 USD false 2 0.7 USD false 1 0.1 USD false listRI1

In the response to the Cancel request, you see the canceled listing. Another way to see that canceled listing is by calling DescribeReservedInstancesListings.The request will look like this example: http://ec2.amazonaws.com/?Action=DescribeReservedInstancesListings &AUTHPARAMS

The response will look like the following example: bec2cf62-98ef-434a-8a15-367c0example 5ec28771-05ff-4b9b-aa319e57dexample f127bd27-cee4-443a-a76b-a5af9example 2012-08-30T17:11:09.449Z 2012-08-31T14:12:23.468Z cancelled cancelled Available 0 Sold 1 Cancelled

API Version 2014-10-01 250

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

2 Pending 0 11 2.5 USD false 10 2.5 USD false 9 2.5 USD false 8 2.0 USD false 7 2.0 USD false 6 2.0 USD false 5 1.5 USD false 4 1.5 USD false 3

API Version 2014-10-01 251

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

0.7 USD false 2 0.7 USD false 1 0.1 USD false listRI1

To change your listing Currently, you cannot modify your listing directly. However, you can change your listing by first canceling it and then creating another listing with new parameters. 1. 2.

Cancel your active Reserved Instance listing. For more information, see the previous procedure. Create a new listing. For more information, see Listing Your Reserved Instance (p. 234).

After Your Reserved Instance Is Sold Topics • Reserved Instance Listing States (p. 253) • Lifecycle of a Listing (p. 253) • Getting Paid (p. 254) • Notifications (p. 254) When your Reserved Instance is sold, AWS will send you an email notification. Each day that there is any kind of activity (for example, you create a listing; you sell a listing; or AWS sends funds to your account), you will get one email notification capturing all the activities of the day. For more information, see Notifications (p. 254). You can track the status of your Reserved Instance listings by looking at the My Listings tab of the selected Reserved Instance on the Reserved Instance page in the Amazon EC2 console. The tab contains the Listing State as well as information about the term, listing price, and a breakdown of how many instances in the listing are available, pending, sold, and cancelled. You can also use the ec2-describereserved-instances-listings CLI command or the DescribeReservedInstancesListings API call, with the appropriate filter to obtain information about your Reserved Instance listings.

API Version 2014-10-01 252

Amazon Elastic Compute Cloud User Guide for Linux Selling in the Reserved Instance Marketplace

Reserved Instance Listing States Listing State displays the current status of your Reserved Instance listings: • Active—The listing is available for purchase. • Cancelled—The listing is canceled and won't be available for purchase in the marketplace. • Closed—The Reserved Instance is not listed. A Reserved Instance might be Closed because the sale of the listing was completed. The information displayed by Listing State is about the status of your listing in the Reserved Instance Marketplace. It is different from the status information that is displayed by the State column in the Reserved Instance page.This State information is about your Reserved Instance. For more information, see Reserved Instance States (p. 213).

Lifecycle of a Listing Now that you have created a listing, let's walk through what happens when your listing sells. When all the instances in your listing are matched and sold, the My Listings tab shows that your Total instance count matches the count listed under Sold, there are no Available instances left for your listing, and its Status is closed. When only a portion of your listing is sold, AWS retires the Reserved Instances in the listing and creates the number of Reserved Instances equal to the Reserved Instances remaining in the count. So, the Reserved Instances listing ID and the listing that it represents, which now has an instance count of fewer instances for sale, is still active. Any future sales of Reserved Instances in this listing are processed this way. When all the Reserved Instances in the listing are sold, AWS marks the listing as closed. For example, let's say you created a listing Reserved Instances listing ID 5ec28771-05ff-4b9b-aa319e57dexample with an instance count of 5. Your My Listings tab in the Reserved Instance page of the Amazon EC2 console will display the listing this way: Reserved Instance listing ID 5ec28771-05ff-4b9b-aa31-9e57dexample • Total instance count = 5 • Sold = 0 • Available = 5 • Status = active Let's say that a buyer purchases two of the instances, which leaves a count of three instances still available for sale. As a result of this partial sale, AWS creates a new Reserved Instance with an instance count of three to represent the remaining three that are still for sale. This is how your listing will look in your My Listings tab: Reserved Instance listing ID 5ec28771-05ff-4b9b-aa31-9e57dexample • Total instance count = 5 • Sold = 2 • Available = 3 • Status = active

API Version 2014-10-01 253

Amazon Elastic Compute Cloud User Guide for Linux Requirements Checklist for Reserved Instances

If you decide to cancel your listing and a portion of that listing has already sold, the cancellation is not effective on the portion that has been sold. Only the portion of the listing not yet sold will no longer be available in the Reserved Instance Marketplace.

Getting Paid As soon as AWS receives funds from the buyer of your Reserved Instance, AWS sends a message to your email address—that is, the email address associated with the account that is registered as owner of the Reserved Instance that was sold. AWS sends an Automated Clearing House (ACH) wire transfer to the bank account that you specified when you registered for the Reserved Instance Marketplace. Typically, this transfer occurs between one to three days after your Reserved Instance has been matched.You can view the state of this disbursem*nt by viewing your Reserved Instance disbursem*nt report. Disbursem*nts take place once a day. Keep in mind that you will not be able to receive disbursem*nts until AWS has received verification from your bank. This period can take up to two weeks. The Reserved Instance you sold will continue to appear in the results of DescribeReservedInstances calls you make.

Notifications As a seller in the Reserved Instance Marketplace, you will receive an email digest of the Reserved Instance Marketplace activities pertaining to your account. On any given day, you will receive one email digest, and you will only receive this email if one or a combination of activities occurred that day: • You created a new listing in the Reserved Instance Marketplace. • You sold one or more of the Reserved Instances you listed. • AWS posted a disbursem*nt to your bank account as a result of a sale of part or all of your listing in the Reserved Instance Marketplace. Your email digest will look similar to the following:

Requirements Checklist for Reserved Instances Amazon EC2 Reserved Instances and the Reserved Instance Marketplace can be a powerful and costsaving strategy for running your business. However, before you use Reserved Instances or the Reserved Instance Marketplace, ensure that you meet the requirements for purchase and sale. You also must understand the details and restrictions on certain elements of Reserved Instances and the Reserved Instance Marketplace—including seller registration, banking, using the AWS free tier, dealing with cancelled instances, and so on. Use this topic as a checklist for buying and selling Reserved Instances, and for buying and selling in the Reserved Instance Marketplace.

API Version 2014-10-01 254

Amazon Elastic Compute Cloud User Guide for Linux Requirements Checklist for Reserved Instances

Note To purchase and modify Reserved Instances, ensure that your account has the appropriate permissions, such as the ability to describe Availability Zones. For information, see the IAM Best Practices and the Permissions and Policies sections in the Using IAM guide. Reserved Instances • AWS account—You need to have an AWS account in order to purchase Reserved Instances. If you don't have an AWS account, you should read and complete the instructions described in Getting Started with Amazon EC2 Linux Instances (p. 26), which provides information on signing up for your Amazon EC2 account and credentials. • AWS free tier—The AWS free usage tier is available for new AWS accounts. If you are using the AWS free usage tier to run Amazon EC2 instances, and then you purchase a Reserved Instance, you will be charged for the Reserved Instance under standard pricing guidelines. For information about the free tier and the applicable services and usage amounts, see AWS Free Usage Tier. Buying Reserved Instances • Usage fee for Heavy Utilization—With Light Utilization and Medium Utilization Reserved Instances, you pay a one-time upfront fee and then only pay the hourly price when you use the instance. With Heavy Utilization Reserved Instances, you pay a low, one-time upfront fee and commit to paying an hourly rate for every hour of the Reserved Instance's term whether or not you use it. For information, see Choosing Reserved Instances Based on Your Usage Plans (p. 191). • Tiered discounts on purchases—The Reserved Instance pricing tier discounts only apply to purchases made from AWS. These discounts do not apply to purchases of third-party Reserved Instances. For information, see Understanding Reserved Instance Pricing Tiers (p. 193). • Cancellation of purchase—Before you confirm your purchase, review the details of the Reserved Instances that you plan to buy, and make sure that all the parameters are accurate. After you purchase a Reserved Instance (either from a third-party seller in the Reserved Instance Marketplace or from AWS), you cannot cancel your purchase. However, you can sell the Reserved Instance if your needs change. For information, see Selling Your Reserved Instances (p. 233). Selling Reserved Instances and the Reserved Instance Marketplace • Seller requirement—To become a seller in the Reserved Instance Marketplace, you must register as a seller. For information, see Selling Your Reserved Instances (p. 233). • Bank requirement—AWS must have your bank information in order to disburse funds collected when you sell your Reserved Instance. The bank you specify must have a US address. For more information, see Your Bank (p. 230). • Tax requirement—Sellers who have 200 or more transactions or who plan to sell $20,000 or more in Reserved Instances will have to provide additional information about their business for tax reasons. For information, see Tax Information (p. 231). • Minimum selling—The minimum price allowed in the Reserved Instance Marketplace is $1.01. • When Reserved Instances can be sold—Reserved Instances can be sold only after AWS has received the upfront payment and the Reserved Instance has been active (you've owned it) for at least 30 days. In addition, there must be at least a month remaining in the term of the Reserved Instance you are listing. • Modifying your listing—Currently, you cannot modify your listing in the Reserved Instance Marketplace directly. However, you can change your listing by first canceling it and then creating another listing with new parameters. For information, see Canceling and Changing Your Listings (p. 243). You also can change your Reserved Instances before listing them. For information, see Modifying Your Reserved Instances (p. 218). • Selling discounted Reserved Instances—Amazon EC2 Reserved Instances purchased at a reduced cost resulting from a tiering discount cannot be sold in the Reserved Instance Marketplace. For more information, see Reserved Instance Marketplace (p. 200). API Version 2014-10-01 255

Amazon Elastic Compute Cloud User Guide for Linux Instance Metadata and User Data

• Service fee—AWS will charge you a service fee of 12 percent of the total upfront price of each Reserved Instance you sell in the marketplace. (The upfront price is the price the seller is charging for his Reserved Instance.) • Other AWS Reserved Instances—Only Amazon EC2 Reserved Instances can be sold in the Reserved Instance Marketplace. Other AWS Reserved Instances, such as Amazon Relational Database Service (Amazon RDS) and Amazon ElastiCache Reserved Instances cannot be sold in the Reserved Instance Marketplace.

Instance Metadata and User Data Instance metadata is data about your instance that you can use to configure or manage the running instance. Instance metadata is divided into categories. For more information, see Instance Metadata Categories (p. 262). EC2 instances can also include dynamic data, such as an instance identity document that is generated when the instance is launched. For more information, see Dynamic Data Categories (p. 266). You can also access the user data that you supplied when launching your instance. For example, you can specify parameters for configuring your instance, or attach a simple script.You can also use this data to build more generic AMIs that can be modified by configuration files supplied at launch time. For example, if you run web servers for various small businesses, they can all use the same AMI and retrieve their content from the Amazon S3 bucket you specify in the user data at launch. To add a new customer at any time, simply create a bucket for the customer, add their content, and launch your AMI. If you launch more than one instance at the same time, the user data is available to all instances in that reservation. Because you can access instance metadata and user data from within your running instance, you do not need to use the Amazon EC2 console or the CLI tools. This can be helpful when you're writing scripts to run from within your instance. For example, you can access your instance's local IP address from within the running instance to manage a connection to an external application.

Important Although you can only access instance metadata and user data from within the instance itself, the data is not protected by cryptographic methods. Anyone who can access the instance can view its metadata.Therefore, you should take suitable precautions to protect sensitive data (such as long-lived encryption keys). You should not store sensitive data, such as passwords, as user data. For more information about adding user data when you launch an instance, see Launching an Instance (p. 290).You can add or modify user data on Amazon EBS-backed instances when they're stopped. For more information about adding user data to a stopped instance, see Modifying a Stopped Instance (p. 311). When you are adding user data, take note of the following: • User data is treated as opaque data: what you give is what you get back. It is up to the instance to be able to interpret it. • User data is limited to 16 KB. This limit applies to the data in raw form, not base64-encoded form. • User data must be base64-encoded before being submitted to the API. The API command line tools perform the base64 encoding for you. The data is decoded before being presented to the instance. For more information about base64 encodings, go to http://tools.ietf.org/html/rfc4648. Topics • Retrieving Instance Metadata (p. 257) • Retrieving User Data (p. 259) • Retrieving Dynamic Data (p. 260) API Version 2014-10-01 256

Amazon Elastic Compute Cloud User Guide for Linux Retrieving Instance Metadata

• Example: AMI Launch Index Value (p. 260) • Instance Metadata Categories (p. 262)

Retrieving Instance Metadata To view all categories of instance metadata from within a running instance, use the following URI: http://169.254.169.254/latest/meta-data/

Note that you are not billed for HTTP requests used to retrieve instance metadata and user data. You can use a tool such as cURL, or if your instance supports it, the GET command; for example: $ curl http://169.254.169.254/latest/meta-data/

$ GET http://169.254.169.254/latest/meta-data/

You can also download the Instance Metadata Query tool, which allows you to query the instance metadata without having to type out the full URI or category names: http://aws.amazon.com/code/1825 All metadata is returned as text (content type text/plain). A request for a specific metadata resource returns the appropriate value, or a 404 - Not Found HTTP error code if the resource is not available. A request for a general metadata resource (the URI ends with a /) returns a list of available resources, or a 404 - Not Found HTTP error code if there is no such resource. The list items are on separate lines, terminated by line feeds (ASCII 10).

Examples of Retrieving Instance Metadata This example gets the available versions of the instance metadata. These versions do not necessarily correlate with an Amazon EC2 API version. The earlier versions are available to you in case you have scripts that rely on the structure and information present in a previous version. $ curl http://169.254.169.254/ 1.0 2007-01-19 2007-03-01 2007-08-29 2007-10-10 2007-12-15 2008-02-01 2008-09-01 2009-04-04 2011-01-01 2011-05-01 2012-01-12 2014-02-25 latest

This example gets the top-level metadata items. Some items are only available for instances in a VPC. For more information about each of these items, see Instance Metadata Categories (p. 262).

API Version 2014-10-01 257

Amazon Elastic Compute Cloud User Guide for Linux Retrieving Instance Metadata

$ curl http://169.254.169.254/latest/meta-data/ ami-id ami-launch-index ami-manifest-path block-device-mapping/ hostname instance-action instance-id instance-type kernel-id local-hostname local-ipv4 mac network/ placement/ public-hostname public-ipv4 public-keys/ reservation-id security-groups services/

These examples get the value of some of the metadata items from the preceding example. $ curl http://169.254.169.254/latest/meta-data/ami-id ami-2bb65342

$ curl http://169.254.169.254/latest/meta-data/reservation-id r-fea54097

$ curl http://169.254.169.254/latest/meta-data/hostname ec2-203-0-113-25.compute-1.amazonaws.com

This example gets the list of available public keys. $ curl http://169.254.169.254/latest/meta-data/public-keys/ 0=my-public-key

This example shows the formats in which public key 0 is available. $ curl http://169.254.169.254/latest/meta-data/public-keys/0 openssh-key

This example gets public key 0 (in the OpenSSH key format). $ curl http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key ssh-rsa MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6 b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z

API Version 2014-10-01 258

Amazon Elastic Compute Cloud User Guide for Linux Retrieving User Data

b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ 21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4 nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE my-public-key

This example shows the information available for a specific network interface (indicated by the MAC address) on an NAT instance in the EC2-Classic platform. $ curl http://169.254.169.254/latest/meta-data/network/inter faces/macs/02:29:96:8f:6a:2d/ device-number local-hostname local-ipv4s mac owner-id public-hostname public-ipv4s

This example gets the subnet ID for an instance launched into a VPC. $ curl http://169.254.169.254/latest/meta-data/network/inter faces/macs/02:29:96:8f:6a:2d/subnet-id subnet-be9b61d7

Retrieving User Data To retrieve user data, use the following URI: http://169.254.169.254/latest/user-data

Requests for user data returns the data as it is (content type application/x-octetstream). This shows an example of returning comma-separated user data. $ curl http://169.254.169.254/latest/user-data 1234,john,reboot,true | 4512,richard, | 173,,,

This shows an example of returning line-separated user data. $ curl http://169.254.169.254/latest/user-data [general] instances: 4 [instance-0] s3-bucket: [instance-1] reboot-on-error: yes

API Version 2014-10-01 259

Amazon Elastic Compute Cloud User Guide for Linux Retrieving Dynamic Data

Retrieving Dynamic Data To retrieve dynamic data from within a running instance, use the following URI: http://169.254.169.254/latest/dynamic/

This example shows how to retrieve the high-level instance identity categories: $ curl http://169.254.169.254//latest/dynamic/instance-identity/ pkcs7 signature document

Example: AMI Launch Index Value This example demonstrates how you can use both user data and instance metadata to configure your instances. Alice wants to launch four instances of her favorite Linux database AMI, with the first acting as master and the remaining three acting as replicas. When she launches them, she wants to add user data about the replication strategy for each replicant. She is aware that this data will be available to all four instances, so she needs to structure the user data in a way that allows each instance to recognize which parts are applicable to it. She can do this using the ami-launch-index instance metadata value, which will be unique for each instance. Here is the user data that Alice has constructed: replicate-every=1min | replicate-every=5min | replicate-every=10min

The replicate-every=1min data defines the first replicant's configuration, replicate-every=5min defines the second replicant's configuration, and so on. Alice decides to provide this data as an ASCII string with a pipe symbol (|) delimiting the data for the separate instances. Alice launches four instances, specifying the user data: $ ec2-run-instances ami-2bb65342 -n 4 -d "replicate-every=1min | replicateevery=5min | replicate-every=10min" RESERVATION r-fea54097 598916040194 default INSTANCE i-10a64379 ami-2bb65342 pending 0 m1.small 2010-03-19T13:59:03+0000 us-east-1a aki-94c527fd ari-96c527ff monitoring-disabled ebs INSTANCE i-10a64380 ami-2bb65342 pending 0 m1.small 2010-03-19T13:59:03+0000 us-east-1a aki-94c527fd ari-96c527ff monitoring-disabled ebs INSTANCE i-10a64381 ami-2bb65342 pending 0 m1.small 2010-03-19T13:59:03+0000 us-east-1a aki-94c527fd ari-96c527ff monitoring-disabled ebs INSTANCE i-10a64382 ami-2bb65342 pending 0 m1.small 2010-03-19T13:59:03+0000 us-east-1a aki-94c527fd ari-96c527ff monitoring-disabled ebs

After they're launched, all instances have a copy of the user data and the common metadata shown here: • AMI id: ami-2bb65342 • Reservation ID: r-fea54097 • Public keys: none

API Version 2014-10-01 260

Amazon Elastic Compute Cloud User Guide for Linux Example: AMI Launch Index Value

• Security group name: default • Instance type: m1.small However, each instance has certain unique metadata. Instance 1 Metadata

Value

instance-id

i-10a64379

ami-launch-index

public-hostname

ec2-203-0-113-25.compute-1.amazonaws.com

public-ipv4

67.202.51.223

local-hostname

ip-10-251-50-12.ec2.internal

local-ipv4

10.251.50.35

Instance 2 Metadata

Value

instance-id

i-10a64380

ami-launch-index

1

public-hostname

ec2-67-202-51-224.compute-1.amazonaws.com

public-ipv4

67.202.51.224

local-hostname

ip-10-251-50-36.ec2.internal

local-ipv4

10.251.50.36

Instance 3 Metadata

Value

instance-id

i-10a64381

ami-launch-index

2

public-hostname

ec2-67-202-51-225.compute-1.amazonaws.com

public-ipv4

67.202.51.225

local-hostname

ip-10-251-50-37.ec2.internal

local-ipv4

10.251.50.37

Instance 4

API Version 2014-10-01 261

Amazon Elastic Compute Cloud User Guide for Linux Instance Metadata Categories

Metadata

Value

instance-id

i-10a64382

ami-launch-index

3

public-hostname

ec2-67-202-51-226.compute-1.amazonaws.com

public-ipv4

67.202.51.226

local-hostname

ip-10-251-50-38.ec2.internal

local-ipv4

10.251.50.38

Alice can use the ami-launch-index value to determine which portion of the user data is applicable to a particular instance. 1. She connects to one of the instances, and retrieves the ami-launch-index for that instance to ensure it is one of the replicants: $ curl http://169.254.169.254/latest/meta-data/ami-launch-index 2

2. She saves the ami-launch-index as a variable: $ ami_launch_index=`curl http://169.254.169.254/latest/meta-data/ami-launchindex`

3. She saves the user data as a variable: $ user_data=`curl http://169.254.169.254/latest/user-data/`

4. Finally, Alice runs a Linux cut command to extract the portion of the user data that is applicable to that instance: $ echo $user_data | cut -d"|" -f"$ami_launch_index" replicate-every=5min

Instance Metadata Categories The following table lists the categories of instance metadata. Data

Description

Version Introduced

ami-id

The AMI ID used to launch the instance.

1.0

API Version 2014-10-01 262

Amazon Elastic Compute Cloud User Guide for Linux Instance Metadata Categories

Data

Description

ami-launch-index

If you started more than one instance 1.0 at the same time, this value indicates the order in which the instance was launched.The value of the first instance launched is 0.

ami-manifest-path

The path to the AMI's manifest file in Amazon S3. If you used an Amazon EBS-backed AMI to launch the instance, the returned result is unknown.

ancestor-ami-ids

The AMI IDs of any instances that were 2007-10-10 rebundled to create this AMI. This value will only exist if the AMI manifest file contained an ancestor-amis key.

block-device-mapping/ami

The virtual device that contains the root/boot file system.

block-device-mapping/ebs N

The virtual devices associated with 2007-12-15 Amazon EBS volumes, if any are present. This value is only available in metadata if it is present at launch time. The N indicates the index of the Amazon EBS volume (such as ebs1 or ebs2).

block-device-mapping/eph emeral N

The virtual devices associated with 2007-12-15 ephemeral devices, if any are present. The N indicates the index of the ephemeral volume.

block-device-mapping/root

The virtual devices or partitions associated with the root devices, or partitions on the virtual device, where the root (/ or C:) file system is associated with the given instance.

2007-12-15

block-device-mapping/swap

The virtual devices associated with swap. Not always present.

2007-12-15

hostname

The private hostname of the instance. 1.0 In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).

iam/info

Returns information about the last time 2012-01-12 the instance profile was updated, including the instance's LastUpdated date, InstanceProfileArn, and InstanceProfileId.

API Version 2014-10-01 263

Version Introduced

1.0

2007-12-15

Amazon Elastic Compute Cloud User Guide for Linux Instance Metadata Categories

Data

Description

Version Introduced

iam/security-credentials /role-name

Where role-name is the name of the IAM role associated with the instance. Returns the temporary security credentials (AccessKeyId, SecretAccessKey, SessionToken, and Expiration) associated with the IAM role.

2012-01-12

instance-action

Notifies the instance that it should 2008-09-01 reboot in preparation for bundling. Valid values: none | shutdown | bundle-pending.

instance-id

The ID of this instance.

instance-type

The type of instance. For more 2007-08-29 information, see Instance Types (p. 103).

kernel-id

The ID of the kernel launched with this 2008-02-01 instance, if applicable.

local-hostname

The private DNS hostname of the 2007-01-19 instance. In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).

local-ipv4

The private IP address of the instance. 1.0 In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).

mac

The instance's media access control 2011-01-01 (MAC) address. In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0).

network/interfaces/macs/ mac/device-number

The device number associated with that 2011-01-01 interface. Each interface must have a unique device number. The device number serves as a hint to device naming in the instance; for example, device-number is 2 for the eth2 device.

network/interfaces/macs/ mac/ipv4-associations/pu blic-ip

The private IPv4 addresses that are 2011-01-01 associated with each public-ip address and assigned to that interface.

network/interfaces/macs/ mac/local-hostname

The interface's local hostname.

2011-01-01

network/interfaces/macs/ mac/local-ipv4s

The private IP addresses associated with the interface.

2011-01-01

API Version 2014-10-01 264

1.0

Amazon Elastic Compute Cloud User Guide for Linux Instance Metadata Categories

Data

Description

Version Introduced

network/interfaces/macs/ mac/mac

The instance's MAC address.

2011-01-01

network/interfaces/macs/ mac/owner-id

The ID of the owner of the network 2011-01-01 interface. In multiple-interface environments, an interface can be attached by a third party, such as Elastic Load Balancing. Traffic on an interface is always billed to the interface owner.

network/interfaces/macs/ mac/public-hostname

The interface's public DNS. If the 2011-01-01 instance is in a VPC, this category is only returned if the enableDnsHostnames attribute is set to true. For more information, see Using DNS with Your VPC.

network/interfaces/macs/ mac/public-ipv4s

The Elastic IP addresses associated with the interface. There may be multiple IP addresses on an instance.

2011-01-01

network/interfaces/macs/ mac/security-groups

Security groups to which the network interface belongs. Returned only for instances launched into a VPC.

2011-01-01

network/interfaces/macs/ mac/security-group-ids

IDs of the security groups to which the 2011-01-01 network interface belongs. Returned only for instances launched into a VPC. For more information on security groups in the EC2-VPC platform, see Security Groups for Your VPC.

network/interfaces/macs/ mac/subnet-id

The ID of the subnet in which the interface resides. Returned only for instances launched into a VPC.

2011-01-01

network/interfaces/macs/ The CIDR block of the subnet in which 2011-01-01 mac/subnet-ipv4-cidr-block the interface resides. Returned only for instances launched into a VPC. network/interfaces/macs/ mac/vpc-id

The ID of the VPC in which the interface resides. Returned only for instances launched into a VPC.

network/interfaces/macs/ mac/vpc-ipv4-cidr-block

The CIDR block of the VPC in which 2011-01-01 the interface resides. Returned only for instances launched into a VPC.

placement/availability-z one

The Availability Zone in which the instance launched.

2008-02-01

product-codes

Product codes associated with the instance, if any.

2007-03-01

API Version 2014-10-01 265

2011-01-01

Amazon Elastic Compute Cloud User Guide for Linux Instance Metadata Categories

Data

Description

Version Introduced

public-hostname

The instance's public DNS. If the 2007-01-19 instance is in a VPC, this category is only returned if the enableDnsHostnames attribute is set to true. For more information, see Using DNS with Your VPC.

public-ipv4

The public IP address. If an Elastic IP 2007-01-19 address is associated with the instance, the value returned is the Elastic IP address.

public-keys/0/openssh-key

Public key. Only available if supplied at 1.0 instance launch time.

ramdisk-id

The ID of the RAM disk specified at launch time, if applicable.

2007-10-10

reservation-id

ID of the reservation.

1.0

security-groups

The names of the security groups applied to the instance.

1.0

Note Only instances launched into a VPC can change security groups after launch. These changes will be reflected here and in network/interfaces/macs/mac/security-groups. services/domain

The domain for AWS resources for the 2014-02-25 region; for example, amazonaws.com for us-east-1.

Dynamic Data Categories The following table lists the categories of dynamic data. Data

Description

Version introduced

fws/instance-monitoring Value showing whether the customer has enabled detailed 2009-04-04 one-minute monitoring in CloudWatch. Valid values: enabled | disabled instance-identity/docume JSON containing instance attributes, such as instance-id, nt private IP address, etc.

2009-04-04

instance-identity/pkcs7 Used to verify the document's authenticity and content against the signature.

2009-04-04

instance-identity/signat Data that can be used by other parties to verify its origin ure and authenticity.

2009-04-04

API Version 2014-10-01 266

Amazon Elastic Compute Cloud User Guide for Linux Importing and Exporting Instances

Importing and Exporting Instances You can use the Amazon Web Services (AWS) VM Import/Export tools to import virtual machine (VM) images from your local environment into AWS and convert them into ready-to-use Amazon EC2 instances. Later, you can export the VM images back to your local environment. VM Import/Export allows you to leverage your existing investments in the virtual machines that you have built to meet your IT security, configuration management, and compliance requirements by bringing those VMs into Amazon Elastic Compute Cloud (Amazon EC2) as ready-to-use instances. VM Import/Export is compatible with Citrix Xen, Microsoft Hyper-V, or VMware vSphere virtualization environments. If you're using VMware vSphere, you can also use the AWS Connector for vCenter to export a VM from VMware and import it into Amazon EC2. For more information, see Migrating Your Virtual Machine to Amazon EC2 Using AWS Connector for vCenter in the AWS Management Portal for vCenter User Guide. VM Import/Export can be used to migrate applications and workloads, copy your VM image catalog, or create a disaster recovery repository for VM images. • Migrate existing applications and workloads to Amazon EC2—You can migrate your VM-based applications and workloads to Amazon EC2 and preserve their software and configuration settings. After you import your applications and workloads into an Amazon EC2 instance, you can create Amazon Machine Images (AMIs) and run multiple copies of the same image. You can also create snapshots and use them to back up your data.You can use AMI and snapshot copies to replicate your applications and workloads around the world. For more information about AMI copy, see Copying an AMI (p. 85). • Copy your VM image catalog to Amazon EC2—You can copy your existing VM image catalog into Amazon EC2. If you maintain a catalog of approved VM images, you can copy your image catalog to Amazon EC2 and create Amazon EC2 instances from the imported VM images.Your existing software, including products that you have installed such as anti-virus software, intrusion detection systems, and so on, can be imported along with your VM images. You can use the resulting Amazon EC2 instances to create Amazon EC2 AMIs. You can use the AMIs as your image catalog within Amazon EC2. • Create a disaster recovery repository for VM images—You can import your local VM images into Amazon EC2 for backup and disaster recovery purposes.You can store the imported images as Amazon Elastic Block Store (Amazon EBS)-backed AMIs so they're ready to launch in Amazon EC2 when you need them. If your local environment suffers an event, you can quickly launch your instances to preserve business continuity while simultaneously exporting them to rebuild your local infrastructure. The following diagram shows the process of exporting a VM from your on-premises virtualization environment to AWS.

API Version 2014-10-01 267

Amazon Elastic Compute Cloud User Guide for Linux Prerequisites

Contents • VM Import/Export Prerequisites (p. 268) • Importing a VM into Amazon EC2 (p. 270) • Exporting Amazon EC2 Instances (p. 279) • Troubleshooting VM Import/Export (p. 280)

VM Import/Export Prerequisites Before you begin the process of exporting an instance from your virtualization environment or importing and exporting a VM from Amazon EC2, you must be aware of the operating systems and image formats that AWS supports, and understand the limitations on exporting instances and volumes. If you plan to use the command line tools to export your instance, you must also download and install them. For more information, see Setting Up the Amazon EC2 Tools. Contents • Operating Systems (p. 268) • Image Formats (p. 269) • Instance Types (p. 269) • Requirements and Limitations (p. 269)

Operating Systems The following operating systems can be imported into and exported from Amazon EC2. Windows (32- and 64-bit) • • • • • •

Microsoft Windows Server 2012 R2 (Standard) Microsoft Windows Server 2012 (Standard, Datacenter) Microsoft Windows Server 2008 R2 (Standard, Datacenter, Enterprise) Microsoft Windows Server 2008 (Standard, Datacenter, Enterprise) Microsoft Windows Server 2003 R2 (Standard, Datacenter, Enterprise) Microsoft Windows Server 2003 (Standard, Datacenter, Enterprise) with Service Pack 1 (SP1) or later

Linux/Unix (64-bit) • Red Hat Enterprise Linux (RHEL) 5.1-5.10, 6.1-6.5

Note RHEL 6.0 is unsupported because it lacks the drivers required to run on Amazon EC2. VM Import supports license portability for RHEL instances. Your existing RHEL licenses are imported along with their associated RHEL instance. For more information about eligibility for Red Hat Cloud Access, see Eligibility at the Red Hat website. • CentOS 5.1-5.10, 6.1-6.5

Note CentOS 6.0 is unsupported because it lacks the drivers required to run on Amazon EC2. • Ubuntu 12.04, 12.10, 13.04, 13.10 • Debian 6.0.0-6.0.8, 7.0.0-7.2.0

API Version 2014-10-01 268

Amazon Elastic Compute Cloud User Guide for Linux Prerequisites

Image Formats The following formats can be imported into and exported from Amazon EC2. Importing Image Formats into Amazon EC2 AWS supports the following image formats for importing both volumes and instances into Amazon EC2: • RAW format for importing volumes and instances. • Virtual Hard Disk (VHD) image formats, which are compatible with Microsoft Hyper-V and Citrix Xen virtualization products. • ESX Virtual Machine Disk (VMDK) image formats, which are compatible with VMware ESX and VMware vSphere virtualization products.

Note You can only import VMDK files into Amazon EC2 that were created through the OVF export process in VMware.

Exporting Image Formats from Amazon EC2 AWS supports the following image formats for exporting both volumes and instances from Amazon EC2: • Open Virtual Appliance (OVA) image format, which is compatible with VMware vSphere versions 4 and 5. • Virtual Hard Disk (VHD) image format, which is compatible with Citrix Xen and Microsoft Hyper-V virtualization products. • Stream-optimized ESX Virtual Machine Disk (VMDK) image format, which is compatible with VMware ESX and VMware vSphere versions 4 and 5 virtualization products.

Instance Types AWS supports importing Windows instances into any instance type. Linux instances can be imported into the following instance types: • General purpose: t2.micro | t2.small | t2.medium | m3.medium | m3.large | m3.xlarge | m3.2xlarge • Compute optimized: c3.large | c3.xlarge | c3.2xlarge | c3.4xlarge | cc2.8xlarge • Memory optimized: cr1.8xlarge • Storage optimized: hi1.4xlarge | hs1.8xlarge | i2.xlarge | i2.2xlarge | i2.4xlarge • GPU: cg1.4xlarge

Requirements and Limitations Known Limitations for Importing a VM into Amazon EC2 Importing instances and volumes is subject to the following limitations: • You can have up to five import tasks in progress at the same time per region. • Imported instances create EC2 instances that use Hardware Virtual Machine (HVM) virtualization. Creating instances that use Paravirtual (PV) virtualization using VM Import is not supported. Linux PVHVM drivers are supported within imported instances. • Imported Red Hat Enterprise Linux (RHEL) instances must use Cloud Access (BYOL) licenses. • Imported Linux instances must use 64-bit images. Importing 32-bit Linux images is not supported. API Version 2014-10-01 269

Amazon Elastic Compute Cloud User Guide for Linux Importing a VM into Amazon EC2

• Imported Linux instances should use default kernels for best results. VMs that use custom Linux kernels might not import successfully. • Typically, you import a compressed version of a disk image; the expanded image cannot exceed 1 TiB. • Make sure your VM only uses a single disk. Importing a VM with more than one disk is not supported. For Linux VMs, /boot and / can be located in different partitions, but they need to be on the same disk. We suggest that you import the VM with only the boot volume, and import any additional disks using the ec2-import-volume command. After the ImportInstance task is complete, use the ec2-attachvolume command to associate the additional volumes with your instance. • Make sure that you have at least 250 MB of available disk space for installing drivers and other software on any VM you want to import into an Amazon EC2 instance running Microsoft Windows. • Imported instances automatically have access to the Amazon EC2 instance store, which is temporary disk storage from disks that are physically attached to the host computer.You cannot disable this during import. For more information about instance storage, see Amazon EC2 Instance Store (p. 581). • Tasks must complete within 7 days of the start date. • Multiple network interfaces are not currently supported. When converted and imported, your instance will have a single virtual NIC using DHCP for address assignment. • Internet Protocol version 6 (IPv6) IP addresses are not supported. • For vCenter 4.0 and vSphere 4.0 users, remove any attached CD-ROM images or ISOs from the virtual machine. • Amazon VM Import does not install the single root I/O virtualization (SR-IOV) drivers on the c3 and i2 instance types, except for imports of Microsoft Windows Server 2012 R2 VMs. These drivers are not required unless you plan to use enhanced networking, which provides higher performance (packets per second), lower latency, and lower jitter. To enable enhanced networking on a c3 or i2 instance type after you import your VM, see Enabling Enhanced Networking on Linux Instances in a VPC (p. 507). For Microsoft Windows Server 2012 R2 VMs, SR-IOV driver are automatically installed as a part of the import process. Known Limitations for Exporting a VM from Amazon EC2 Exporting instances and volumes is subject to the following limitations: • • • •

You cannot export Amazon Elastic Block Store (Amazon EBS) data volumes. You cannot export an instance that has more than one virtual disk. You cannot export an instance that has more than one network interface. You cannot export an instance from Amazon EC2 unless you previously imported it into Amazon EC2 from another virtualization environment.

Importing a VM into Amazon EC2 There are two ways you can launch an instance in Amazon EC2. You can launch an instance from an Amazon Machine Image (AMI), or, you can launch an instance from a virtual machine (VM) that you imported from a virtualization environment such as Citrix Xen, Microsoft Hyper-V, or VMware vSphere. This section covers importing a VM and launching it as an Amazon EC2 instance. For more information about how to launch an Amazon EC2 instance from an AMI, see Launch Your Instance (p. 289). To use your VM as an instance in Amazon EC2, you must first export it from the virtualization environment, and then import it to Amazon EC2 using the Amazon EC2 command line interface (CLI) or API tools. If you're importing a VM from VMware vCenter, you can also use the AWS Connector for vCenter to export a VM from VMware and import it into Amazon EC2. For more information, see Migrating Your Virtual Machine to Amazon EC2 Using AWS Connector for vCenter in the AWS Management Portal for vCenter User Guide.

API Version 2014-10-01 270

Amazon Elastic Compute Cloud User Guide for Linux Importing a VM into Amazon EC2

Whether you use the CLI or the API, you will follow the same steps for importing VMs or volumes into Amazon EC2. This is the process for using the CLI.

To import a VM into Amazon EC2 1.

Install the CLI. For more information, see Step 1: Install the Amazon EC2 CLI (p. 271).

2. 3.

Prepare the VM for import to Amazon EC2. For more information, see Step 2: Prepare Your VM (p. 272). Export the VM from the virtualization environment. For more information, see Step 3: Export Your VM from Its Virtual Environment (p. 272). Import the VM into Amazon EC2. For information, see Step 4: Importing Your VM into Amazon EC2 (p. 273).

4. 5.

Launch the instance in Amazon EC2. For more information, see Step 5: Launch the instance in Amazon EC2 (p. 279).

Step 1: Install the Amazon EC2 CLI You need to install the Amazon EC2 CLI to import your Citrix, Microsoft Hyper-V, or VMware vSphere virtual machines into Amazon EC2 or to export them from Amazon EC2. If you haven't already installed the Amazon EC2 CLI, see Setting Up the Amazon EC2 Tools. You'll use the following Amazon EC2 commands to import or export a VM. Command

Description

ec2-import-instance

Creates a new import instance task using metadata from the specified disk image and imports the instance to Amazon EC2.

ec2-import-volume

Creates a new import volume task using metadata from the specified disk image and imports the volume to Amazon EC2.

ec2-resume-import

Resumes the upload of a disk image associated with an import instance or import volume task ID.

ec2-describe-conversion-tasks

Lists and describes your import tasks.

ec2-cancel-conversion-task

Cancels an active import task. The task can be the import of an instance or volume.

ec2-delete-disk-image

Deletes a partially or fully uploaded disk image for import from an Amazon S3 bucket.

ec2-create-image-export-task

Exports a running or stopped instance to an Amazon S3 bucket.

ec2-cancel-export-task

Cancels an active export task.

ec2-describe-export-tasks

Lists and describes your export tasks, including the most recent canceled and completed tasks.

For information about these commands and other Amazon EC2 commands, see the Amazon EC2 Command Line Reference.

API Version 2014-10-01 271

Amazon Elastic Compute Cloud User Guide for Linux Importing a VM into Amazon EC2

Step 2: Prepare Your VM Use the following guidelines to configure your VM before exporting it from the virtualization environment. • Review the prerequisites. For more information, see VM Import/Export Prerequisites (p. 268). • Disable any antivirus or intrusion detection software on your VM. These services can be re-enabled after the import process is complete. • Uninstall the VMware Tools from your VMware VM. • Disconnect any CD-ROM drives (virtual or physical). • Set your network to DHCP instead of a static IP address. If you want to assign a static private IP address, be sure to use a non-reserved private IP address in your VPC subnet. Amazon Virtual Private Cloud (Amazon VPC) reserves the first four private IP addresses in a VPC subnet. • Shut down your VM before exporting it. Windows • Enable Remote Desktop (RDP) for remote access. • Make sure that your host firewall (Windows firewall or similar), if configured, allows access to RDP. Otherwise, you will not be able to access your instance after the import is complete. • Make sure that the administrator account and all other user accounts use secure passwords. All accounts must have passwords or the importation might fail. • Make sure that your Windows VM has .NET Framework 3.5 installed, as required by Amazon Windows EC2Config Service. • Do not run System Preparation (Sysprep) on your Windows VM images.We recommend that you import the image and then use the Amazon EC2 Config service to run Sysprep. • Disable Autologon on your Windows VM. • Make sure that there are no pending Microsoft updates, and that the computer is not set to install software when it reboots. Linux • Enable Secure Shell (SSH) for remote access. • Make sure that your host firewall (such as Linux iptables) allows access to SSH. Otherwise, you will not be able to access your instance after the import is complete. • Make sure that you have configured a non-root user to use public key-based SSH to access your instance after it is imported. The use of password-based SSH and root login over SSH are both possible, but not recommended. The use of public keys and a non-root user is recommended because it is more secure. VM Import will not configure an ec2-user account as part of the import process. • Make sure that your Linux VM uses GRUB (GRUB legacy) or GRUB 2 as its bootloader. • Make sure that your Linux VM uses a root filesystem is one of the following: EXT2, EXT3, EXT4, Btrfs, JFS, or XFS.

Step 3: Export Your VM from Its Virtual Environment After you have prepared your VM for export, you can export it from your virtualization environment. For information about how to export a VM from your virtualization environment, see the documentation for Citrix, Microsoft Hyper-V, or VMware vCenter virtualization environment. Citrix: For more information, see Export VMs as OVF/OVA at the Citrix website. Microsoft Hyper-V: For more information, see Hyper-V - Export & Import at the Microsoft website.

API Version 2014-10-01 272

Amazon Elastic Compute Cloud User Guide for Linux Importing a VM into Amazon EC2

VMware: For more information, see Export an OVF Template at the VMware website.

Step 4: Importing Your VM into Amazon EC2 After exporting your VM from your virtualization environment, you can import it into Amazon EC2. The import process is the same regardless of the origin of the VM. Here are some important things to know about your VM instance, as well as some security and storage recommendations: • Amazon EC2 automatically assigns a DHCP IP address to your instance.The DNS name and IP address are available through the ec2-describe-instances command when the instance starts running. • Your instance has only one Ethernet network interface. • To specify a subnet to use when you create the import task, use the --subnet subnet_id option with the ec2-import-instance command; otherwise, your instance will use a public IP address. We recommend that you use a restrictive security group to control access to your instance. • We recommend that your Windows instances contain strong passwords for all user accounts. We recommend that your Linux instances use public keys for SSH. • For Windows instances, we recommend that you install the Amazon Windows EC2Config Service after you import your virtual machine into Amazon EC2. To import a VM into Amazon EC2 Use ec2-import-instance to create a new import instance task. The syntax of the command is as follows: ec2-import-instance disk_image_filename -f file_format -t instance_type -a ar chitecture -b s3_bucket_name -o owner -w secret_key -p platform_name

If the import of the VM is interrupted, you can use the ec2-resume-import command to resume the import from where it stopped. For more information, see Resuming an Upload (p. 277). Example (Windows) The following command creates an import instance task that imports a Windows Server 2008 SP2 (32bit) VM. C:\> ec2-import-instance ./WinSvr8-2-32-disk1.vmdk –f VMDK -t m1.small -a i386 -b myawsbucket -o AKIAIOSFODNN7EXAMPLE -w wJalrXUtnFEMI/K7MDENG/bPxRfi CYEXAMPLEKEY -p Windows

This request uses the VMDK file, WinSvr8-2-32-disk1.vmdk, to create the import task. (Note that you can alternatively use VHD or RAW format.) If you do not specify a size for the requesting volume using the -s parameter, a volume size based on the disk image file is used. The output is similar to the following. Requesting volume size: 25 GB Disk image format: Stream-optimized VMDK Converted volume size: 26843545600 bytes (25.00 GiB) Requested EBS volume size: 26843545600 bytes (25.00 GiB) TaskType IMPORTINSTANCE TaskId import-i-fhbx6hua ExpirationTime 2011-09-09T15:03:38+00:00 Status active StatusMessage Pending In stanceID i-6ced060c

API Version 2014-10-01 273

Amazon Elastic Compute Cloud User Guide for Linux Importing a VM into Amazon EC2

DISKIMAGE DiskImageFormat VMDK DiskImageSize 5070303744 VolumeSize 25 AvailabilityZone us-east-1c Approximate BytesConverted 0 Status active StatusMessage Pending Creating new manifest at testImport/9cba4345-b73e-4469-81062756a9f5a077/Win_2008_R1_EE_64.vmdkmanifest.xml Uploading the manifest file Uploading 5070303744 bytes across 484 parts 0% |--------------------------------------------------| 100% |==================================================| Done

Example (Linux) The following example creates an import instance task that imports a 64-bit Linux VM. $ ec2-import-instance rhel6.4-64bit-disk.vhd -f vhd -t m3.xlarge -a x86_64 -b myawsbucket -o AKIAIOSFODNN7EXAMPLE –w wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY -p Linux

This request uses the VHD file, rhel6.4-64bit-disk.vhd, to create the import task. The output is similar to the following. Requesting volume size: 8 GB TaskType IMPORTINSTANCE TaskId import-i-ffnzq636 ExpirationTime 2013-12-12T22:55:18Z Status active StatusMessage Pending InstanceID i-a56ab6dd DISKIMAGE DiskImageFormat VHD DiskImageSize 861055488 VolumeSize 8 AvailabilityZone us-east-1d ApproximateBytesCon verted 0 Status active StatusMessage Pending Creating new manifest at myawsbucket/b73bae14-7ec5-4122-89584234028e1d9f/rhel6.4-64bit-disk.vhdmanifest.xml Uploading the manifest file Uploading 861055488 bytes across 83 parts 0% |--------------------------------------------------| 100% |==================================================| Done Average speed was 11.054 MBps The disk image for import-i-ffnzq636 has been uploaded to Amazon S3 where it is being converted into an EC2 instance. You may monitor the progress of this task by running ec2-de scribe-conversion-tasks. When the task is completed, you may use ec2-delete-disk-image to remove the image from S3.

Checking on the Status of Your Import Task The ec2-describe-conversion-tasks command returns the status of an import task. Status values include the following: • active—Your instance or volume is still importing. • cancelling—Your instance or volume is still being canceled. • cancelled—Your instance or volume is canceled.

API Version 2014-10-01 274

Amazon Elastic Compute Cloud User Guide for Linux Importing a VM into Amazon EC2

• completed—Your instance or volume is ready to use. The imported instance is in the stopped state. You use ec2-start-instance to start it. For more information, see ec2-start-instances in the Amazon EC2 Command Line Reference. To check the status of your import task Use ec2-describe-conversion-tasks to return the status of the task. The syntax of the command is as follows: ec2-describe-conversion-tasks task_id

Example The following example enables you to see the status of your import instance task. $ ec2-describe-conversion-tasks import-i-ffvko9js

Response 1 The following response shows that the IMPORTINSTANCE status is active, and 73747456 bytes out of 893968896 have been converted. TaskType IMPORTINSTANCE TaskId import-i-ffvko9js ExpirationTime 2011-06-07T13:30:50+00:00 Status active StatusMessage Pending In stanceID i-17912579 DISKIMAGE DiskImageFormat VMDK DiskImageSize 893968896 VolumeSize 12 AvailabilityZone us-east-1 ApproximateBytesConverted 73747456 Status active StatusMessage Pending

Response 2 The following response shows that the IMPORTINSTANCE status is active, at 7% progress, and the DISKIMAGE is completed. TaskType IMPORTINSTANCE TaskId import-i-ffvko9js ExpirationTime 2011-06-07T13:30:50+00:00 Status active StatusMessage Progress: 7% InstanceID i-17912579 DISKIMAGE DiskImageFormat VMDK DiskImageSize 893968896 VolumeId vol-9b59daf0 VolumeSize 12 AvailabilityZone us-east-1 ApproximateBytesConverted 893968896 Status completed

Response 3 The following response shows that the IMPORTINSTANCE status is completed. TaskType IMPORTINSTANCE TaskId import-i-ffvko9js ExpirationTime 2011-06-07T13:30:50+00:00 Status completed InstanceID i-17912579 DISKIMAGE DiskImageFormat VMDK DiskImageSize 893968896 VolumeId vol-9b59daf0 VolumeSize 12 AvailabilityZone us-east-1 ApproximateBytesConverted 893968896 Status completed

API Version 2014-10-01 275

Amazon Elastic Compute Cloud User Guide for Linux Importing a VM into Amazon EC2

Note The IMPORTINSTANCE status is what you use to determine the final status. The DISKIMAGE status will be completed for a period of time before the IMPORTINSTANCE status is completed. You can now use commands such as ec2-stop-instance, ec2-start-instance, ec2-rebootinstance, and ec2-terminate-instance to manage your instance. For more information, see the Amazon EC2 Command Line Reference

Importing Your Volumes into Amazon EBS This section describes how to import your data storage into Amazon EBS, and then attach it to one of your existing EC2 instances. Amazon EC2 supports importing RAW, Virtual Hard Disk (VHD), and ESX Virtual Machine Disk (VMDK) disk formats.

Important We recommend using Amazon EC2 security groups to limit network access to your imported instance. Configure a security group to allow only trusted EC2 instances and remote hosts to connect to RDP and other service ports. For more information about security groups, see Amazon EC2 Security Groups (p. 421). After you have exported your virtual machine from the virtualization environment, importing the volume to Amazon EBS is a single-step process. You create an import task and upload the volume.

To import a volume into Amazon EBS 1.

Use ec2-import-volume to create a task that allows you to upload your volume into Amazon EBS. The syntax of the command is as follows: ec2-import-volume disk_image -f file_format -s volume_size -z availabil ity_zone -b s3_bucket_name -o owner -w secret_key

The following example creates an import volume task for importing a volume to the us-east-1 region in the d availability zone. $ ec2-import-volume Win_2008_R1_EE_64.vmdk –f vmdk –s 25 -z us-east-1d -b myawsbucket -o AKIAIOSFODNN7EXAMPLE -w wJalrXUtnFEMI/K7MDENG/bPxRfi CYEXAMPLEKEY --region us-east-1 -o AKIAI44QH8DHBEXAMPLE -w je7MtGbCl wBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY

The following is an example response. Requesting volume size: 25 GB Disk image format: Stream-optimized VMDK Converted volume size: 26843545600 bytes (25.00 GiB) Requested EBS volume size: 26843545600 bytes (25.00 GiB) TaskType IMPORTVOLUME TaskId import-vol-ffut5xv4 ExpirationTime 2011-09-09T15:22:30+00:00 Status active StatusMessage Pending DISKIMAGE DiskImageFormat VMDK DiskImageSize 5070303744 VolumeSize 25 AvailabilityZone us-east-1d Approximate BytesConverted 0 Creating new manifest at myawsbucket/0fd8fcf5-04d8-44ae-981f3c9f56d04520/Win_2008_R1_EE_64.vmdkmanifest.xml Uploading the manifest file Uploading 5070303744 bytes across 484 parts 0% |--------------------------------------------------| 100%

API Version 2014-10-01 276

Amazon Elastic Compute Cloud User Guide for Linux Importing a VM into Amazon EC2

|==================================================| Done

Amazon EC2 returns a task ID that you use in the next step. In this example, the ID is import-volffut5xv4. 2.

Use ec2-describe-conversion-tasks to confirm that your volume imported successfully. $ ec2-describe-conversion-tasks import-vol-ffut5xv4 TaskType IMPORTVOLUME TaskId import-vol-ffut5xv4 ExpirationTime 2011-09-09T15:22:30+00:00 Status completed DISKIMAGE DiskImageFormat VMDK DiskImageSize 5070303744 VolumeId vol-365a385c VolumeSize 25 AvailabilityZone us-east-1d ApproximateBytesConverted 5070303744

The status in this example is completed, which means the import succeeded. 3.

Use ec2-attach-volume to attach the Amazon EBS volume to one of your existing EC2 instances. The following example attaches the volume, vol-2540994c, to the i-a149ec4a instance on the device, /dev/sde. $ ec2-attach-volume vol-2540994c -i i-a149ec4a -d /dev/sde ATTACHMENT vol-2540994c i-a149ec4a /dev/sde attaching 2010-0323T15:43:46+00:00

Resuming an Upload Connectivity problems can interrupt an upload. When you resume an upload, Amazon EC2 automatically starts the upload from where it stopped. The following procedure steps you through determining how much of an upload succeeded and how to resume it. To resume an upload Use the task ID with ec2-resume-import to continue the upload. The command uses the HTTP HEAD action to determine where to resume. ec2-resume-import disk_image -t task_id -o owner -w secret_key

Example The following example resumes an import instance task. $ ec2-resume-import Win_2008_R1_EE_64.vmdk -t import-i-ffni8aei -o AKIAIOSFOD NN7EXAMPLE -w wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

The following shows the output when the import instance task is complete: Disk image size: 5070303744 bytes (4.72 GiB) Disk image format: Stream-optimized VMDK Converted volume size: 26843545600 bytes (25.00 GiB) Requested EBS volume size: 26843545600 bytes (25.00 GiB) Uploading 5070303744 bytes across 484 parts 0% |--------------------------------------------------| 100%

API Version 2014-10-01 277

Amazon Elastic Compute Cloud User Guide for Linux Importing a VM into Amazon EC2

|==================================================| Done Average speed was 10.316 MBps The disk image for import-i-ffni8aei has been uploaded to Amazon S3 where it is being converted into an EC2 instance. You may monitor the progress of this task by running ec2-describe-conversion-tasks. When the task is completed, you may use ec2-delete-disk-image to remove the image from S3.

Canceling an Upload Use ec2-cancel-conversion-task to cancel an active import task. The task can be the upload of an instance or a volume. The command removes all artifacts of the import, including uploaded volumes or instances. If the import is complete or still transferring the final disk image, the command fails and returns an exception similar to the following: Client.CancelConversionTask Error: Failed to cancel conversion task import-ifh95npoc

To cancel an upload task Use the task ID of the upload you want to delete with ec2-cancel-conversion-task. Example The following example cancels the upload associated with the task ID import-i-fh95npoc. $ ec2-cancel-conversion-task import-i-fh95npoc

The output for a successful cancellation is similar to the following: CONVERSION-TASK import-i-fh95npoc

You can use the ec2-describe-conversion-tasks command to check the status of the cancellation as in the following example: $ ec2-describe-conversion-tasks import-i-fh95npoc TaskType IMPORTINSTANCE TaskId import-i-fh95npoc ExpirationTime 2010-12-20T18:36:39+00:00 Status cancelled InstanceID i-825063ef DISKIMAGE DiskImageFormat VMDK DiskImageSize 2671981568 VolumeSize 40 AvailabilityZone us-east-1c ApproximateBytesCon verted 0 Status cancelled

In this example, the status is cancelled. If the upload were still in process, the status would be cancelling.

Cleaning Up After an Upload You can use ec2-delete-disk-image to remove the image file after it is uploaded. If you do not delete it, you will be charged for its storage in Amazon S3. To delete a disk image

API Version 2014-10-01 278

Amazon Elastic Compute Cloud User Guide for Linux Exporting Amazon EC2 Instances

Use the task ID of the disk image you want to delete with ec2-delete-disk-image. Example The following example deletes the disk image associated with the task ID, import-i-fh95npoc. $ ec2-delete-disk-image -t import-i-fh95npoc

The output for a successful cancellation is similar to the following: DELETE-TASK import-i-fh95npoc

Step 5: Launch the instance in Amazon EC2 After you upload the VM to Amazon S3, the VM Import process automatically converts it into an Amazon EC2 instance and launches it as a stopped instance in the Amazon EC2 console. Before you can begin using the instance, you must start it. For more information about working with an Amazon EC2 instance, see Instance Lifecycle (p. 286).

To start the instance 1. 2. 3. 4.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. If necessary, change the region. From the navigation bar, select the region where your instance is running. For more information, see Regions and Endpoints. In the navigation pane, click Instances. In the content pane, right-click the instance, and then click Start.

Exporting Amazon EC2 Instances If you have previously imported an instance into Amazon EC2, you can use the command line tools to export that instance to Citrix Xen, Microsoft Hyper-V, or VMware vSphere. Exporting an instance that you previously imported is useful when you want to deploy a copy of your EC2 instance in your on-site virtualization environment. Contents • Export an Instance (p. 279) • Cancel or Stop the Export of an Instance (p. 280)

Export an Instance You can use the Amazon EC2 CLI to export an instance. If you haven't installed the CLI already, see Setting Up the Amazon EC2 Tools. The ec2-create-instance-export-task command gathers all of the information necessary (e.g., instance ID; name of the Amazon S3 bucket that will hold the exported image; name of the exported image; VMDK, OVA, or VHD format) to properly export the instance to the selected virtualization format. The exported file is saved in the Amazon S3 bucket that you designate.

Note When you export an instance, you are charged the standard Amazon S3 rates for the bucket where the exported VM is stored. In addition, a small charge reflecting temporary use of an Amazon EBS snapshot might appear on your bill. For more information about Amazon S3 pricing, see Amazon Simple Storage Service (S3) Pricing. API Version 2014-10-01 279

Amazon Elastic Compute Cloud User Guide for Linux Troubleshooting

To export an instance 1.

Create an Amazon S3 bucket for storing the exported instances. The Amazon S3 bucket must grant Upload/Delete and View Permissions access to the [emailprotected] account. For more information, see Creating a Bucket and Editing Bucket Permissions in the Amazon Simple Storage Service Console User Guide.

2.

At a command prompt, type the following command: ec2-create-instance-export-task instance_id –e target_environment –f disk_image_format -c container_format –b s3_bucket instance_id The ID of the instance you want to export. target_environment VMware, Citrix, or Microsoft. disk_image_format VMDK for VMware or VHD for Microsoft Hyper-V and Citrix Xen. container_format Optionally set to OVA when exporting to VMware. s3_bucket The name of the Amazon S3 bucket to which you want to export the instance.

3.

To monitor the export of your instance, at the command prompt, type the following command, where task_id is the ID of the export task: ec2-describe-export-tasks task_id

Cancel or Stop the Export of an Instance You can use the Amazon EC2 CLI to cancel or stop the export of an instance up to the point of completion. The ec2-cancel-export-task command removes all artifacts of the export, including any partially created Amazon S3 objects. If the export task is complete or is in the process of transferring the final disk image, the command fails and returns an error. To cancel or stop the export of an instance At the command prompt, type the following command, where task_id is the ID of the export task: ec2-cancel-export-task task_id

Troubleshooting VM Import/Export When importing or exporting a VM, most errors occur when you attempt to do something that isn't supported. To avoid these errors, read VM Import/Export Prerequisites (p. 268) before you begin an import or an export. Errors • AWS Error Code: InvalidParameter, AWS Error Message: Parameter disk-image-size=0 has an invalid format. (p. 281)

API Version 2014-10-01 280

Amazon Elastic Compute Cloud User Guide for Linux Troubleshooting

• Client.UnsupportedOperation: This instance has multiple volumes attached. Please remove additional volumes. (p. 281) • ClientError: Footers not identical (p. 281) • ClientError: Uncompressed data has invalid length. (p. 281) • ERROR: Bucket is not in the region, it's in . (p. 282) • ERROR: File uses unsupported compression algorithm 0. (p. 282) • Error starting instances: Invalid value for instanceId. Instance does not have a volume attached at root (/dev/sda1). (p. 282) • java.lang.OutOfMemoryError: Java heap space (p. 282) • Service.InternalError: An internal error has occurred. Status Code: 500, AWS Service: AmazonEC2 (p. 282) • FirstBootFailure: This import request failed because the Windows instance failed to boot and establish network connectivity. (p. 283) • Linux is not supported on the requested instance (p. 285)

AWS Error Code: InvalidParameter, AWS Error Message: Parameter disk-image-size=0 has an invalid format. The image format you used is not supported. Resolution Retry using one of the supported image formats: RAW, VHD, or VMDK.

Client.UnsupportedOperation: This instance has multiple volumes attached. Please remove additional volumes. The VM has multiple attached disks. Resolution Detach the extra drives and try again. If you need the data on the other volumes, copy the data to the root volume and try to export the VM again.

ClientError: Footers not identical You attempted to import a fixed or differencing VHD, or there was an error in creating the VHD. Resolution Export your VM again and retry importing it into Amazon EC2.

ClientError: Uncompressed data has invalid length. The VMDK file is corrupted. Resolution You can try repairing or recreating the VMDK file, or use another one for your import.

API Version 2014-10-01 281

Amazon Elastic Compute Cloud User Guide for Linux Troubleshooting

ERROR: Bucket is not in the region, it's in . The Amazon S3 bucket is not in the same region as the instance you want to import. Resolution Try adding the --ignore-region-affinity option, which ignores whether the bucket's region matches the region where the import task is created.You can also create an Amazon S3 bucket using the Amazon Simple Storage Service console and set the region to the region where you want to import the VM. Run the command again and specify the new bucket you just created.

ERROR: File uses unsupported compression algorithm 0. The VMDK was created using OVA format instead of OVF format. Resolution Create the VMDK in OVF format.

Error starting instances: Invalid value for instanceId. Instance does not have a volume attached at root (/dev/sda1). You attempted to start the instance before the VM import process and all conversion tasks were complete. Resolution Wait for the VM import process and all conversion tasks to completely finish, and then start the instance.

java.lang.OutOfMemoryError: Java heap space There is not enough virtual memory available to launch Java, or the image you are trying to import is too large. Resolution If you allocate extra memory to Java, the extra memory will only apply to JVM, but if that setting is specified (explicitly for the EC2 command line tools) it will override the global settings. For example, you can use the following command to allocate 512 MB of extra memory to Java 'set EC2_JVM_ARGS=-Xmx512m'.

Service.InternalError: An internal error has occurred. Status Code: 500, AWS Service: AmazonEC2 You tried to import an instance that does not have a default VPC without specifying the subnet and Availability Zone. Resolution If you're importing an instance without a default VPC, be sure to specify the subnet and Availability Zone.

API Version 2014-10-01 282

Amazon Elastic Compute Cloud User Guide for Linux Troubleshooting

FirstBootFailure: This import request failed because the Windows instance failed to boot and establish network connectivity. When you import a VM using the ec2-import-instance command, the import task might stop before its completed, and then fail. To investigate what went wrong, you can use the ec2-describe-conversiontasks command to describe the instance. When you receive the FirstBootFailure error message, it means that your virtual disk image was unable to perform one of the following steps: • Boot up and start Windows. • Install Amazon EC2 networking and disk drivers. • Use a DHCP-configured network interface to retrieve an IP address. • Activate Windows using the Amazon EC2 Windows volume license. The following best practices can help you to avoid Windows first boot failures: • Disable anti-virus and anti-spyware software and firewalls. These types of software can prevent installing new Windows services or drivers or prevent unknown binaries from running. Software and firewalls can be re-enabled after importing. • Do not harden your operating system. Security configurations, sometimes called hardening, can prevent unattended installation of Amazon EC2 drivers. There are numerous Windows configuration settings that can prevent import. These settings can be reapplied once imported. • Disable or delete multiple bootable partitions. If your virtual machine boots and requires you to choose which boot partition to use, the import may fail. This inability of the virtual disk image to boot up and establish network connectivity could be due to any of the following causes. Causes • The installation of Windows is not valid on the virtual machine (p. 283) • TCP/IP networking and DHCP are not enabled (p. 284) • A volume that Windows requires is missing from the virtual machine (p. 284) • • • •

Windows always boots into System Recovery Options (p. 284) The virtual machine was created using a physical-to-virtual (P2V) conversion process (p. 284) Windows activation fails (p. 284) No bootable partition found (p. 284)

The installation of Windows is not valid on the virtual machine Cause: The installation of Windows must be valid before you can successfully import the virtual machine. Resolution: Do not run System Preparation (Sysprep) before shutting down the EC2 instance. After the instance is imported, you can run Sysprep from the instance before you create an AMI. Importing creates a single instance, so running Sysprep is not necessary. Ensure that the installation process is fully complete and that Windows boots (without user intervention) to a login prompt.

API Version 2014-10-01 283

Amazon Elastic Compute Cloud User Guide for Linux Troubleshooting

TCP/IP networking and DHCP are not enabled Cause: For any Amazon EC2 instance, including those in Amazon VPC, TCP/IP networking and DHCP must be enabled. Within a VPC, you can define an IP address for the instance either before or after importing the instance. Do not set a static IP address before exporting the instance. Resolution: Ensure that TCP/IP networking is enabled. For more information, see Setting up TCP/IP (Windows Server 2003) or Configuring TCP/IP (Windows Server 2008) at the Microsoft TechNet website. Ensure that DHCP is enabled. For more information, see What is DHCP at the Microsoft TechNet web site.

A volume that Windows requires is missing from the virtual machine Cause: Importing a VM into Amazon EC2 only imports the boot disk, all other disks must be detached and Windows must able to boot before importing the virtual machine. For example, Active Directory often stores the Active Directory database on the D:\ drive. A domain controller cannot boot if the Active Directory database is missing or inaccessible. Resolution: Detach any secondary and network disks attached to the Windows VM before exporting. Move any Active Directory databases from secondary drives or partitions onto the primary Windows partition. For more information, see "Directory Services cannot start" error message when you start your Windows-based or SBS-based domain controller at the Microsoft Support website.

Windows always boots into System Recovery Options Cause: Windows can boot into System Recovery Options for a variety of reasons, including when Windows is pulled into a virtualized environment from a physical machine, also known as P2V. Resolution: Ensure that Windows boots to a login prompt before exporting and preparing for import. Do not import virtualized Windows instances that have come from a physical machine.

The virtual machine was created using a physical-to-virtual (P2V) conversion process Cause: A P2V conversion occurs when a disk image is created by performing the Windows installation process on a physical machine and then importing a copy of that Windows installation into a VM. VMs that are created as the result of a P2V conversion are not supported by Amazon EC2 VM import. Amazon EC2 VM import only supports Windows images that were natively installed inside the source VM. Resolution: Install Windows in a virtualized environment and migrate your installed software to that new VM.

Windows activation fails Cause: During boot, Windows will detect a change of hardware and attempt activation. During the import process we attempt to switch the licensing mechanism in Windows to a volume license provided by Amazon Web Services. However, if the Windows activation process does not succeed, then the import will not succeed. Resolution: Ensure that the version of Windows you are importing supports volume licensing. Beta or preview versions of Windows might not.

No bootable partition found Cause: During the import process of a virtual machine, we could not find the boot partition.

API Version 2014-10-01 284

Amazon Elastic Compute Cloud User Guide for Linux Troubleshooting

Resolution: Ensure that the disk you are importing has the boot partition. We do not support multi-disk import.

Linux is not supported on the requested instance Cause: Linux import is only supported on specific instance types.You attempted to import an unsupported instance type. Resolution: Retry using one of the supported instance types. • General purpose: t2.micro | t2.small | t2.medium | m3.medium | m3.large | m3.xlarge | m3.2xlarge • Compute optimized: c3.large | c3.xlarge | c3.2xlarge | c3.4xlarge | cc2.8xlarge • Memory optimized: cr1.8xlarge • Storage optimized: hi1.4xlarge | hs1.8xlarge | i2.xlarge | i2.2xlarge | i2.4xlarge • GPU: cg1.4xlarge

API Version 2014-10-01 285

Amazon Elastic Compute Cloud User Guide for Linux Instance Launch

Instance Lifecycle By working with Amazon EC2 to manage your instances from the moment you launch them through their termination, you ensure that your customers have the best possible experience with the applications or sites that you host on your instances. The following illustration represents the transitions between instance states. Notice that you can't stop and start an instance store-backed instance. For more information about instance store-backed instances, see Storage for the Root Device (p. 55).

Instance Launch When you launch an instance, it enters the pending state. The instance type that you specified at launch determines the hardware of the host computer for your instance. We use the Amazon Machine Image (AMI) you specified at launch to boot the instance. After the instance is ready for you, it enters the running state. You can connect to your running instance and use it the way that you'd use a computer sitting in front of you. As soon as your instance starts to boot, you're billed for each hour or partial hour that you keep the instance running (even if the instance remains idle and you don't connect to it). For more information, see Launch Your Instance (p. 289) and Connect to Your Linux Instance (p. 299).

API Version 2014-10-01 286

Amazon Elastic Compute Cloud User Guide for Linux Instance Stop and Start (Amazon EBS-backed instances only)

Instance Stop and Start (Amazon EBS-backed instances only) If your instance fails a status check or is not running your applications as expected, and if the root volume of your instance is an Amazon EBS volume, you can stop and start your instance to try to fix the problem. When you stop your instance, it enters the stopping state, and then the stopped state. We don't charge hourly usage or data transfer fees for your instance after you stop it, but we do charge for the storage for any Amazon EBS volumes. While your instance is in the stopped state, you can modify certain attributes of the instance, including the instance type. When you start your instance, it enters the pending state, and we move the instance to a new host computer. Therefore, when you stop and start your instance, you'll lose any data on the instance store volumes on the previous host computer. If your instance is running in EC2-Classic, it receives a new private IP address, which means that an Elastic IP address (EIP) associated with the private IP address is no longer associated with your instance. If your instance is running in EC2-VPC, it retains its private IP address, which means that an EIP associated with the private IP address or network interface is still associated with your instance. Each time you transition an instance from stopped to running, we charge a full instance hour, even if these transitions happen multiple times within a single hour. For more information, see Stop and Start Your Instance (p. 309).

Instance Reboot You can reboot your instance using the Amazon EC2 console, the Amazon EC2 CLI, and the Amazon EC2 API. We recommend that you use Amazon EC2 to reboot your instance instead of running the operating system reboot command from your instance. Rebooting an instance is equivalent to rebooting an operating system; the instance remains on the same host computer and maintains its public DNS name, private IP address, and any data on its instance store volumes. It typically takes a few minutes for the reboot to complete, but the time it takes to reboot depends on the instance configuration. Rebooting an instance doesn't start a new instance billing hour. For more information, see Reboot Your Instance (p. 312).

Instance Retirement An instance is scheduled to be retired when AWS detects irreparable failure of the underlying hardware hosting the instance. When an instance reaches its scheduled retirement date, it is stopped or terminated by AWS. If your instance root device is an Amazon EBS volume, the instance is stopped, and you can start it again at any time. If your instance root device is an instance store volume, the instance is terminated, and cannot be used again. For more information, see Instance Retirement (p. 312).

API Version 2014-10-01 287

Amazon Elastic Compute Cloud User Guide for Linux Instance Termination

Instance Termination When you've decided that you no longer need an instance, you can terminate it. As soon as the status of an instance changes to shutting-down or terminated, you stop incurring charges for that instance. Note that if you enable termination protection, you can't terminate the instance using the console, CLI, or API. After you terminate an instance, it remains visible in the console for a short while, and then the entry is deleted. You can also describe a terminated instance using the CLI and API. You can't connect to or recover a terminated instance. Each Amazon EBS-backed instance supports the InstanceInitiatedShutdownBehavior attribute, which controls whether the instance stops or terminates when you initiate a shutdown from within the instance itself (for example, by using the shutdown command on Linux). The default behavior is to stop the instance. You can modify the setting of this attribute while the instance is running or stopped. Each Amazon EBS volume supports the DeleteOnTermination attribute, which controls whether the volume is deleted or preserved when you terminate the instance it is attached to. The default is to preserve volumes that you attach to a running instance and delete volumes that you attach at launch, such as the root volume. For more information, see Terminate Your Instance (p. 315).

Differences Between Reboot, Stop, and Terminate The following table summarizes the key differences between rebooting, stopping, and terminating your instance. Characteristic Reboot

Stop/start (Amazon EBS-backed instances only)

Host computer

The instance stays on the same host computer

The instance runs on a new None host computer

Private and public IP addresses

These addresses stay the same

EC2-Classic: The instance None gets new private and public IP addresses EC2-VPC: The instance keeps its private IP address. The instance gets a new public IP address, unless it has an Elastic IP address (EIP), which doesn't change during a stop/start.

API Version 2014-10-01 288

Terminate

Amazon Elastic Compute Cloud User Guide for Linux Launch

Characteristic Reboot

Elastic IP addresses (EIP)

Stop/start (Amazon EBS-backed instances only)

The EIP remains associated EC2-Classic: The EIP is with the instance disassociated from the instance

Terminate

The EIP is disassociated from the instance

EC2-VPC:The EIP remains associated with the instance Instance store volumes

The data is preserved

The data is erased

The data is erased

Root device volume

The volume is preserved

The volume is preserved

The volume is deleted by default

Billing

The instance billing hour doesn't change.

You stop incurring charges for an instance as soon as its state changes to stopping. Each time an instance transitions from stopped to pending, we start a new instance billing hour.

You stop incurring charges for an instance as soon as its state changes to shutting-down.

Note that operating system shutdown commands always terminate an instance store-backed instance. You can control whether operating system shutdown commands stop or terminate an Amazon EBSbacked instance. For more information, see Changing the Instance Initiated Shutdown Behavior (p. 317).

Launch Your Instance An instance is a virtual server in the AWS cloud.You launch an instance from an Amazon Machine Image (AMI). The AMI provides the operating system, application server, and applications for your instance. When you sign up for AWS, you can get started with Amazon EC2 for free using the AWS Free Usage Tier. You can either leverage the Free Usage Tier to launch and use a micro instance for free for 12 months. If you launch an instance that is not within the Free Usage Tier, you incur the standard Amazon EC2 usage fees for the instance. For more information, see the Amazon EC2 Pricing. You can launch an instance using the following methods. Method

Documentation

Use the Amazon EC2 console with an AMI that you Launching an Instance (p. 290) select Use the Amazon EC2 console to launch an instance using an existing instance as a template

Launching an Instance Using an Existing Instance as a Template (p. 295)

Use the Amazon EC2 console with an Amazon EBS snapshot that you created

Launching a Linux Instance from a Backup (p. 296)

API Version 2014-10-01 289

Amazon Elastic Compute Cloud User Guide for Linux Launching an Instance

Method

Documentation

Use the Amazon EC2 console with an AMI that you Launching an AWS Marketplace Instance (p. 297) purchased from the AWS Marketplace Use the AWS CLI with an AMI that you select

Using Amazon EC2 through the AWS CLI

Use the Amazon EC2 CLI with an AMI that you select

Launching an Instance Using the Amazon EC2 CLI

Use the AWS Tools for Windows PowerShell with an AMI that you select

Amazon EC2 from the AWS Tools for Windows PowerShell

After you launch your instance, you can connect to it and use it. To begin, the instance state is pending. When the instance state is running, the instance has started booting. There might be a short time before you can connect to the instance. The instance receives a public DNS name that you can use to contact the instance from the Internet. The instance also receives a private DNS name that other instances within the same Amazon EC2 network (EC2-Classic or EC2-VPC) can use to contact the instance. For more information about connecting to your instance, see Connect to Your Linux Instance (p. 299). When you are finished with an instance, be sure to terminate it. For more information, see Terminate Your Instance (p. 315).

Launching an Instance Before you launch your instance, be sure that you are set up. For more information, see Setting Up with Amazon EC2 (p. 20). Your AWS account might support both the EC2-Classic and EC2-VPC platforms, depending on when you created your account and which regions you've used.To find out which platform your account supports, see Supported Platforms (p. 471). If your account supports EC2-Classic, you can launch an instance into either platform. If your account supports EC2-VPC only, you can launch an instance into a VPC only.

Important When you launch an instance that's not within the AWS Free Usage Tier, you are charged for the time that the instance is running, even if it remains idle.

Launching Your Instance from an AMI When you launch an instance, you must select a configuration, known as an Amazon Machine Image (AMI). An AMI contains the information required to create a new instance. For example, an AMI might contain the software required to act as a web server: for example, Linux, Apache, and your web site.

To launch an instance 1. 2.

Open the Amazon EC2 console. In the navigation bar at the top of the screen, the current region is displayed. Select the region for the instance.This choice is important because some Amazon EC2 resources can be shared between regions, while others can't. Select the region that meets your needs. For more information, see Resource Locations (p. 605).

API Version 2014-10-01 290

Amazon Elastic Compute Cloud User Guide for Linux Launching an Instance

3. 4.

From the Amazon EC2 console dashboard, click Launch Instance. On the Choose an Amazon Machine Image (AMI) page, choose an AMI as follows: a.

Select the type of AMI to use in the left pane: Quick Start A selection of popular AMIs to help you get started quickly. To ensure that you select an AMI that is eligible for the free tier, click Free tier only in the left pane. (Notice that these AMIs are marked Free tier eligible.) My AMIs The private AMIs that you own, or private AMIs that have been shared with you. AWS Marketplace An online store where you can buy software that runs on AWS, including AMIs. For more information about launching an instance from the AWS Marketplace, see Launching an AWS Marketplace Instance (p. 297). Community AMIs The AMIs that AWS community members have made available for others to use. To filter the list of AMIs by operating system, select the Amazon Linux check box under Operating system. You can also filter by architecture and root device type.

b.

c.

d.

Check the Root device type listed for each AMI. Notice which AMIs are the type that you need, either ebs (backed by Amazon EBS) or instance-store (backed by instance store). For more information, see Storage for the Root Device (p. 55). Check the Virtualization type listed for each AMI. Notice which AMIs are the type that you need, either hvm or paravirtual. For example, some instance types require HVM. For more information, see Virtualization Types (p. 58). Choose an AMI that meets your needs, and then click Select.

API Version 2014-10-01 291

Amazon Elastic Compute Cloud User Guide for Linux Launching an Instance

5.

On the Choose an Instance Type page, select the hardware configuration and size of the instance to launch. Larger instance types have more CPU and memory. For more information, see Instance Types (p. 103). To remain eligible for the free tier, select the t2.micro instance type. For more information, see T2 Instances (p. 105). By default, the wizard displays current generation instance types, and selects the first available instance type based on the AMI that you selected. To view previous generation instance types, select All generations from the filter list.

Tip If you are new to AWS and would like to set up an instance quickly for testing purposes, you can click Review and Launch at this point to accept default configuration settings, and launch your instance. Otherwise, to configure your instance further, click Next: Configure Instance Details. 6.

On the Configure Instance Details page, change the following settings as necessary (expand Advanced Details to see all the settings), and then click Next: Add Storage: • Number of instances: Enter the number of instances to launch. • Purchasing option: Select Request Spot Instances to launch a Spot Instance. For more information, see Spot Instances (p. 132). • Your account may support the EC2-Classic and EC2-VPC platforms, or EC2-VPC only. To find out which platform your account supports, see Supported Platforms (p. 471). If your account supports EC2-VPC only, you can launch your instance into your default VPC or a nondefault VPC. Otherwise, you can launch your instance into EC2-Classic or a nondefault VPC.

Note You must launch a T2 instance into a VPC. If you don't have a VPC, you can let the wizard create one for you. To launch into EC2-Classic: • Network: Select Launch into EC2-Classic. • Availability Zone: Select the Availability Zone to use. To let AWS choose an Availability Zone for you, select No preference. To launch into a VPC: • Network: Select the VPC, or to create a new VPC, click Create new VPC to go the Amazon VPC console. When you have finished, return to the wizard and click Refresh to load your VPC in the list. • Subnet: Select the subnet into which to launch your instance. If your account is EC2-VPC only, select No preference to let AWS choose a default subnet in any Availability Zone. To create a new subnet, click Create new subnet to go to the Amazon VPC console. When you are done, return to the wizard and click Refresh to load your subnet in the list. • Auto-assign Public IP: Specify whether your instance receives a public IP address. By default, instances in a default subnet receive a public IP address and instances in a nondefault subnet do not. You can select Enable or Disable to override the subnet's default setting. For more information, see Public IP Addresses and External DNS Hostnames (p. 481). • IAM role: If applicable, select an AWS Identity and Access Management (IAM) role to associate with the instance. For more information, see IAM Roles for Amazon EC2 (p. 461). • Shutdown behavior: Select whether the instance should stop or terminate when shut down. For more information, see Changing the Instance Initiated Shutdown Behavior (p. 317). • Enable termination protection: Select this check box to prevent accidental termination. For more information, see Enabling Termination Protection for an Instance (p. 316).

API Version 2014-10-01 292

Amazon Elastic Compute Cloud User Guide for Linux Launching an Instance

• Monitoring: Select this check box to enable detailed monitoring of your instance using Amazon CloudWatch. Additional charges apply. For more information, see Monitoring Your Instances with CloudWatch (p. 354). • EBS-Optimized instance: An Amazon EBS-optimized instance uses an optimized configuration stack and provides additional, dedicated capacity for Amazon EBS I/O. If the instance type supports this feature, select this check box to enable it. Additional charges apply. For more information, see Amazon EBS–Optimized Instances (p. 125). • Tenancy: If you are launching your instance into a VPC, you can select Dedicated tenancy to run your instance on isolated, dedicated hardware. Additional charges apply. For more information, see Dedicated Instances in the Amazon VPC User Guide. • Network interfaces: If you are launching an instance into a VPC and you did not select No Preference for your subnet, you can specify up to two network interfaces in the wizard. Click Add IP to assign more than one IP address to the selected interface. For more information about network interfaces, see Elastic Network Interfaces (ENI) (p. 494). If you selected the Public IP check box above, you can only assign a public IP address to a single, new network interface with the device index of eth0. For more information, see Assigning a Public IP Address (p. 484). • Kernel ID: (Only valid for paravirtual (PV) AMIs) Select Use default unless you want to use a specific kernel. • RAM disk ID: (Only valid for paravirtual (PV) AMIs) Select Use default unless you want to use a specific RAM disk. If you have selected a kernel, you may need to select a specific RAM disk with the drivers to support it. • Placement group: A placement group is a logical grouping for your cluster instances. Select an existing placement group, or create a new one. This option is only available if you've selected an instance type that supports placement groups. For more information, see Placement Groups (p. 126). • User data: You can specify user data to configure an instance during launch, or to run a configuration script. To attach a file, select the As file option and browse for the file to attach.

7.

On the Add Storage page, you can specify volumes to attach to the instance besides the volumes specified by the AMI (such as the root device volume). You can change the following options, then click Next: Tag Instance when you have finished: • Type: Select instance store or Amazon EBS volumes to associate with your instance. The type of volume available in the list depends on the instance type you've chosen. For more information, see Amazon EC2 Instance Store (p. 581) and Amazon EBS Volumes (p. 521). • Device: Select from the list of available device names for the volume. • Snapshot: Enter the name or ID of the snapshot from which to restore a volume. You can also search for public snapshots by typing text into the Snapshot field. Snapshot descriptions are casesensitive. • Size: For Amazon EBS-backed volumes, you can specify a storage size. Note that even if you have selected an AMI and instance that are eligible for the free usage tier, you need to keep under 30 GiB of total storage to stay within the free usage tier.

Note If you increase the size of your root volume at this point (or any other volume created from a snapshot), you need to extend the file system on that volume in order to use the extra space. For more information about extending your file system after your instance has launched, see Expanding the Storage Space of a Volume (p. 545). • Volume Type: For Amazon EBS volumes, select either a General Purpose (SSD), Provisioned IOPS (SSD), or Magnetic volume. For more information, see Amazon EBS Volume Types (p. 523).

Note If you select a Magnetic boot volume, you'll be prompted when you complete the wizard to make General Purpose (SSD) volumes the default boot volume for this instance and future console launches. (This preference persists in the browser session, and does not affect AMIs with Provisioned IOPS (SSD) boot volumes.) We recommended that you API Version 2014-10-01 293

Amazon Elastic Compute Cloud User Guide for Linux Launching an Instance

make General Purpose (SSD) volumes the default because they provide a much faster boot experience and they are the optimal volume type for most workloads. For more information, see Amazon EBS Volume Types (p. 523).

Note Some AWS accounts created before 2012 might have access to Availability Zones in useast-1, us-west-1, or ap-northeast-1 that do not support SSD volumes such as Provisioned IOPS (SSD) and General Purpose (SSD). If you are unable to create an SSD volume (or launch an instance with an SSD volume in its block device mapping) in one of these regions, try a different Availability Zone in the region. You can verify that an Availability Zone supports General Purpose (SSD) and Provisioned IOPS (SSD) volumes by creating a 1 GiB General Purpose (SSD) volume in that zone. • IOPS: If you have selected a Provisioned IOPS (SSD) volume type, then you can enter the number of I/O operations per second (IOPS) that the volume can support. • Delete on Termination: For Amazon EBS volumes, select this check box to delete the volume when the instance is terminated. For more information, see Preserving Amazon EBS Volumes on Instance Termination (p. 318). • Encrypted: Select this check box to encrypt new Amazon EBS volumes. Amazon EBS volumes that are restored from encrypted snapshots are automatically encrypted. Encrypted volumes may only be attached to supported instance types (p. 565).

Note Encrypted boot volumes are not supported at this time.

8.

9.

On the Tag Instance page, specify tags (p. 610) for the instance by providing key and value combinations. Click Create Tag to add more than one tag to your resource. Click Next: Configure Security Group when you are done. On the Configure Security Group page, use a security group to define firewall rules for your instance. These rules specify which incoming network traffic is delivered to your instance. All other traffic is ignored. (For more information about security groups, see Amazon EC2 Security Groups (p. 421).) Select or create a security group as follows, and then click Review and Launch. To select an existing security group: 1.

2. 3.

Click Select an existing security group. Your security groups are displayed. (If you are launching into EC2-Classic, these are security groups for EC2-Classic. If you are launching into a VPC, these are security group for that VPC.) Select a security group from the list. (Optional) You can't edit the rules of an existing security group, but you can copy them to a new group by clicking Copy to new. Then you can add rules as described in the next procedure.

To create a new security group: 1.

Click Create a new security group. The wizard automatically defines the launch-wizard-x security group.

2. 3.

(Optional) You can edit the name and description of the security group. The wizard automatically defines an inbound rule to allow to you connect to your instance over SSH (port 22).

Caution This rule enables all IP addresses (0.0.0.0/0) to access your instance over the specified port. This is acceptable for this short exercise, but it's unsafe for production environments. You should authorize only a specific IP address or range of addresses to access your instance.

API Version 2014-10-01 294

Amazon Elastic Compute Cloud User Guide for Linux Launching an Instance From an Existing Instance

4.

You can add rules to suit your needs. For example, if your instance is a web server, open ports 80 (HTTP) and 443 (HTTPS) to allow Internet traffic. To add a rule, click Add Rule, select the protocol to open to network traffic, and then specify the source. Select My IP from the Source list to let the wizard add your computer's public IP address. However, if you are connecting through an ISP or from behind your firewall without a static IP address, you need to find out the range of IP addresses used by client computers.

10. On the Review Instance Launch page, check the details of your instance, and make any necessary changes by clicking the appropriate Edit link. When you are ready, click Launch. 11. In the Select an existing key pair or create a new key pair dialog box, you can choose an existing key pair, or create a new one. For example, select Choose an existing key pair, then select the key pair you created when getting set up. To launch your instance, select the acknowledgment check box, then click Launch Instances.

Important We recommend against selecting the Proceed without key pair option. If you launch an instance without a key pair, you won't be able to connect to it. This option is used only when you are creating your own AMI and don't need to connect to the instance. 12. If the instance state immediately goes to terminated instead of running, you can get information about why the instance didn't launch. For more information, see What To Do If An Instance Immediately Terminates (p. 631).

Launching an Instance Using an Existing Instance as a Template The Amazon EC2 console provides a Launch More Like This wizard option that enables you to use a current instance as a template for launching other instances. This option automatically populates the Amazon EC2 launch wizard with certain configuration details from the selected instance.

Note The Launch More Like This wizard option does not clone your selected instance; it only replicates some configuration details. To create a copy of your instance, first create an AMI from it, then launch more instances from the AMI. The following configuration details are copied from the selected instance into the launch wizard: • AMI ID • Instance type • Availability Zone, or the VPC and subnet in which the selected instance is located • Tags associated with the instance, if applicable • Kernel ID and RAM disk ID, if applicable • IAM role associated with the instance, if applicable • Security group associated with the instance • Tenancy setting, if launching into a VPC (shared or dedicated) • Amazon EBS-optimization setting (true or false) • Public IP address. If the selected instance currently has a public IP address, the new instance receives a public IP address - regardless of the selected instance's default public IP address setting. For more information about public IP addresses, see Public IP Addresses and External DNS Hostnames (p. 481).

API Version 2014-10-01 295

Amazon Elastic Compute Cloud User Guide for Linux Launching a Linux Instance from a Backup

The following configuration details are not copied from your selected instance; instead, the wizard applies their default settings or behavior: • Storage: The default storage configuration is determined by the AMI and the instance type. • Termination protection: Disabled by default. • Shutdown behavior: Set to 'stop' by default. • User data: None by default.

To use your current instance as a template 1.

On the Instances page, select the instance you want to use.

2. 3.

Click Actions, and select Launch More Like This. The launch wizard opens on the Review Instance Launch page. You can check the details of your instance, and make any necessary changes by clicking the appropriate Edit link. When you are ready, click Launch to select a key pair and launch your instance.

Launching a Linux Instance from a Backup With an Amazon EBS-backed Linux instance, you can back up the root device volume of the instance by creating a snapshot. When you have a snapshot of the root device volume of an instance, you can terminate that instance and then later launch a new instance from the snapshot. This can be useful if you don't have the original AMI that you launched an instance from, but you need to be able to launch an instance using the same image. At this time, although you can create a Windows AMI from a snapshot, you can't launch an instance from the AMI. Use the following procedure to create an AMI from the root volume of your instance using the console. If you prefer, you can use the register-image (AWS CLI) or ec2-register (Amazon EC2 CLI) command instead.

To create an AMI from your root volume using the console 1. 2. 3.

Open the Amazon EC2 console. In the navigation pane, under Elastic Block Store, click Snapshots. Click Create Snapshot.

4.

In the Volumes field, start typing the name or ID of the root volume, and then select it from the list of options. Select the snapshot that you just created, and then select Create Image from the Actions list.

5. 6.

In the Create Image from EBS Snapshot dialog box, complete the fields to create your AMI, then click Create. Be sure to do the following: • Select the architecture from the Architecture list (i386 for 32-bit or x86_64 for 64-bit). • Select the AKI from the Kernel ID list. If you select the default AKI or don't select an AKI, you'll be required to specify an AKI every time you launch an instance. In addition, your instance may fail the health check because the default AKI is incompatible with the instance.

7. 8.

In the navigation pane, select AMIs. Select the AMI that you just created, and then click Launch. Follow the wizard to launch your instance. For more information about how to configure each step in the wizard, see Launching an Instance (p. 290).

API Version 2014-10-01 296

Amazon Elastic Compute Cloud User Guide for Linux Launching an AWS Marketplace Instance

Launching an AWS Marketplace Instance You can subscribe to an AWS Marketplace product and launch an instance from the product's AMI using the Amazon EC2 launch wizard. For more information about paid AMIs, see Paid AMIs (p. 70). To cancel your subscription after launch, you first have to terminate all instances running from it. For more information, see Managing Your AWS Marketplace Subscriptions (p. 73).

To launch an instance from the AWS Marketplace using the launch wizard 1.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

2. 3.

From the Amazon EC2 dashboard, click Launch Instance. On the Choose an Amazon Machine Image (AMI) page, select the AWS Marketplace category on the left. Find a suitable AMI by browsing the categories, or using the search functionality. Click Select to choose your product. A dialog displays an overview of the product you've selected. You can view the pricing information, as well as any other information that the vendor has provided. When you're ready, click Continue.

4.

Note You are not charged for using the product until you have launched an instance with the AMI. Take note of the pricing for each supported instance type, as you will be prompted to select an instance type on the next page of the wizard. 5. 6.

On the Choose an Instance Type page, select the hardware configuration and size of the instance to launch. When you're done, click Next: Configure Instance Details. On the next pages of the wizard, you can configure your instance, add storage, and add tags. For more information about the different options you can configure, see Launching an Instance (p. 290). Click Next until you reach the Configure Security Group page. The wizard creates a new security group according to the vendor's specifications for the product. The security group may include rules that allow all IP addresses (0.0.0.0/0) access on SSH (port 22). We recommend that you adjust these rules to allow only a specific IP address or range of addresses to access your instance over those specific ports.

7.

8.

When you are ready, click Review and Launch. On the Review Instance Launch page, check the details of the AMI from which you're about to launch the instance, as well as the other configuration details you set up in the wizard. When you're ready, click Launch to choose or create a key pair, and launch your instance. Depending on the product you've subscribed to, the instance may take a few minutes or more to launch. You are first subscribed to the product before your instance can launch. If there are any problems with your credit card details, you will be asked to update your account details. When the launch confirmation page displays, click View Instances to go to the Instances page.

Note You are charged the subscription price as long as your instance is running, even if it is idle. If your instance is stopped, you may still be charged for storage. 9.

When your instance is in the running state, you can connect to it. To do this, select your instance in the list and click Connect. Follow the instructions in the dialog. For more information about connecting to your instance, see Connect to Your Linux Instance (p. 299).

Important Check the vendor's usage instructions carefully, as you may need to use a specific user name to log in to the instance. For more information about accessing your subscription details, see Managing Your AWS Marketplace Subscriptions (p. 73).

API Version 2014-10-01 297

Amazon Elastic Compute Cloud User Guide for Linux Launching an AWS Marketplace Instance

Launching an AWS Marketplace AMI Instance Using the API and CLI To launch instances from AWS Marketplace products using the API or command line tools, first ensure that you are subscribed to the product. You can then launch an instance with the product's AMI ID using the following methods: Method

Documentation

AWS CLI

Use the run-instances command, or see the following topic for more information: Launching an Instance.

Amazon EC2 CLI

Use the ec2-run-instances command, or see the following topic for more information: Launching an Instance Using the Amazon EC2 CLI.

AWS Tools for Windows PowerShell

Use the New-EC2Instance command, or see the following topic for more information: Launch an Amazon EC2 Instance Using Windows PowerShell

Query API

Use the RunInstances request.

API Version 2014-10-01 298

Amazon Elastic Compute Cloud User Guide for Linux Connect

Connect to Your Linux Instance Learn how to connect to the instances that you launched and transfer files between your local computer and your instance. Your Computer

Topic

Linux

Connecting to Your Linux Instance Using SSH (p. 299)

Windows

Connecting to Your Linux Instance from Windows Using PuTTY (p. 303)

All

Connecting to Your Linux Instance Using MindTerm (p. 308)

After you connect to your instance, you can try one of our tutorials, such as Tutorial: Installing a LAMP Web Server (p. 38) or Tutorial: Hosting a WordPress Blog with Amazon EC2 (p. 45).

Connecting to Your Linux Instance Using SSH After you launch your instance, you can connect to it and use it the way that you'd use a computer sitting in front of you.

Note It may take a couple of minutes after launch for your running instance to finish provisioning so that you can connect to it. Check that your instance has passed its status checks - you can view this information in the Status Checks column on the Instances page. If you receive an error while attempting to connect to your instance, see Troubleshooting Connecting to Your Instance. The following instructions explain how to connect to your instance using an SSH client.

Prerequisites • Install an SSH client Your Linux computer most likely includes an SSH client by default. You can check for an SSH client by typing ssh at the command line. If your computer doesn't recognize the command, the OpenSSH project provides a free implementation of the full suite of SSH tools. For more information, see http://www.openssh.org. • Install the Amazon EC2 CLI Tools (Optional) If you're using a public AMI from a third party, you can use the command line tools to verify the fingerprint. For more information about installing the AWS CLI or Amazon EC2 CLI, see Accessing Amazon EC2 (p. 3). • Get the ID of the instance You can get the ID of your instance using the Amazon EC2 console (from the Instance ID column). If you prefer, you can use the describe-instances (AWS CLI) or ec2-describe-instances (Amazon EC2 CLI) command. • Get the public DNS name of the instance You can get the public DNS for your instance using the Amazon EC2 console (check the Public DNS column; if this column is hidden, click the Show/Hide icon and select Public DNS). If you prefer, you can use the describe-instances (AWS CLI) or ec2-describe-instances (Amazon EC2 CLI) command. • Locate the private key You'll need the fully-qualified path of the .pem file for the key pair that you specified when you launched the instance. • Enable inbound SSH traffic from your IP address to your instance

API Version 2014-10-01 299

Amazon Elastic Compute Cloud User Guide for Linux Connect Using SSH

Ensure that the security group associated with your instance allows incoming SSH traffic from your IP address. For more information, see Authorizing Network Access to Your Instances.

Important Your default security group does not allow incoming SSH traffic by default.

Connecting to Your Linux Instance To connect to your instance using SSH 1.

(Optional) You can verify the RSA key fingerprint on your instance by using one of the following commands on your local system (not on the instance). This is useful if you've launched your instance from a public AMI from a third party. Locate the SSH HOST KEY FINGERPRINTS section, and note the RSA fingerprint (for example, 1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f) and compare it to the fingerprint of the instance. • get-console-output (AWS CLI) aws ec2 get-console-output --instance-id instance_id

• ec2-get-console-output (Amazon EC2 CLI) ec2-get-console-output instance_id

Note The SSH HOST KEY FINGERPRINTS section is only available after the first boot of the instance. 2. 3.

In a command line shell, change directories to the location of the private key file that you created when you launched the instance. Use the chmod command to make sure your private key file isn't publicly viewable. For example, if the name of your private key file is my-key-pair.pem, you would use the following command: chmod 400 my-key-pair.pem

4.

Use the ssh command to connect to the instance. You'll specify the private key (.pem) file and user_name@public_dns_name. For Amazon Linux, the user name is ec2-user. For RHEL5, the user name is either root or ec2-user. For Ubuntu, the user name is ubuntu. For Fedora, the user name is either fedora or ec2-user. For SUSE Linux, the user name is root. Otherwise, if ec2user and root don't work, check with your AMI provider. ssh -i my-key-pair.pem [emailprotected]

You'll see a response like the following. The authenticity of host 'ec2-198-51-100-1.compute-1.amazonaws.com (10.254.142.33)' can't be established. RSA key fingerprint is 1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f. Are you sure you want to continue connecting (yes/no)?

API Version 2014-10-01 300

Amazon Elastic Compute Cloud User Guide for Linux Connect Using SSH

5.

6.

(Optional) Verify that the fingerprint in the security alert matches the fingerprint that you obtained in step 1. If these fingerprints don't match, someone might be attempting a "man-in-the-middle" attack. If they match, continue to the next step. Enter yes. You'll see a response like the following. Warning: Permanently added 'ec2-198-51-100-1.compute-1.amazonaws.com' (RSA) to the list of known hosts.

Transferring Files to Linux Instances from Linux Using SCP One way to transfer files between your local computer and a Linux instance is to use Secure Copy (SCP). This section describes how to transfer files with SCP. The procedure is very similar to the procedure for connecting to an instance with SSH.

Prerequisites • Install an SCP client Most Linux, Unix, and Apple computers include an SCP client by default. If yours doesn't, the OpenSSH project provides a free implementation of the full suite of SSH tools, including an SCP client. For more information, go to http://www.openssh.org. • Get the ID of the instance You can get the ID of your instance using the Amazon EC2 console (from the Instance ID column). If you prefer, you can use the describe-instances (AWS CLI) or ec2-describe-instances (Amazon EC2 CLI) command. • Get the public DNS name of the instance You can get the public DNS for your instance using the Amazon EC2 console (check the Public DNS column; if this column is hidden, click the Show/Hide icon and select Public DNS). If you prefer, you can use the describe-instances (AWS CLI) or ec2-describe-instances (Amazon EC2 CLI) command. • Locate the private key You'll need the fully-qualified path of the .pem file for the key pair that you specified when you launched the instance. • Enable inbound SSH traffic from your IP address to your instance Ensure that the security group associated with your instance allows incoming SSH traffic from your IP address. For more information, see Authorizing Network Access to Your Instances.

Important Your default security group does not allow incoming SSH traffic by default.

The following procedure steps you through using SCP to transfer a file. If you've already connected to the instance with SSH and have verified its fingerprints, you can start with the step that contains the SCP command (step 4).

To use SCP to transfer a file 1.

(Optional) You can verify the RSA key fingerprint on your instance by using one of the following commands on your local system (not on the instance). This is useful if you've launched your instance from a public AMI from a third party. Locate the SSH HOST KEY FINGERPRINTS section, and note the RSA fingerprint (for example, 1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f) and compare it to the fingerprint of the instance.

API Version 2014-10-01 301

Amazon Elastic Compute Cloud User Guide for Linux Connect Using SSH

• get-console-output (AWS CLI) aws ec2 get-console-output --instance-id instance_id

• ec2-get-console-output (Amazon EC2 CLI) ec2-get-console-output instance_id

Note The SSH HOST KEY FINGERPRINTS section is only available after the first boot of the instance. 2. 3.

In a command shell, change directories to the location of the private key file that you specified when you launched the instance. Use the chmod command to make sure your private key file isn't publicly viewable. For example, if the name of your private key file is my-key-pair.pem, you would use the following command: chmod 400 my-key-pair.pem

4.

Transfer a file to your instance using the instance's public DNS name. For example, if the name of the private key file is my-key-pair, the file to transfer is SampleFile.txt, and the public DNS name of the instance is ec2-198-51-100-1.compute-1.amazonaws.com, use the following command to copy the file to the ec2-user home directory. scp -i my-key-pair.pem SampleFile.txt [emailprotected]:~

Tip For Amazon Linux, the user name is ec2-user. For RHEL5, the user name is either root or ec2-user. For Ubuntu, the user name is ubuntu. For Fedora, the user name is either fedora or ec2-user. For SUSE Linux, the user name is root. Otherwise, if ec2-user and root don't work, check with your AMI provider. You'll see a response like the following. The authenticity of host 'ec2-198-51-100-1.compute-1.amazonaws.com (10.254.142.33)' can't be established. RSA key fingerprint is 1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f. Are you sure you want to continue connecting (yes/no)?

5.

(Optional) Verify that the fingerprint in the security alert matches the fingerprint that you obtained in step 1. If these fingerprints don't match, someone might be attempting a "man-in-the-middle" attack. If they match, continue to the next step.

6.

Enter yes. You'll see a response like the following.

API Version 2014-10-01 302

Amazon Elastic Compute Cloud User Guide for Linux Connect Using PuTTY

Warning: Permanently added 'ec2-198-51-100-1.compute-1.amazonaws.com' (RSA) to the list of known hosts. Sending file modes: C0644 20 SampleFile.txt Sink: C0644 20 SampleFile.txt SampleFile.txt

100%

20

0.0KB/s

00:00

To transfer files in the other direction (from your Amazon EC2 instance to your local computer), simply reverse the order of the host parameters. For example, to transfer the SampleFile.txt file from your EC2 instance back to the home directory on your local computer as SampleFile2.txt, use the following command on your local computer. scp -i my-key-pair.pem [emailprotected]:~/Sample File.txt ~/SampleFile2.txt

Connecting to Your Linux Instance from Windows Using PuTTY After you launch your instance, you can connect to it and use it the way that you'd use a computer sitting in front of you.

Note It may take a couple of minutes after launch for your running instance to finish provisioning so that you can connect to it. Check that your instance has passed its status checks - you can view this information in the Status Checks column on the Instances page. If you receive an error while attempting to connect to your instance, see Troubleshooting Connecting to Your Instance. The following instructions explain how to connect to your instance using PuTTY, a free SSH client for Windows.

Prerequisites • Install PuTTY Download and install PuTTY from the PuTTY download page. Be sure to install the entire suite. • Get the ID of the instance You can get the ID of your instance using the Amazon EC2 console (from the Instance ID column). If you prefer, you can use the describe-instances (AWS CLI) or ec2-describe-instances (Amazon EC2 CLI) command. • Get the public DNS name of the instance You can get the public DNS for your instance using the Amazon EC2 console (check the Public DNS column; if this column is hidden, click the Show/Hide icon and select Public DNS). If you prefer, you can use the describe-instances (AWS CLI) or ec2-describe-instances (Amazon EC2 CLI) command. • Locate the private key You'll need the fully-qualified path of the .pem file for the key pair that you specified when you launched the instance. • Enable inbound SSH traffic from your IP address to your instance Ensure that the security group associated with your instance allows incoming SSH traffic from your IP address. For more information, see Authorizing Network Access to Your Instances.

Important Your default security group does not allow incoming SSH traffic by default.

API Version 2014-10-01 303

Amazon Elastic Compute Cloud User Guide for Linux Connect Using PuTTY

Converting Your Private Key Using PuTTYgen PuTTY does not natively support the private key format (.pem) generated by Amazon EC2. PuTTY has a tool named PuTTYgen, which can convert keys to the required PuTTY format (.ppk). You must convert your private key into this format (.ppk) before attempting to connect to your instance using PuTTY.

To convert your private key 1. 2.

Start PuTTYgen (for example, from the Start menu, click All Programs > PuTTY > PuTTYgen). Under Type of key to generate, select SSH-2 RSA.

3.

Click Load. By default, PuTTYgen displays only files with the extension .ppk. To locate your .pem file, select the option to display files of all types.

4.

Select your .pem file and click Open. Click OK to dismiss the confirmation dialog box.

5.

Click Save private key to save the key in the format that PuTTY can use. PuTTYgen displays a warning about saving the key without a passphrase. Click Yes.

Note A passphrase on a private key is an extra layer of protection, so even if your private key is discovered, it can't be used without the passphrase. The downside to using a passphrase is that it makes automation harder because human intervention is needed to log on to an instance, or copy files to an instance. 6.

Specify the same name for the key that you used for the key pair (for example, my-key-pair). PuTTY automatically adds the .ppk file extension.

Your private key is now in the correct format for use with PuTTY. You can now connect to your instance using PuTTY's SSH client.

Starting a PuTTY Session To start a PuTTY session 1.

(Optional) You can verify the RSA key fingerprint on your instance by using one of the following commands on your local system (not on the instance). This is useful if you've launched your instance from a public AMI from a third party. Locate the SSH HOST KEY FINGERPRINTS section, and note the RSA fingerprint (for example, 1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f) and compare it to the fingerprint of the instance. • get-console-output (AWS CLI) aws ec2 get-console-output --instance-id instance_id

• ec2-get-console-output (Amazon EC2 CLI)

API Version 2014-10-01 304

Amazon Elastic Compute Cloud User Guide for Linux Connect Using PuTTY

ec2-get-console-output instance_id

Note The SSH HOST KEY FINGERPRINTS section is only available after the first boot of the instance. 2. 3.

Start PuTTY (from the Start menu, click All Programs > PuTTY > PuTTY). In the Category pane, select Session and complete the following fields: a.

In the Host Name box, enter user_name@public_dns_name. Be sure to specify the appropriate user name for your AMI. For example: • For an Amazon Linux AMI, the user name is ec2-user. • For a RHEL5 AMI, the user name is either root or ec2-user. • For an Ubuntu AMI, the user name is ubuntu. • For a Fedora AMI, the user name is either fedora or ec2-user. • For SUSE Linux, the user name is root. • Otherwise, if ec2-user and root don't work, check with the AMI provider.

b. c.

4.

Under Connection type, select SSH. Ensure that Port is 22.

In the Category pane, expand Connection, expand SSH, and then select Auth. Complete the following: a. b.

Click Browse. Select the .ppk file that you generated for your key pair, and then click Open.

c.

(Optional) If you plan to start this session again later, you can save the session information for future use. Select Session in the Category tree, enter a name for the session in Saved Sessions, and then click Save. Click Open to start the PuTTY session.

d.

API Version 2014-10-01 305

Amazon Elastic Compute Cloud User Guide for Linux Connect Using PuTTY

5. 6.

7.

If this is the first time you have connected to this instance, PuTTY displays a security alert dialog box that asks whether you trust the host you are connecting to. (Optional) Verify that the fingerprint in the security alert matches the fingerprint that you obtained in step 1. If these fingerprints don't match, someone might be attempting a "man-in-the-middle" attack. If they match, continue to the next step. Click Yes. A window opens and you are connected to your instance.

Note If you specified a passphrase when you converted your private key to PuTTY's format, you must provide that passphrase when you log in to the instance.

Transferring Files to Your Linux Instance Using the PuTTY Secure Copy Client The PuTTY Secure Copy client (PSCP) is a command-line tool that you can use to transfer files between your Windows computer and your Linux instance. If you prefer a graphical user interface (GUI), you can use an open source GUI tool named WinSCP. For more information, see Transferring Files to Your Linux Instance Using WinSCP (p. 306). To use PSCP, you'll need the private key you generated in Converting Your Private Key Using PuTTYgen (p. 304). You'll also need the public DNS address of your Linux instance. The following example transfers the file Sample_file.txt from a Windows computer to the /usr/local directory on a Linux instance: C:\> pscp -i C:\Keys\my-key-pair.ppk C:\Sample_file.txt user_name@pub lic_dns:/usr/local/Sample_file.txt

Transferring Files to Your Linux Instance Using WinSCP WinSCP is a GUI-based file manager for Windows that allows you to upload and transfer files to a remote computer using the SFTP, SCP, FTP, and FTPS protocols. WinSCP allows you to drag and drop files from your Windows machine to your Linux instance or synchronize entire directory structures between the two systems.

API Version 2014-10-01 306

Amazon Elastic Compute Cloud User Guide for Linux Connect Using PuTTY

To use WinSCP, you'll need the private key you generated in Converting Your Private Key Using PuTTYgen (p. 304). You'll also need the public DNS address of your Linux instance. 1.

Download and install WinSCP from http://winscp.net/eng/download.php. For most users, the default installation options are OK.

2. 3. 4.

Start WinSCP. At the WinSCP login screen, for Host name, enter the public DNS address for your instance. For User name, enter the default user name for your AMI. For Amazon Linux AMIs, the user name is ec2-user. For Red Hat AMIs the user name is root, and for Ubuntu AMIs the user name is ubuntu.

5.

Specify the private key for your instance. For Private key, enter the path to your private key, or click the "…" button to browse for the file. For newer versions of WinSCP, you need to click Advanced to open the advanced site settings and then under SSH, click Authentication to find the Private key file setting.

Note WinSCP requires a PuTTY private key file (.ppk). You can convert a .pem security key file to the .ppk format using PuTTYgen. For more information, see Converting Your Private Key Using PuTTYgen (p. 304). 6.

7.

8.

(Optional) In the left panel, click Directories, and then, for Remote directory, enter the path for the directory you want to add files to. For newer versions of WinSCP, you need to click Advanced to open the advanced site settings and then under Environment, click Directories to find the Remote directory setting. Click Login to connect, and click Yes to add the host fingerprint to the host cache.

After the connection is established, in the connection window your Linux instance is on the right and your local machine is on the left. You can drag and drop files directly into the remote file system from your local machine. For more information on WinSCP, see the project documentation at http://winscp.net/eng/docs/start.

API Version 2014-10-01 307

Amazon Elastic Compute Cloud User Guide for Linux Connect Using MindTerm

Connecting to Your Linux Instance Using MindTerm After you launch your instance, you can connect to it and use it the way that you'd use a computer sitting in front of you.

Note It may take a couple of minutes after launch for your running instance to finish provisioning so that you can connect to it. Check that your instance has passed its status checks - you can view this information in the Status Checks column on the Instances page. If you receive an error while attempting to connect to your instance, see Troubleshooting Connecting to Your Instance. The following instructions explain how to connect to your instance using MindTerm through the Amazon EC2 console.

Prerequisites • Install Java Your Linux computer most likely includes Java. If not, see How do I enable Java in my web browser? On a Windows or Mac client, you must run your browser using administrator credentials. For Linux, additional steps may be required if you are not logged in as root. • Enable Java in your browser For instructions, see http://java.com/en/download/help/enable_browser.xml. • Locate the private key You'll need the fully-qualified path of the .pem file for the key pair that you specified when you launched the instance. • Enable inbound SSH traffic from your IP address to your instance Ensure that the security group associated with your instance allows incoming SSH traffic from your IP address. For more information, see Authorizing Network Access to Your Instances.

Important Your default security group does not allow incoming SSH traffic by default.

Starting MindTerm To connect to your instance using a web browser with MindTerm 1.

In the Amazon EC2 console, click Instances in the navigation pane.

2. 3.

Select the instance, and then click Connect. Click A Java SSH client directly from my browser (Java required).

4.

Amazon EC2 automatically detects the public DNS name of your instance and the name of the populates Public DNS for you. It also detects name of the key pair that you specified when you launched the instance. Complete the following, and then click Launch SSH Client. a.

In User name, enter the user name to log in to your instance.

Tip For Amazon Linux, the user name is ec2-user. For RHEL5, the user name is either root or ec2-user. For Ubuntu, the user name is ubuntu. For Fedora, the user name is either fedora or ec2-user. For SUSE Linux, the user name is root. Otherwise, if ec2-user and root don't work, check with your AMI provider. b.

In Private key path, enter the fully-qualified path to your private key (.pem) file, including the key pair name; for example:

API Version 2014-10-01 308

Amazon Elastic Compute Cloud User Guide for Linux Stop and Start

C:\KeyPairs\my-key-pair.pem

c.

(Optional) Click Store in browser cache to store the location of the private key in your browser cache. This enables Amazon EC2 to detect the location of the private key in subsequent browser sessions, until your clear your browser's cache.

5.

If necessary, click Yes to trust the certificate, and click Run to run the MindTerm client.

6.

If this is your first time running MindTerm, a series of dialog boxes asks you to accept the license agreement, to confirm setup for your home directory, and to confirm setup of the known hosts directory. Confirm these settings. A dialog prompts you to add the host to your set of known hosts. If you do not want to store the host key information on your local computer, click No. A window opens and you are connected to your instance.

7. 8.

Note If you clicked No in the previous step, you'll see the following message, which is expected: Verification of server key disabled in this session.

Stop and Start Your Instance You can stop and restart your instance if it has an Amazon EBS volume as its root device. The instance retains its instance ID, but can change as described in the Overview section. When you stop an instance, we shut it down. We don't charge hourly usage for a stopped instance, or data transfer fees, but we do charge for the storage for any Amazon EBS volumes. Each time you start a stopped instance we charge a full instance hour, even if you make this transition multiple times within a single hour. While the instance is stopped, you can treat its root volume like any other volume, and modify it (for example, repair file system problems or update software). You just detach the volume from the stopped instance, attach it to a running instance, make your changes, detach it from the running instance, and then reattach it to the stopped instance. Make sure that you reattach it using the storage device name that's specified as the root device in the block device mapping for the instance. If you decide that you no longer need an instance, you can terminate it. As soon as the state of an instance changes to shutting-down or terminated, we stop charging for that instance. For more information, see Terminate Your Instance (p. 315). Topics • Overview (p. 309) • Stopping and Starting Your Instances (p. 310) • Modifying a Stopped Instance (p. 311) • Troubleshooting (p. 312)

Overview You can only stop an Amazon EBS-backed instance. To verify the root device type of your instance, describe the instance and check whether the device type of its root volume is ebs (Amazon EBS-backed instance) or instance store (instance store-backed instance). For more information, see Determining the Root Device Type of Your AMI (p. 56).

API Version 2014-10-01 309

Amazon Elastic Compute Cloud User Guide for Linux Stopping and Starting Your Instances

When you stop a running instance, the following happens: • The instance performs a normal shutdown and stops running; its status changes to stopping and then stopped. • Any Amazon EBS volumes remain attached to the instance, and their data persists. • Any data stored in the RAM of the host computer or the instance store volumes of the host computer is gone. • EC2-Classic: We release the public and private IP addresses for the instance when you stop the instance, and assign new ones when you restart it. EC2-VPC: The instance retains its private IP addresses when stopped and restarted. We release the public IP address and assign a new one when you restart it. • EC2-Classic: We disassociate any Elastic IP address (EIP) that's associated with the instance. You're charged for Elastic IP addresses that aren't associated with an instance. When you restart the instance, you must associate the Elastic IP address with the instance; we don't do this automatically. EC2-VPC: The instance retains its associated Elastic IP addresses (EIP). You're charged for any Elastic IP addresses associated with a stopped instance. • If you've registered the instance with a load balancer, it's likely that the load balancer won't be able to route traffic to your instance after you've stopped and restarted it. You must de-register the instance from the load balancer after stopping the instance, and then re-register after starting the instance. For more information, see De-Registering and Registering Amazon EC2 Instances in the Elastic Load Balancing Developer Guide. For more information, see Differences Between Reboot, Stop, and Terminate (p. 288). You can modify the following attributes of an instance only when it is stopped: • Instance type • User data • Kernel • RAM disk

If you try to modify these attributes while the instance is running, Amazon EC2 returns the IncorrectInstanceState error.

Stopping and Starting Your Instances You can start and stop your Amazon EBS-backed instance using the console or the command line. By default, when you initiate a shutdown from an Amazon EBS-backed instance (using the shutdown, halt, or poweroff command), the instance stops.You can change this behavior so that it terminates instead. For more information, see Changing the Instance Initiated Shutdown Behavior (p. 317).

To stop and start an Amazon EBS-backed instance using the console 1. 2.

In the navigation pane, click Instances, and select the instance. [EC2-Classic] If the instance has an associated Elastic IP address, write down the Elastic IP address and the instance ID shown in the details pane.

3.

Click Actions, and then click Stop. If Stop is disabled, either the instance is already stopped or its root device is an instance store volume.

4.

In the confirmation dialog box, click Yes, Stop. It can take a few minutes for the instance to stop.

API Version 2014-10-01 310

Amazon Elastic Compute Cloud User Guide for Linux Modifying a Stopped Instance

[EC2-Classic] When the instance state becomes stopped, the Elastic IP, Public DNS, Private DNS, and Private IPs fields in the details pane are blank to indicate that the old values are no longer associated with the instance. 5. 6. 7.

While your instance is stopped, you can modify certain instance attributes. For more information, see Modifying a Stopped Instance (p. 311). To restart the stopped instance, select the instance, click Actions, and then click Start. In the confirmation dialog box, click Yes, Start. It can take a few minutes for the instance to enter the running state. [EC2-Classic] When the instance state becomes running, the Public DNS, Private DNS, and Private IPs fields in the details pane contain the new values that we assigned to the instance.

8.

[EC2-Classic] If your instance had an associated Elastic IP address, you must reassociate it as follows: a.

In the navigation pane, click Elastic IPs.

b. c.

Select the Elastic IP address that you wrote down before you stopped the instance. Click Associate Address.

d.

Select the instance ID that you wrote down before you stopped the instance, and then click Associate.

To stop and start an Amazon EBS-backed instance using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • stop-instances and start-instances (AWS CLI) • ec2-stop-instances and ec2-start-instances (Amazon EC2 CLI) • Stop-EC2Instance and Start-EC2Instance (AWS Tools for Windows PowerShell)

Modifying a Stopped Instance You can change the instance type and user data attributes using the AWS Management Console or the command line interface. You can't use the AWS Management Console to modify the kernel or RAM disk attributes.

To change the instance type for a stopped instance using the console 1. 2.

In the navigation pane, click Instances. Select the stopped instance, click Actions, and then click Change Instance Type.

3.

In the Change Instance Type dialog box, in the Instance Type list, select the type of instance you need, and then click Apply. For more information, see Resizing Your Instance (p. 128).

To change the user data for a stopped instance using the console 1. 2.

In the navigation pane, click Instances. Select the stopped instance, click Actions, and then click View/Change User Data.

3.

In the View/Change User Data dialog box, update the user data, and then click Save. Note that you can't change the user data if the instance is running, but you can view it.

API Version 2014-10-01 311

Amazon Elastic Compute Cloud User Guide for Linux Troubleshooting

To modify an instance attribute using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • modify-instance-attribute (AWS CLI) • ec2-modify-instance-attribute (Amazon EC2 CLI) • Edit-EC2InstanceAttribute (AWS Tools for Windows PowerShell)

Troubleshooting If you have stopped your Amazon EBS-backed instance and it appears "stuck" in the stopping state, you can forcibly stop it. For more information, see Troubleshooting Stopping Your Instance (p. 637).

Reboot Your Instance An instance reboot is equivalent to an operating system reboot. In most cases, it takes only a few minutes to reboot your instance. When you reboot an instance, it remains on the same physical host, so your instance keeps its public DNS name, private IP address, and any data on its instance store volumes. Rebooting an instance doesn't start a new instance billing hour, unlike stopping and restarting your instance. We might schedule your instance for a reboot for necessary maintenance, such as to apply updates that require a reboot. No action is required on your part; we recommend that you wait for the reboot to occur within its scheduled window. For more information, see Monitoring Events for Your Instances (p. 351). We recommend that you use Amazon EC2 to reboot your instance instead of running the operating system reboot command from your instance.

To reboot an instance using the console 1. 2. 3. 4.

Open the Amazon EC2 console. In the navigation pane, click Instances. Select the instance, click Actions, and then click Reboot. Click Yes, Reboot when prompted for confirmation.

To reboot an instance using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • reboot-instances (AWS CLI) • ec2-reboot-instances (Amazon EC2 CLI) • Restart-EC2Instance (AWS Tools for Windows PowerShell)

Instance Retirement An instance is scheduled to be retired when AWS detects irreparable failure of the underlying hardware hosting the instance. When an instance reaches its scheduled retirement date, it is stopped or terminated by AWS. If your instance root device is an Amazon EBS volume, the instance is stopped, and you can

API Version 2014-10-01 312

Amazon Elastic Compute Cloud User Guide for Linux Identifying Instances Scheduled for Retirement

start it again at any time. Starting the stopped instance migrates it to new hardware. If your instance root device is an instance store volume, the instance is terminated, and cannot be used again. Topics • Identifying Instances Scheduled for Retirement (p. 313) • Working with Instances Scheduled for Retirement (p. 313) For more information about types of instance events, see Monitoring Events for Your Instances (p. 351).

Identifying Instances Scheduled for Retirement If your instance is scheduled for retirement, you'll receive an email prior to the event with the instance ID and retirement date. This email is sent to the address that's associated with your account; the same email address that you use to log in to the AWS Management Console. If you use an email account that you do not check regularly, then you can use the Amazon EC2 console or the command line to determine if any of your instances are scheduled for retirement. To update the contact information for your account, go to the Account Settings page.

To identify instances scheduled for retirement using the console 1. 2.

Open the Amazon EC2 console. In the navigation pane, click EC2 Dashboard. Under Scheduled Events, you can see the events associated with your Amazon EC2 instances and volumes, organized by region.

3.

If you have an instance with a scheduled event listed, click its link below the region name to go to the Events page. The Events page lists all resources with events associated with them. To view instances that are scheduled for retirement, select Instance resources from the first filter list, and then Instance retirement from the second filter list. If the filter results show that an instance is scheduled for retirement, select it, and note the date and time in the Start time field in the details pane. This is your instance retirement date.

4.

5.

To identify instances scheduled for retirement using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • describe-instance-status (AWS CLI) • ec2-describe-instance-status (Amazon EC2 CLI) • Get-EC2InstanceStatus (AWS Tools for Windows PowerShell)

Working with Instances Scheduled for Retirement There are a number of actions available to you when your instance is scheduled for retirement. The action you take depends on whether your instance root device is an Amazon EBS volume, or an instance store volume. If you do not know what your instance root device type is, you can find out using the Amazon EC2 console or the command line. API Version 2014-10-01 313

Amazon Elastic Compute Cloud User Guide for Linux Working with Instances Scheduled for Retirement

Determining Your Instance Root Device Type To determine your instance root device type using the console 1.

In the navigation pane, click Events. Use the filter lists to identify retiring instances, as demonstrated in the procedure above, Identifying instances scheduled for retirement (p. 313).

2. 3.

In the Resource ID column, click the instance ID to go to the Instances page. Select the instance and locate the Root device type field in the Description tab. If the value is ebs, then your instance is EBS-backed. If the value is instance-store, then your instance is instance store-backed.

To determine your instance root device type using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • describe-instances (AWS CLI) • ec2-describe-instances (Amazon EC2 CLI) • Get-EC2Instance (AWS Tools for Windows PowerShell)

Managing Instances Scheduled for Retirement You can perform one of the actions listed below in order to preserve the data on your retiring instance. It's important that you take this action before the instance retirement date, to prevent unforeseen downtime and data loss.

Warning If your instance store-backed instance passes its retirement date, it's terminated and you cannot recover the instance or any data that was stored on it. Regardless of the root device of your instance, the data on instance store volumes is lost when the instance is retired, even if they are attached to an EBS-backed instance. Instance Root Device Type

Action

EBS

Wait for the scheduled retirement date - when the instance is stopped - or stop the instance yourself before the retirement date. You can start the instance again at any time. For more information about stopping and starting your instance, and what to expect when your instance is stopped, such as the effect on public, private and Elastic IP addresses associated with your instance, see Stop and Start Your Instance (p. 309).

EBS

Create an EBS-backed AMI from your instance, and launch a replacement instance. For more information, see Creating an Amazon EBS-Backed Linux AMI (p. 74).

Instance store

Create an instance store-backed AMI from your instance using the AMI tools, and launch a replacement instance. For more information, see Creating an Instance Store-Backed Linux AMI (p. 77).

Instance store

Convert your instance to an EBS-backed instance by transferring your data to an EBS volume, taking a snapshot of the volume, and then creating an AMI from the snapshot. You can launch a replacement instance from your new AMI. For more information, see Converting your Instance Store-Backed AMI to an Amazon EBS-Backed AMI (p. 82).

API Version 2014-10-01 314

Amazon Elastic Compute Cloud User Guide for Linux Terminate

Terminate Your Instance When you've decided that you no longer need an instance, you can terminate it. As soon as the state of an instance changes to shutting-down or terminated, you stop incurring charges for that instance. You can't connect to or restart an instance after you've terminated it. However, you can launch additional instances using the same AMI. If you'd rather stop and restart your instance, see Stop and Start Your Instance (p. 309). For more information, see Differences Between Reboot, Stop, and Terminate (p. 288). Topics • Instance Termination (p. 315) • Terminating an Instance (p. 315) • Enabling Termination Protection for an Instance (p. 316) • Changing the Instance Initiated Shutdown Behavior (p. 317) • Preserving Amazon EBS Volumes on Instance Termination (p. 318) • Troubleshooting (p. 320)

Instance Termination After you terminate an instance, it remains visible in the console for a short while, and then the entry is deleted. When an instance terminates, the data on any instance store volumes associated with that instance is deleted. By default, any Amazon EBS volumes that you attach as you launch the instance are automatically deleted when the instance terminates. However, by default, any volumes that you attach to a running instance persist even after the instance terminates. This behavior is controlled by the volume's DeleteOnTermination attribute, which you can modify. For more information, see Preserving Amazon EBS Volumes on Instance Termination (p. 318). You can prevent an instance from being terminated accidentally by someone using the AWS Management Console, the CLI, and the API. This feature is available for both Amazon EC2 instance store-backed and Amazon EBS-backed instances. Each instance has a DisableApiTermination attribute with the default value of false (the instance can be terminated through Amazon EC2). You can modify this instance attribute while the instance is running or stopped (in the case of Amazon EBS-backed instances). For more information, see Enabling Termination Protection for an Instance (p. 316). You can control whether an instance should stop or terminate when shutdown is initiated from the instance using an operating system command for system shutdown. For more information, see Changing the Instance Initiated Shutdown Behavior (p. 317). If you run a script on instance termination, your instance might have an abnormal termination, because we have no way to ensure that shutdown scripts run. Amazon EC2 attempts to shut an instance down cleanly and run any system shutdown scripts; however, certain events (such as hardware failure) may prevent these system shutdown scripts from running.

Terminating an Instance You can terminate an instance using the AWS Management Console or the command line.

API Version 2014-10-01 315

Amazon Elastic Compute Cloud User Guide for Linux Enabling Termination Protection

To terminate an instance using the console 1.

Before you terminate the instance, verify that you won't lose any data by checking that your Amazon EBS volumes won't be deleted on termination and that you've copied any data that you need from your instance store volumes to Amazon EBS or Amazon S3.

2. 3. 4.

Open the Amazon EC2 console. In the navigation pane, click Instances. Select the instance, click Actions, and then click Terminate.

5.

Click Yes, Terminate when prompted for confirmation.

To terminate an instance using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • terminate-instances (AWS CLI) • ec2-terminate-instances (Amazon EC2 CLI) • Stop-EC2Instance (AWS Tools for Windows PowerShell)

Enabling Termination Protection for an Instance By default, you can terminate your instance using the Amazon EC2 console, command line interface, or API. If you want to prevent your instance from being accidentally terminated using Amazon EC2, you can enable termination protection for the instance. The DisableApiTermination attribute controls whether the instance can be terminated using the console, CLI, or API. By default, termination protection is disabled for your instance. You can set the value of this attribute when you launch the instance, while the instance is running, or while the instance is stopped (for Amazon EBS-backed instances). The DisableApiTermination attribute does not prevent you from terminating an instance by initiating shutdown from the instance (using an operating system command for system shutdown) when the InstanceInitiatedShutdownBehavior attribute is set. For more information, see Changing the Instance Initiated Shutdown Behavior (p. 317). Instances that are part of an Auto Scaling group are not covered by termination protection. For more information, see Instance Termination Policy for Your Auto Scaling Group in the Auto Scaling Developer Guide. You can enable or disable termination protection using the AWS Management Console or the command line.

To enable termination protection for an instance at launch time 1.

On the dashboard of the Amazon EC2 console, click Launch Instance and follow the directions in the wizard.

2.

On the Configure Instance Details page, select the Enable termination protection check box.

To enable termination protection for a running or stopped instance 1.

Select the instance, click Actions, and then click Change Termination Protection.

2.

Click Yes, Enable.

API Version 2014-10-01 316

Amazon Elastic Compute Cloud User Guide for Linux Changing the Shutdown Behavior

To disable termination protection for a running or stopped instance 1.

Select the instance, click Actions, and then click Change Termination Protection.

2.

Click Yes, Disable.

To enable or disable termination protection using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • modify-instance-attribute (AWS CLI) • ec2-modify-instance-attribute (Amazon EC2 CLI) • Edit-EC2InstanceAttribute (AWS Tools for Windows PowerShell)

Changing the Instance Initiated Shutdown Behavior By default, when you initiate a shutdown from an Amazon EBS-backed instance (using a command such as shutdown, halt, or poweroff), the instance stops.You can change this behavior using the InstanceInitiatedShutdownBehavior attribute for the instance so that it terminates instead.You can update this attribute while the instance is running or stopped. You can update the InstanceInitiatedShutdownBehavior attribute using the AWS Management Console or the command line.

To change the shutdown behavior of an instance using the console 1. 2. 3. 4.

Open the Amazon EC2 console. In the navigation pane, click Instances. Select the instance, click Actions, and then click Change Shutdown Behavior. The current behavior is already selected. To change the behavior, select an option from the Shutdown behavior list, and then click Apply.

To change the shutdown behavior of an instance using the command line You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • modify-instance-attribute (AWS CLI) • ec2-modify-instance-attribute (Amazon EC2 CLI) • Edit-EC2InstanceAttribute (AWS Tools for Windows PowerShell) API Version 2014-10-01 317

Amazon Elastic Compute Cloud User Guide for Linux Preserving Amazon EBS Volumes on Instance Termination

Preserving Amazon EBS Volumes on Instance Termination By default, we do the following: • Preserve any volumes that you attach to a running instance even after the instance terminates • Preserve any volumes that you attach to your instance at launch when you stop and restart an instance • Delete the volumes that you attach to your instance at launch, including the root device volume, when you terminate the instance You can change this behavior using the DeleteOnTermination attribute for the volume. If the value of this attribute is true, we delete the volume after the instance terminates; otherwise, we preserve the volume. If the DeleteOnTermination attribute of a volume is false, the volume persists in its current state. You can take a snapshot of the volume, and you can attach it to another instance. If you detach a volume that you attached to your instance at launch, and then reattach it, we preserve it even after the instance terminates. In other words, its DeleteOnTermination attribute is set to false. You can see the value for the DeleteOnTermination attribute on the volumes attached to an instance by looking at the instance's block device mapping. For more information, see Viewing the Amazon EBS Volumes in an Instance Block Device Mapping (p. 600). You can update the DeleteOnTermination attribute using the AWS Management Console or the command line.

Changing the Root Volume to Persist Using the Console Using the console, you can change the DeleteOnTermination attribute when you launch an instance. To change this attribute for a running instance, you must use the command line.

To change the root volume of an instance to persist at launch using the console 1. 2. 3. 4. 5. 6.

Open the Amazon EC2 console. From the console dashboard, click Launch Instance. On the Choose an Amazon Machine Image (AMI) page, choose an AMI and click Select. Follow the wizard to complete the Choose an Instance Type and Configure Instance Details pages. On the Add Storage page, deselect the Delete On Termination check box for the root volume. Complete the remaining wizard pages, and then click Launch.

You can verify the setting by viewing details for the root device volume on the instance's details pane. Next to Block devices, click the entry for the root device volume. By default, Delete on termination is True. If you change the default behavior, Delete on termination is False.

Changing the Root Volume of a Running Instance to Persist Using the Command Line You can use one of the following commands to change the root device volume of a running instance to persist.The root device is typically /dev/sda1. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • modify-instance-attribute (AWS CLI)

API Version 2014-10-01 318

Amazon Elastic Compute Cloud User Guide for Linux Preserving Amazon EBS Volumes on Instance Termination

• ec2-modify-instance-attribute (Amazon EC2 CLI) • Edit-EC2InstanceAttribute (AWS Tools for Windows PowerShell)

Example for AWS CLI The following command preserves the root volume by setting its DeleteOnTermination attributes to false. $ aws ec2 modify-instance-attribute --instance-id i-5203422c --block-devicemappings '[{"DeviceName":"/dev/sda1","Ebs":{"DeleteOnTermination":false}}]'

You can confirm that deleteOnTermination is false by using the describe-instances command and looking for the BlockDeviceMappings entry for /dev/sda1 in the command output.

Example for Amazon EC2 CLI The following command preserves the root volume by setting its DeleteOnTermination attribute to false. $ ec2-modify-instance-attribute i-5203422c -b /dev/sda1=::false

Changing the Root Volume of an Instance to Persist at Launch Using the Command Line When you launch an instance, you can use one of the following commands to change the root device volume to persist. The root device is typically /dev/sda1. For more information about these command line interfaces, see Accessing Amazon EC2 (p. 3). • run-instances (AWS CLI) • ec2-run-instances (Amazon EC2 CLI) • New-EC2Instance (AWS Tools for Windows PowerShell)

Example for AWS CLI The following command preserves the root volume by setting its DeleteOnTermination attributes to false. $ aws ec2 run-instances --image-id ami-1a2b3c4d --block-device-mappings '[{"DeviceName":"/dev/sda1","Ebs":{"DeleteOnTermination":false}}]" other para meters...

You can confirm that deleteOnTermination is false by using the describe-instances command and looking for the BlockDeviceMappings entry for /dev/sda1 in the command output.

Example for Amazon EC2 CLI The following command preserves the root volume by setting its DeleteOnTermination attribute to false. $ ec2-run-instances ami-1a2b3c4d

-b /dev/sda1=::false other parameters... -v

API Version 2014-10-01 319

Amazon Elastic Compute Cloud User Guide for Linux Troubleshooting

Troubleshooting If your instance is in the shutting-down state for longer than usual, it will eventually be cleaned up (terminated) by automated processes within the Amazon EC2 service. For more information, see Troubleshooting Terminating (Shutting Down) Your Instance (p. 638).

API Version 2014-10-01 320

Amazon Elastic Compute Cloud User Guide for Linux Common Configuration Scenarios

Configuring Your Amazon Linux Instance After you have successfully launched and logged into your Amazon Linux instance, you can make changes to it. There are many different ways you can configure an instance to meet the needs of a specific application. The following are some common tasks to help get you started. Topics • Common Configuration Scenarios (p. 321) • Managing Software on Your Linux Instance (p. 322) • Managing User Accounts on Your Linux Instance (p. 330) • Setting the Time for Your Linux Instance (p. 332) • Changing the Hostname of Your Linux Instance (p. 335) • Setting Up Dynamic DNS on Your Linux Instance (p. 337) • Running Commands on Your Linux Instance at Launch (p. 339)

Common Configuration Scenarios The base distribution of Amazon Linux contains many software packages and utilities that are required for basic server operations. However, many more software packages are available in various software repositories, and even more packages are available for you to build from source code. For more information on installing and building software from these locations, see Managing Software on Your Linux Instance (p. 322). Amazon Linux instances come pre-configured with an ec2-user account, but you may want to add other user accounts that do not have super-user privileges. For more information on adding and removing user accounts, see Managing User Accounts on Your Linux Instance (p. 330). The default time configuration for Amazon Linux instances uses Network Time Protocol to set the system time on an instance. The default time zone is UTC. For more information on setting the time zone for an instance or using your own time server, see Setting the Time for Your Linux Instance (p. 332). If you have your own network with a domain name registered to it, you can change the hostname of an instance to identify itself as part of that domain. You can also change the system prompt to show a more meaningful name without changing the hostname settings. For more information, see Changing the

API Version 2014-10-01 321

Amazon Elastic Compute Cloud User Guide for Linux Managing Software

Hostname of Your Linux Instance (p. 335). You can configure an instance to use a dynamic DNS service provider. For more information, see Setting Up Dynamic DNS on Your Linux Instance (p. 337). When you launch an instance in Amazon EC2, you have the option of passing user data to the instance that can be used to perform common configuration tasks and even run scripts after the instance starts. You can pass two types of user data to Amazon EC2, cloud-init directives, and shell scripts. For more information, see Running Commands on Your Linux Instance at Launch (p. 339).

Managing Software on Your Linux Instance The base distribution of Amazon Linux contains many software packages and utilities that are required for basic server operations. However, many more software packages are available in various software repositories, and even more packages are available for you to build from source code. Contents • • • • •

Updating Instance Software (p. 322) Adding Repositories (p. 326) Finding Software Packages (p. 327) Installing Software Packages (p. 328) Preparing to Compile Software (p. 329)

It is important to keep software up-to-date. Many packages in a Linux distribution are updated frequently to fix bugs, add features, and protect against security exploits. For more information, see Updating Instance Software (p. 322). By default, Amazon Linux instances launch with two repositories enabled: amzn-main and amzn-updates. While there are many packages available in these repositories that are updated by Amazon Web Services, there may be a package that you wish to install that is contained in another repository. For more information, see Adding Repositories (p. 326). For help finding packages in enabled repositories, see Finding Software Packages (p. 327). For information about installing software on an Amazon Linux instance, see Installing Software Packages (p. 328). Not all software is available in software packages stored in repositories; some software must be compiled on an instance from its source code. For more information, see Preparing to Compile Software (p. 329). Amazon Linux instances manage their software using the yum package manager. The yum package manager can install, remove, and update software, as well as manage all of the dependencies for each package. Debian-based Linux distributions, like Ubuntu, use the apt-get command and dpkg package manager, so the yum examples in the following sections do not work for those distributions.

Updating Instance Software It is important to keep software up-to-date. Many packages in a Linux distribution are updated frequently to fix bugs, add features, and protect against security exploits. When you first launch and connect to an Amazon Linux instance, you may see a message asking you to update software packages for security purposes. This section shows how to update an entire system, or just a single package.

Important These procedures are intended for use with Amazon Linux, but the commands and file locations are similar for Red Hat and CentOS. For more information about other distributions, see their specific documentation.

API Version 2014-10-01 322

Amazon Elastic Compute Cloud User Guide for Linux Updating Instance Software

__| __|_ ) _| ( / ___|\___|___|

Amazon Linux AMI

https://aws.amazon.com/amazon-linux-ami/2013.03-release-notes/ There are 12 security update(s) out of 25 total update(s) available Run "sudo yum update" to apply all updates. [ec2-user ~]$

To update all packages on an Amazon Linux instance 1.

(Optional) Start a screen session in your shell window. Sometimes you may experience a network interruption that can disconnect the SSH connection to your instance. If this happens during a long software update, it can leave the instance in a recoverable, although confused state. A screen session allows you to continue running the update even if your connection is interrupted, and you can reconnect to the session later without problems. a.

Execute the screen command to begin the session. [ec2-user ~]$ screen

b.

If your session is disconnected, log back into your instance and list the available screens. [ec2-user ~]$ screen -ls There is a screen on: 17793.pts-0.ip-12-34-56-78 (Detached) 1 Socket in /var/run/screen/S-ec2-user.

c.

Reconnect to the screen using the screen -r command and the process ID from the previous command. [ec2-user ~]$ screen -r 17793

d.

When you are finished using screen, use the exit command to close the session. [ec2-user ~]$ exit [screen is terminating]

2.

Run the yum update command. Optionally, you can add the --security flag to apply only security updates. [ec2-user ~]$ sudo yum update Loaded plugins: priorities, security, update-motd, upgrade-helper amzn-main | 2.1 kB 00:00 amzn-updates | 2.3 kB 00:00 Setting up Update Process Resolving Dependencies --> Running transaction check ---> Package aws-apitools-ec2.noarch 0:1.6.8.1-1.0.amzn1 will be updated ---> Package aws-apitools-ec2.noarch 0:1.6.10.0-1.0.amzn1 will be an update

API Version 2014-10-01 323

Amazon Elastic Compute Cloud User Guide for Linux Updating Instance Software

---> Package ---> Package ---> Package ---> Package ---> Package ---> Package ---> Package ---> Package ---> Package ---> Package --> Finished

gnupg2.x86_64 0:2.0.18-1.16.amzn1 will be updated gnupg2.x86_64 0:2.0.19-8.21.amzn1 will be an update libgcrypt.i686 0:1.4.5-9.10.amzn1 will be updated libgcrypt.x86_64 0:1.4.5-9.10.amzn1 will be updated libgcrypt.i686 0:1.4.5-9.12.amzn1 will be an update libgcrypt.x86_64 0:1.4.5-9.12.amzn1 will be an update openssl.x86_64 1:1.0.1e-4.53.amzn1 will be updated openssl.x86_64 1:1.0.1e-4.54.amzn1 will be an update python-boto.noarch 0:2.9.9-1.0.amzn1 will be updated python-boto.noarch 0:2.13.3-1.0.amzn1 will be an update Dependency Resolution

Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Updating: aws-apitools-ec2 noarch 1.6.10.0-1.0.amzn1 amzn-updates 14 M gnupg2 x86_64 2.0.19-8.21.amzn1 amzn-updates 2.4 M libgcrypt i686 1.4.5-9.12.amzn1 amzn-updates 248 k libgcrypt x86_64 1.4.5-9.12.amzn1 amzn-updates 262 k openssl x86_64 1:1.0.1e-4.54.amzn1 amzn-updates 1.7 M python-boto noarch 2.13.3-1.0.amzn1 amzn-updates 1.6 M Transaction Summary ================================================================================ Upgrade 6 Package(s) Total download size: 20 M Is this ok [y/N]:

3.

Review the packages listed, and type y and Enter to accept the updates. Updating all of the packages on a system can take several minutes. The yum output shows the status of the update while it is running. Downloading Packages: (1/6): aws-apitools-ec2-1.6.10.0-1.0.amzn1.noarch.rpm | 14 MB 00:00 (2/6): gnupg2-2.0.19-8.21.amzn1.x86_64.rpm | 2.4 MB 00:00 (3/6): libgcrypt-1.4.5-9.12.amzn1.i686.rpm | 248 kB 00:00 (4/6): libgcrypt-1.4.5-9.12.amzn1.x86_64.rpm | 262 kB 00:00 (5/6): openssl-1.0.1e-4.54.amzn1.x86_64.rpm | 1.7 MB 00:00 (6/6): python-boto-2.13.3-1.0.amzn1.noarch.rpm | 1.6 MB 00:00 ------------------------------------------------------------------------------Total 28 MB/s | 20 MB 00:00 Running rpm_check_debug Running Transaction Test

API Version 2014-10-01 324

Amazon Elastic Compute Cloud User Guide for Linux Updating Instance Software

Transaction Test Succeeded Running Transaction Updating : libgcrypt-1.4.5-9.12.amzn1.x86_64 1/12 Updating : gnupg2-2.0.19-8.21.amzn1.x86_64 2/12 Updating : aws-apitools-ec2-1.6.10.0-1.0.amzn1.noarch 3/12 Updating : 1:openssl-1.0.1e-4.54.amzn1.x86_64 4/12 ... Complete!

To update a single package on an Amazon Linux instance Use this procedure to update a single package (and its dependencies) and not the entire system. 1.

Run the yum update command with the name of the package you would like to update. [ec2-user ~]$ sudo yum update openssl Loaded plugins: priorities, security, update-motd, upgrade-helper amzn-main | 2.1 kB amzn-updates | 2.3 kB Setting up Update Process Resolving Dependencies --> Running transaction check ---> Package openssl.x86_64 1:1.0.1e-4.53.amzn1 will be updated ---> Package openssl.x86_64 1:1.0.1e-4.54.amzn1 will be an update --> Finished Dependency Resolution

00:00 00:00

Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Updating: openssl x86_64 1:1.0.1e-4.54.amzn1 amzn-updates 1.7 M Transaction Summary ================================================================================ Upgrade 1 Package(s) Total download size: 1.7 M Is this ok [y/N]:

2.

Review the package information listed, and type y and Enter to accept the update or updates. Sometimes there will be more than one package listed if there are package dependencies that must be resolved. The yum output shows the status of the update while it is running.

API Version 2014-10-01 325

Amazon Elastic Compute Cloud User Guide for Linux Adding Repositories

Downloading Packages: openssl-1.0.1e-4.54.amzn1.x86_64.rpm Running rpm_check_debug Running Transaction Test Transaction Test Succeeded Running Transaction Updating : 1:openssl-1.0.1e-4.54.amzn1.x86_64 1/2 Cleanup : 1:openssl-1.0.1e-4.53.amzn1.x86_64 2/2 Verifying : 1:openssl-1.0.1e-4.54.amzn1.x86_64 1/2 Verifying : 1:openssl-1.0.1e-4.53.amzn1.x86_64 2/2

| 1.7 MB

00:00

Updated: openssl.x86_64 1:1.0.1e-4.54.amzn1 Complete!

Adding Repositories By default, Amazon Linux instances launch with two repositories enabled: amzn-main and amzn-updates. While there are many packages available in these repositories that are updated by Amazon Web Services, there may be a package that you wish to install that is contained in another repository.

Important These procedures are intended for use with Amazon Linux, but the commands and file locations are similar for Red Hat and CentOS. For more information about other distributions, see their specific documentation. To install a package from a different repository with yum, you need to add the repository information to the /etc/yum.conf file or to its own repository.repo file in the /etc/yum.repos.d directory. You can do this manually, but most yum repositories provide their own repository.repo file at their repository URL.

To add a yum repository to /etc/yum.repos.d 1.

Find the location of the .repo file. This will vary depending on the repository you are adding. In this example, the .repo file is at https://www.example.com/repository.repo.

2.

Add the repository with the yum-config-manager command. [ec2-user ~]$ sudo yum-config-manager --add-repo https://www.example.com/re pository.repo Loaded plugins: priorities, update-motd, upgrade-helper adding repo from: https://www.example.com/repository.repo grabbing file https://www.example.com/repository.repo to /etc/yum.repos.d/re pository.repo repository.repo | 4.0 kB 00:00 repo saved to /etc/yum.repos.d/repository.repo

API Version 2014-10-01 326

Amazon Elastic Compute Cloud User Guide for Linux Finding Software Packages

To enable a yum repository in /etc/yum.repos.d •

Use the yum-config-manager command with the --enable repository flag. The following command enables the Extra Packages for Enterprise Linux (EPEL) repository from the Fedora project. By default, this repository is present in /etc/yum.repos.d on Amazon Linux instances, but it is not enabled. [ec2-user ~]$ sudo yum-config-manager --enable epel

Note For information on enabling the EPEL repository on other distributions, such as Red Hat and CentOS, see the EPEL documentation at https://fedoraproject.org/wiki/EPEL.

Finding Software Packages You can use the yum search command to search the descriptions of packages that are available in your configured repositories. This is especially helpful if you don't know the exact name of the package you want to install. Simply append the keyword search to the command; for multiple word searches, wrap the search query with quotation marks.

Important These procedures are intended for use with Amazon Linux, but the commands and file locations are similar for Red Hat and CentOS. For more information about other distributions, see their specific documentation. Multiple word search queries in quotation marks only return results that match the exact query. If you don't see the expected package, simplify your search to one keyword and then scan the results. You can also try keyword synonyms to broaden your search. [ec2-user ~]$ sudo yum search "find" Loaded plugins: priorities, security, update-motd, upgrade-helper ============================== N/S Matched: find =============================== findutils.x86_64 : The GNU versions of find utilities (find and xargs) perl-File-Find-Rule.noarch : Perl module implementing an alternative interface : to File::Find perl-Module-Find.noarch : Find and use installed modules in a (sub)category libpuzzle.i686 : Library to quickly find visually similar images (gif, png, jpg) libpuzzle.x86_64 : Library to quickly find visually similar images (gif, png, : jpg) mlocate.x86_64 : An utility for finding files by name

The yum package manager also combines several packages into groups that you can install with one command to perform a particular task, such as installing a web server or build tools for software compilation. To list the groups that are already installed on your system and the available groups that you can install, use the yum grouplist command. [ec2-user ~]$ sudo yum grouplist Loaded plugins: priorities, security, update-motd, upgrade-helper Setting up Group Process Installed Groups: Development Libraries Development tools

API Version 2014-10-01 327

Amazon Elastic Compute Cloud User Guide for Linux Installing Software Packages

Editors Legacy UNIX compatibility Mail Server MySQL Database Network Servers Networking Tools PHP Support Perl Support System Tools Web Server Available Groups: Console internet tools DNS Name Server FTP Server Java Development MySQL Database client NFS file server Performance Tools PostgreSQL Database client (version 8) PostgreSQL Database server (version 8) Scientific support TeX support Technical Writing Web Servlet Engine Done

You can see the different packages in a group by using the yum groupinfo "Group Name" command, replacing Group Name with the name of the group to get information about. This command lists all of the mandatory, default, and optional packages that can be installed with that group.

Installing Software Packages The yum package manager is a great tool for installing software, because it can search all of your enabled repositories for different software packages and also handle any dependencies in the software installation process.

Important These procedures are intended for use with Amazon Linux, but the commands and file locations are similar for Red Hat and CentOS. For more information about other distributions, see their specific documentation. To install a package from a repository, use the yum install package command, replacing package with the name of the software to install. For example, to install the links text-based web browser, enter the following command. [ec2-user ~]$ sudo yum install links

To install a group of packages, use the yum groupinstall Group Name command, replacing Group Name with the name of the group you would like to install. For example, to install the "Performance Tools" group, enter the following command. [ec2-user@ip-10-161-113-54 ~]$ sudo yum groupinstall "Performance Tools"

By default, yum will only install the mandatory and default packages in the group listing. If you would like to install the optional packages in the group also, you can set the group_package_types configuration parameter in the command when you execute it that adds the optional packages.

API Version 2014-10-01 328

Amazon Elastic Compute Cloud User Guide for Linux Preparing to Compile Software

[ec2-user ~]$ sudo yum --setopt=group_package_types=mandatory,default,optional groupinstall "Performance Tools"

You can also use yum install to install RPM package files that you have downloaded from the Internet. To do this, simply append the path name of an RPM file to the installation command instead of a repository package name. [ec2-user ~]$ sudo yum install my-package.rpm

Preparing to Compile Software There is a wealth of open-source software available on the Internet that has not been pre-compiled and made available for download from a package repository.You may eventually discover a software package that you need to compile yourself, from its source code. For your system to be able to compile software, you need to install several development tools, such as make, gcc, and autoconf.

Important These procedures are intended for use with Amazon Linux, but the commands and file locations are similar for Red Hat and CentOS. For more information about other distributions, see their specific documentation. Because software compilation is not a task that every Amazon EC2 instance requires, these tools are not installed by default, but they are available in a package group called "Development Tools" that is easily added to an instance with the yum groupinstall command. [ec2-user ~]$ sudo yum groupinstall "Development Tools"

Software source code packages are often available for download (from web sites such as https://github.com/ and http://sourceforge.net/) as a compressed archive file, called a tarball. These tarballs will usually have the .tar.gz file extension. You can decompress these archives with the tar command. [ec2-user ~]$ tar -xzf software.tar.gz

After you have decompressed and unarchived the source code package, you should look for a README or INSTALL file in the source code directory that can provide you with further instructions for compiling and installing the source code.

To retrieve source code for Amazon Linux packages Amazon Web Services provides the source code for maintained packages. You can download the source code for any installed packages with the get_reference_source command. •

Run the get_reference_source -p package command to download the source code for package. For example, to download the source code for the htop package, enter the following command. [ec2-user ~]$ get_reference_source -p htop Requested package: htop Found package from local RPM database: htop-1.0.1-2.3.amzn1.x86_64 Corresponding source RPM to found package : htop-1.0.1-2.3.amzn1.src.rpm Are these parameters correct? Please type 'yes' to continue: yes Source RPM downloaded to: /usr/src/srpm/debug/htop-1.0.1-2.3.amzn1.src.rpm

API Version 2014-10-01 329

Amazon Elastic Compute Cloud User Guide for Linux Managing Users

The command output lists the location of the source RPM, in this case /usr/src/srpm/debug/htop-1.0.1-2.3.amzn1.src.rpm.

Managing User Accounts on Your Linux Instance Each Linux instance type launches with a default Linux system user account. For Amazon Linux, the user name is ec2-user. For RHEL5, the user name is either root or ec2-user. For Ubuntu, the user name is ubuntu. For Fedora, the user name is either fedora or ec2-user. For SUSE Linux, the user name is root. Otherwise, if ec2-user and root don't work, check with your AMI provider.

Note Linux system users should not be confused with AWS Identity and Access Management (IAM) users. For more information, see IAM Users and Groups in the Using IAM guide. Using the default user account is adequate for many applications, but you may choose to add user accounts so that individuals can have their own files and workspaces. Creating user accounts for new users is much more secure than granting multiple (possibly inexperienced) users access to the ec2-user account, since that account can cause a lot of damage to a system when used improperly.

To add a new user to the system Effectively adding users to a Linux instance involves two basic operations: adding the user to the system, and providing that user with a way to log in remotely. 1.

To add a new user to the system, use the adduser command followed by any relevant options and the name of the user you wish to create.

Important If you are adding a user to an Ubuntu system, you should add the --disabled-password option to avoid adding a password to the account. [ec2-user ~]$ sudo adduser newuser

This command adds the newuser account to the system (with an entry in the /etc/passwd file), creates a newuser group, and creates a home directory for the account in /home/newuser. 2.

To provide remote access to this account, you must create a .ssh directory in the newuser home directory and create a file within it named "authorized_keys" that contains a public key. a.

Switch to the new account so that newly created files have the proper ownership. [ec2-user ~]$ sudo su - newuser [newuser ~]$

b.

Note that the prompt now says newuser instead of ec2-user; you have switched the shell session to the new account. Create a .ssh directory for the authorized_keys file. [newuser ~]$ mkdir .ssh

c.

Change the file permissions of the .ssh directory to 700 (this means only the file owner can read, write, or open the directory).

API Version 2014-10-01 330

Amazon Elastic Compute Cloud User Guide for Linux Managing Users

Important This step is very important; without these exact file permissions, you will not be able to log into this account using SSH. [newuser ~]$ chmod 700 .ssh

d.

Create a file named "authorized_keys" in the .ssh directory. [newuser ~]$ touch .ssh/authorized_keys

e.

Change the file permissions of the authorized_keys file to 600 (this means only the file owner can read or write to the file).

Important This step is very important; without these exact file permissions, you will not be able to log into this account using SSH. [newuser ~]$ chmod 600 .ssh/authorized_keys

f.

Edit the authorized_keys file with your favorite text editor and paste the public key for your key pair into the file, for example: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQClKsfkNkuSevGj3eYhCe53pcjqP3maAhD FcvBS7O6V hz2ItxCih+PnDSUaw+WNQn/mZphTk/a/gU8jEzoOWbkM4yxyb/wB96xbiFveSFJuOp/d6RJh JOI0iBXr lsLnBItntckiJ7FbtxJMXLvvwJryDUilBMTjYtwB+QhYXUMOzce5Pjz5/i8Se JtjnV3iAoG/cQk+0FzZ qaeJAAHco+CY/5WrUBkrHmFJr6HcXkvJdWPkYQS3xqC0+FmUZofz221CBt5IMucxXP kX4rWi+z7wB3Rb BQoQzd8v7yeb7OzlPnWOyN0qFU0XA246RA8QFYiCNYwI3f05p6KLxEXAMPLE

Note For more information about creating a key pair or retrieving a public key from an existing key pair, see Amazon EC2 Key Pairs (p. 413)

You should now be able to log into the newuser account on your instance via SSH using the private key that matches the public key from Step 2.f (p. 331).

To remove a user from the system If a user account is no longer needed, you can remove that account so that it may no longer be used. •

To delete a user account, the user's home directory, and the user's mail spool, execute the userdel -r command followed by the user name you wish to delete. [ec2-user ~]$ sudo userdel -r olduser

Note To keep the user's home directory and mail spool, omit the -r option.

API Version 2014-10-01 331

Amazon Elastic Compute Cloud User Guide for Linux Setting the Time

Setting the Time for Your Linux Instance A consistent and accurate time reference is crucial for many server tasks and processes. Most system logs include a time stamp that you can use to determine when problems occur and in what order the events take place. Network Time Protocol (NTP) is configured by default on Amazon Linux instances, and the system time is synchronized with a load-balanced pool of public servers on the Internet and set to the UTC time zone. For more information about NTP, go to http://www.ntp.org/. Tasks • Changing the Time Zone (p. 332) • Configuring Network Time Protocol (NTP) (p. 333)

Important These procedures are intended for use with Amazon Linux, but the commands and file locations are similar for Red Hat and CentOS. For more information about other distributions, see their specific documentation.

Changing the Time Zone Amazon Linux instances are set to the UTC (Coordinated Universal Time) time zone by default, but you may wish to change the time on an instance to the local time or to another time zone in your network.

To change the time zone on an instance 1.

Identify the time zone to use on the instance. The /usr/share/zoneinfo directory contains a hierarchy of time zone data files. Browse the directory structure at that location to find a file for your time zone. [ec2-user ~]$ ls /usr/share/zoneinfo Africa Chile GB Indian America CST6CDT GB-Eire Iran Antarctica Cuba GMT iso3166.tab Arctic EET GMT0 Israel ...

Mideast MST MST7MDT Navajo

posixrules PRC PST8PDT right

US UTC WET W-SU

Some of the entries at this location are directories (such as America), and these directories contain time zone files for specific cities. Find your city (or a city in your time zone) to use for the instance. In this example, you can use the time zone file for Los Angeles, /usr/share/zoneinfo/America/Los_Angeles. 2.

Update the /etc/sysconfig/clock file with the new time zone. a.

Open the /etc/sysconfig/clock file with your favorite text editor (such as vim or nano). You need to use sudo with your editor command because /etc/sysconfig/clock is owned by root.

b.

Locate the ZONE entry, and change it to the time zone file (omitting the /usr/share/zoneinfo section of the path). For example, to change to the Los Angeles time zone, change the ZONE entry to the following. ZONE="America/Los_Angeles"

c.

Save the file and exit the text editor.

API Version 2014-10-01 332

Amazon Elastic Compute Cloud User Guide for Linux Configuring Network Time Protocol (NTP)

3.

Create a symbolic link between /etc/localtime and your time zone file so that the instance finds the time zone file when it references local time information. [ec2-user ~]$ sudo ln -sf /usr/share/zoneinfo/America/Los_Angeles /etc/loc altime

4.

Reboot the system to pick up the new time zone information in all services and applications. [ec2-user ~]$ sudo reboot

Configuring Network Time Protocol (NTP) Network Time Protocol (NTP) is configured by default on Amazon Linux instances; however, an instance needs access to the Internet for the standard NTP configuration to work. The procedures in this section show how to verify that the default NTP configuration is working correctly. If your instance does not have access to the Internet, you need to configure NTP to query a different server in your private network to keep accurate time.

To verify that NTP is working properly 1.

Use the ntpstat command to view the status of the NTP service on the instance. [ec2-user ~]$ ntpstat

If your output resembles the output below, then NTP is working properly on the instance. synchronised to NTP server (12.34.56.78) at stratum 3 time correct to within 399 ms polling server every 64 s

If your output states, "unsynchronised", wait a minute and try again. The first synchronization may take a minute to complete.

2.

If your output states, "Unable to talk to NTP daemon. Is it running?", you probably need to start the NTP service and enable it to automatically start at boot time. (Optional) You can use the ntpq -p command to see a list of peers known to the NTP server and a summary of their state. [ec2-user ~]$ ntpq -p remote refid st t when poll reach delay offset jitter ============================================================================== +lttleman.deekay 204.9.54.119 2 u 15 128 377 88.649 5.946 6.876 -bittorrent.tomh 91.189.94.4 3 u 133 128 377 182.673 8.001 1.278 *ntp3.junkemailf 216.218.254.202 2 u 68 128 377 29.377 4.726 11.887 +tesla.selinc.co 149.20.64.28 2 u 31 128 377 28.586 -1.215 1.435

API Version 2014-10-01 333

Amazon Elastic Compute Cloud User Guide for Linux Configuring Network Time Protocol (NTP)

To start and enable NTP 1.

Start the NTP service with the following command. [ec2-user ~]$ sudo service ntpd start Starting ntpd:

2.

[

OK

]

Enable NTP to start at boot time with the chkconfig command. [ec2-user ~]$ sudo chkconfig ntpd on

3.

Verify that NTP is enabled with the following command. [ec2-user ~]$ sudo chkconfig --list ntpd ntpd 0:off 1:off 2:on 3:on 4:on 5:on 6:off

Here ntpd is on in runlevels 2, 3, 4, and 5, which is correct.

To change NTP servers You may decide not to use the standard NTP servers or you may need to use your own NTP server within your private network for instances that do not have Internet access. 1.

Open the /etc/ntp.conf file in your favorite text editor (such as vim or nano). You need to use sudo with the editor command because /etc/ntp.conf is owned by root.

2.

Find the server section, which defines the servers to poll for NTP configuration. # Use public servers from the pool.ntp.org project. # Please consider joining the pool (http://www.pool.ntp.org/join.html). server 0.amazon.pool.ntp.org iburst server 1.amazon.pool.ntp.org iburst server 2.amazon.pool.ntp.org iburst server 3.amazon.pool.ntp.org iburst

3.

Comment out the servers you don't want to use by adding a "#" character to the beginning of those server definitions. # Use public servers from the # Please consider joining the #server 0.amazon.pool.ntp.org #server 1.amazon.pool.ntp.org #server 2.amazon.pool.ntp.org #server 3.amazon.pool.ntp.org

4.

pool.ntp.org project. pool (http://www.pool.ntp.org/join.html). iburst iburst iburst iburst

Add an entry for each server to poll for time synchronization. You can use a DNS name for this entry or a dotted quad IP address (such as 10.0.0.254). server my-ntp-server.my-domain.com iburst

5.

Restart the NTP service to pick up the new servers.

API Version 2014-10-01 334

Amazon Elastic Compute Cloud User Guide for Linux Changing the Hostname

[ec2-user ~]$ sudo service ntpd start Starting ntpd:

6.

[

OK

]

Verify that your new settings work and that NTP is functioning. [ec2-user ~]$ ntpstat synchronised to NTP server (64.246.132.14) at stratum 2 time correct to within 99 ms

Changing the Hostname of Your Linux Instance When you launch an instance, it is assigned a hostname that is a form of the private, internal IP address. A typical Amazon EC2 private DNS name looks something like this: ip-12-34-56-78.us-west2.compute.internal, where the name consists of the internal domain, the service (in this case, compute), the region, and a form of the private IP address. Part of this hostname is displayed at the shell prompt when you log into your instance (for example, ip-12-34-56-78). Each time you stop and restart your Amazon EC2 instance (unless you are using an Elastic IP address), the public and private IP addresses change, and so does your public DNS name, system hostname, and shell prompt.

Important These procedures are intended for use with Amazon Linux, but the commands and file locations are similar for Red Hat and CentOS. For more information about other distributions, see their specific documentation.

Changing the System Hostname If you have a public DNS name registered for the IP address of your instance (such as webserver.mydomain.com), you can set the system hostname so your instance identifies itself as a part of that domain. This also changes the shell prompt so that it displays the first portion of this name instead of the hostname supplied by AWS (for example, ip-12-34-56-78). If you do not have a public DNS name registered, you can still change the hostname, but the process is a little different.

To change the system hostname to a public DNS name Follow this procedure if you already have a public DNS name registered. 1.

Open the /etc/sysconfig/network configuration file in your favorite text editor and change the HOSTNAME entry to reflect the fully qualified domain name (such as webserver.mydomain.com). HOSTNAME=webserver.mydomain.com

2.

Reboot the instance to pick up the new hostname. [ec2-user ~]$ sudo reboot

3.

Log into your instance and verify that the hostname has been updated. Your prompt should show the new hostname (up to the first ".") and the hostname command should show the fully qualified domain name.

API Version 2014-10-01 335

Amazon Elastic Compute Cloud User Guide for Linux Changing the Shell Prompt Without Affecting the Hostname [ec2-user@webserver ~]$ hostname webserver.mydomain.com

To change the system hostname without a public DNS name 1.

Open the /etc/sysconfig/network configuration file in your favorite text editor and change the HOSTNAME entry to reflect the desired system hostname (such as webserver). HOSTNAME=webserver.localdomain

2.

Open the /etc/hosts file in your favorite text editor and change the entry beginning with 127.0.0.1 to match the example below, substituting your own hostname. 127.0.0.1 webserver.localdomain webserver localhost localhost.localdomain

3.

Reboot the instance to pick up the new hostname. [ec2-user ~]$ sudo reboot

4.

Log into your instance and verify that the hostname has been updated. Your prompt should show the new hostname (up to the first ".") and the hostname command should show the fully qualified domain name. [ec2-user@webserver ~]$ hostname webserver.localdomain

Changing the Shell Prompt Without Affecting the Hostname If you do not want to modify the hostname for your instance, but you would like to have a more useful system name (such as webserver) displayed than the private name supplied by AWS (for example, ip12-34-56-78), you can edit the shell prompt configuration files to display your system nickname instead of the hostname.

To change the shell prompt to a host nickname 1.

Create a file in /etc/profile.d that sets the environment variable called NICKNAME to the value you want in the shell prompt. For example, to set the system nickname to webserver, execute the following command. [ec2-user ~]$ sudo sh -c 'echo "export NICKNAME=webserver" > /etc/pro file.d/prompt.sh'

2.

Open the /etc/bashrc file in your favorite text editor (such as vim or nano).You need to use sudo with the editor command because /etc/bashrc is owned by root.

API Version 2014-10-01 336

Amazon Elastic Compute Cloud User Guide for Linux Setting Up Dynamic DNS

3.

Edit the file and change the shell prompt variable (PS1) to display your nickname instead of the hostname. Find the following line that sets the shell prompt in /etc/bashrc (several surrounding lines are shown below for context; look for the line that starts with [ "$PS1"): # Turn on checkwinsize shopt -s checkwinsize [ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\u@\h \W]\\$ " # You might want to have e.g. tty in prompt (e.g. more virtual machines) # and console windows

And change the \h (the symbol for hostname) in that line to the value of the NICKNAME variable. # Turn on checkwinsize shopt -s checkwinsize [ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\u@$NICKNAME \W]\\$ " # You might want to have e.g. tty in prompt (e.g. more virtual machines) # and console windows

4.

(Optional) To set the title on shell windows to the new nickname, complete the following steps. a.

Create a file called /etc/sysconfig/bash-prompt-xterm. [ec2-user ~]$ sudo touch /etc/sysconfig/bash-prompt-xterm

b.

Make the file executable with the following command. [ec2-user ~]$ sudo chmod +x /etc/sysconfig/bash-prompt-xterm

c.

Open the /etc/sysconfig/bash-prompt-xterm file in your favorite text editor (such as vim or nano). You need to use sudo with the editor command because /etc/sysconfig/bashprompt-xterm is owned by root.

d.

Add the following line to the file. echo -ne "\033]0;${USER}@${NICKNAME}:${PWD/#$HOME/~}\007"

5.

Log out and then log back in to pick up the new nickname value.

Setting Up Dynamic DNS on Your Linux Instance When you launch an Amazon EC2 instance, it is assigned a public IP address and a public DNS (Domain Name System) name that you can use to reach it from the Internet. Because there are so many hosts in the Amazon Web Services domain, these public names must be quite long for each name to remain unique. A typical Amazon EC2 public DNS name looks something like this: ec2-12-34-56-78.uswest-2.compute.amazonaws.com, where the name consists of the Amazon Web Services domain, the service (in this case, compute), the region, and a form of the public IP address. Dynamic DNS services provide custom DNS host names within their domain area that can be easy to remember and that can also be more relevant to your host's use case; some of these services are also free of charge. You can use a dynamic DNS provider with Amazon EC2 and configure the instance to

API Version 2014-10-01 337

Amazon Elastic Compute Cloud User Guide for Linux Setting Up Dynamic DNS

update the IP address associated with a public DNS name each time the instance starts. There are many different providers to choose from, and the specific details of choosing a provider and registering a name with them are outside the scope of this guide. A simple web search of "dynamic DNS" should return multiple results for service providers, many of whom provide this service for free.

Important These procedures are intended for use with Amazon Linux, but the commands and file locations are similar for Red Hat and CentOS. For more information about other distributions, see their specific documentation.

To use dynamic DNS with Amazon EC2 1. 2.

Sign up with a dynamic DNS service provider and register a public DNS name with their service. In this procedure, you can use the free service from no-ip.com/free. Configure the dynamic DNS update client. After you have a dynamic DNS service provider and a public DNS name registered with their service, point the DNS name to the IP address for your instance. Many providers allow you to do this manually from your account page on their website, but many also allow you to do this automatically with a software update client. In this example, you can use the noip2 client, which only works with the service provided by no-ip.com.

Note Other service providers may offer their own client, or you may be able to configure the ddclient update utility to work with their service. For more information, see the specific documentation for your service provider and http://sourceforge.net/p/ddclient/wiki/Home/. a.

Enable the Extra Packages for Enterprise Linux (EPEL) repository to gain access to the noip client. The ddclient package is also available in this repository, but the configuration steps that follow are different.

Note Amazon Linux instances have the GPG keys and repository information for the EPEL repository installed by default; however, Red Hat and CentOS instances must first install the epel-release package before you can enable the EPEL repository. For more information and to download the latest version of this package, see https://fedoraproject.org/wiki/EPEL. [ec2-user ~]$ sudo yum-config-manager --enable epel

b.

Install the noip package. [ec2-user ~]$ sudo yum install -y noip

c.

Create the noip2 configuration file. Enter the login and password information for when prompted and answer the subsequent questions to configure the client. [ec2-user ~]$ sudo noip2 -C

3.

Enable the noip service with the chkconfig command. [ec2-user ~]$ sudo chkconfig noip on

You can verify that the service is enabled with the chkconfig --list command.

API Version 2014-10-01 338

Amazon Elastic Compute Cloud User Guide for Linux Running Commands at Launch

[ec2-user ~]$ chkconfig --list noip noip 0:off 1:off 2:on 3:on 4:on 5:on 6:off

4.

Here, noip is on in runlevels 2, 3, 4, and 5 (which is correct). Now the update client starts at every boot and updates the public DNS record to point to the IP address of the instance. Start the noip service. [ec2-user ~]$ sudo service noip start Starting noip2:

[

OK

]

This command starts the client, which reads the configuration file (/etc/no-ip2.conf) that you created earlier and updates the IP address for the public DNS name that you chose. 5.

Verify that the update client has set the correct IP address for your dynamic DNS name. Allow a few minutes for the DNS records to update, and then try to connect to your instance via SSH with the public DNS name that you configured in this procedure.

Running Commands on Your Linux Instance at Launch When you launch an instance in Amazon EC2, you have the option of passing user data to the instance that can be used to perform common automated configuration tasks and even run scripts after the instance starts. You can pass two types of user data to Amazon EC2: shell scripts and cloud-init directives. You can also pass this data into the launch wizard as plain text, as a file (this is useful for launching instances via the command line tools), or as base64-encoded text (for API calls). If you are interested in more complex automation scenarios, consider using AWS CloudFormation and AWS OpsWorks. For more information, see the AWS CloudFormation User Guide and the AWS OpsWorks User Guide. In the following examples, the commands from the Installing a LAMP Web Server tutorial (p. 38) are converted to a shell script and a set of cloud-init directives that executes when the instance launches. In each example, the following tasks are executed by the user data: • The distribution software packages are updated. • The necessary web server, php, and mysql packages are installed. • The httpd service is started and turned on via chkconfig. • The www group is added, and the ec2-user is added to that group. • The appropriate ownership and file permissions are set for the web directory and the files contained within it. • A simple web page is created to test the web server and php engine. Contents • Prerequisites (p. 340) • User Data and Shell Scripts (p. 340) • User Data and cloud-init Directives (p. 341)

API Version 2014-10-01 339

Amazon Elastic Compute Cloud User Guide for Linux Prerequisites

Prerequisites The following examples assume that your instance has a public DNS name that is reachable from the Internet. For more information, see Launch an Amazon EC2 Instance (p. 27). You must also configure your security group to allow SSH (port 22), HTTP (port 80), and HTTPS (port 443) connections. For more information about these prerequisites, see Setting Up with Amazon EC2 (p. 20). Also, these instructions are intended for use with Amazon Linux, and the commands and directives may not work for other Linux distributions. For more information about other distributions, such as their support for cloud-init, see their specific documentation.

User Data and Shell Scripts If you are familiar with shell scripting, this is the easiest and most complete way to send instructions to an instance at launch, and the cloud-init log file (/var/log/cloud-init.log) captures console output so it is easy to debug your scripts following a launch if the instance does not behave the way you intended.

Important User data scripts and cloud-init directives only run during the first boot cycle when an instance is launched. User data shell scripts must start with the #! characters and the path to the interpreter you want to read the script (commonly /bin/bash). For a great introduction on shell scripting, see the BASH Programming HOW-TO at the Linux Documentation Project (tldp.org). Scripts entered as user data are executed as the root user, so do not use the sudo command in the script. Remember that any files you create will be owned by root; if you need non-root users to have file access, you should modify the permissions accordingly in the script. Also, because the script is not run interactively, you cannot include commands that require user feedback (such as yum update without the -y flag). Adding these tasks at boot time adds to the amount of time it takes to boot the instance.You should allow a few minutes of extra time for the tasks to complete before you test that the user script has finished successfully.

To pass a shell script to an instance with user data 1.

Follow the procedure for launching an instance at Launching Your Instance from an AMI (p. 290), but when you get to Step 6 (p. 292), paste the user data script text into the User data field and then complete the launch procedure. For the example below, the script creates and configures our web server. #!/bin/bash yum update -y yum groupinstall -y "Web Server" "MySQL Database" "PHP Support" yum install -y php-mysql service httpd start chkconfig httpd on groupadd www usermod -a -G www ec2-user chown -R root:www /var/www chmod 2775 /var/www find /var/www -type d -exec chmod 2775 {} + find /var/www -type f -exec chmod 0664 {} + echo "" > /var/www/html/phpinfo.php

API Version 2014-10-01 340

Amazon Elastic Compute Cloud User Guide for Linux User Data and cloud-init Directives

2.

Allow enough time for the instance to launch and execute the commands in your script, and then check to see that your script has completed the tasks that you intended. For our example, in a web browser, enter the URL of the PHP test file the script created. This URL is the public DNS address of your instance followed by a forward slash and the file name. http://my.public.dns.amazonaws.com/phpinfo.php

You should see the PHP information page.

Tip If you are unable to see the PHP information page, check that the security group you are using contains a rule to allow HTTP (port 80) traffic. For information about adding an HTTP rule to your security group, see Adding Rules to a Security Group (p. 426). 3.

(Optional) If your script did not accomplish the tasks you were expecting it to, or if you just want to verify that your script completed without errors, examine the cloud-init log file at /var/log/cloud-init.log and look for error messages in the output. For additional debugging information, you can create a Mime multipart archive that includes a cloudinit data section with the following directive: output : { all : '| tee -a /var/log/cloud-init-output.log' }

This directive sends command output from your script to /var/log/cloud-init-output.log. For more information on cloud-init data formats and creating Mime multi part archive, see cloudinit Formats.

User Data and cloud-init Directives The cloud-init package configures specific aspects of a new Amazon Linux instance when it is launched; most notably, it configures the .ssh/authorized_keys file for the ec2-user so you can log in with your own private key. The cloud-init user directives can be passed to an instance at launch the same way that a script is passed, although the syntax is different. For more information about cloud-init, go to http://cloudinit.readthedocs.org/en/latest/index.html.

Important User data scripts and cloud-init directives only run during the first boot cycle when an instance is launched. The Amazon Linux version of cloud-init does not support all of the directives that are available in the base package, and some of the directives have been renamed (such as repo_update instead of aptupgrade). Adding these tasks at boot time adds to the amount of time it takes to boot an instance. You should allow a few minutes of extra time for the tasks to complete before you test that your user data directives have completed.

To pass cloud-init directives to an instance with user data 1.

Follow the procedure for launching an instance at Launching Your Instance from an AMI (p. 290), but when you get to Step 6 (p. 292), paste your cloud-init directive text into the User data field and then complete the launch procedure. For the example below, the directives create and configure a web server.

API Version 2014-10-01 341

Amazon Elastic Compute Cloud User Guide for Linux User Data and cloud-init Directives

#cloud-config repo_update: true repo_upgrade: all packages: - httpd - crypto-utils - mod_perl - mod_ssl - mod_wsgi - mysql-server - php - php-gd - php-pdo - php-pear - php-xml - php-mysql runcmd: - service httpd start - chkconfig httpd on - groupadd www - [ sh, -c, "usermod -a -G www ec2-user" ] - [ sh, -c, "chown -R root:www /var/www" ] - chmod 2775 /var/www - [ find, /var/www, -type, d, -exec, chmod, 2775, {}, + ] - [ find, /var/www, -type, f, -exec, chmod, 0664, {}, + ] - [ sh, -c, 'echo "" > /var/www/html/phpinfo.php' ]

2.

Allow enough time for the instance to launch and execute the directives in your user data, and then check to see that your directives have completed the tasks you intended. For our example, in a web browser, enter the URL of the PHP test file the directives created. This URL is the public DNS address of your instance followed by a forward slash and the file name. http://my.public.dns.amazonaws.com/phpinfo.php

You should see the PHP information page.

Tip If you are unable to see the PHP information page, check that the security group you are using contains a rule to allow HTTP (port 80) traffic. For information about adding an HTTP rule to your security group, see Adding Rules to a Security Group (p. 426). 3.

(Optional) If your directives did not accomplish the tasks you were expecting them to, or if you just want to verify that your directives completed without errors, examine the cloud-init log file at /var/log/cloud-init.log and look for error messages in the output. For additional debugging information, you can add the following line to your directives: output : { all : '| tee -a /var/log/cloud-init-output.log' }

This directive sends runcmd output to /var/log/cloud-init-output.log.

API Version 2014-10-01 342

Amazon Elastic Compute Cloud User Guide for Linux

Monitoring Amazon EC2 Monitoring is an important part of maintaining the reliability, availability, and performance of your Amazon Elastic Compute Cloud (Amazon EC2) instances and your AWS solutions. You should collect monitoring data from all of the parts in your AWS solutions so that you can more easily debug a multi-point failure if one occurs. Before you start monitoring Amazon EC2, however, you should create a monitoring plan that should include: • • • • • •

What are your goals for monitoring? What resources you will monitor? How often you will monitor these resources? What monitoring tools will you use? Who will perform the monitoring tasks? Who should be notified when something goes wrong?

After you have defined your monitoring goals and have created your monitoring plan, the next step is to establish a baseline for normal Amazon EC2 performance in your environment. You should measure Amazon EC2 performance at various times and under different load conditions. As you monitor Amazon EC2, you should store a history of monitoring data that you've collected.You can compare current Amazon EC2 performance to this historical data to help you to identify normal performance patterns and performance anomalies, and devise methods to address them. For example, you can monitor CPU utilization, disk I/O, and network utilization for your Amazon EC2 instances. When performance falls outside your established baseline, you might need to reconfigure or optimize the instance to reduce CPU utilization, improve disk I/O, or reduce network traffic. To establish a baseline you should, at a minimum, monitor the following items: Item to Monitor

Amazon EC2 Metric

CPU utilization

CPUUtilization (p. 358)

Monitoring Script

Memory utilization

Monitoring Scripts for Amazon EC2 Instances (p. 405)

Memory used

Monitoring Scripts for Amazon EC2 Instances (p. 405)

Memory available

Monitoring Scripts for Amazon EC2 Instances (p. 405)

API Version 2014-10-01 343

Amazon Elastic Compute Cloud User Guide for Linux Automated and Manual Monitoring

Item to Monitor

Amazon EC2 Metric

Network utilization

NetworkIn (p. 358)

Monitoring Script

NetworkOut (p. 358) Disk performance

DiskReadOps (p. 358) DiskWriteOps (p. 358)

Disk Swap utilization

Monitoring Scripts for Amazon EC2 Instances (p. 405)

Swap used (Linux) Page File utilization

Monitoring Scripts for Amazon EC2 Instances (p. 405)

Page File used Page File available Disk Reads/Writes

DiskReadBytes (p. 358) DiskWriteBytes (p. 358)

Disk Space utilization

Monitoring Scripts for Amazon EC2 Instances (p. 405)

Disk Space used

Monitoring Scripts for Amazon EC2 Instances (p. 405)

Disk Space available

Monitoring Scripts for Amazon EC2 Instances (p. 405)

Automated and Manual Monitoring AWS provides various tools that you can use to monitor Amazon EC2. You can configure some of these tools to do the monitoring for you, while some of the tools require manual intervention. Topics • Automated Monitoring Tools (p. 344) • Manual Monitoring Tools (p. 345)

Automated Monitoring Tools You can use the following automated monitoring tools to watch Amazon EC2 and report back to you when something is wrong: • System Status Checks - monitor the AWS systems required to use your instance to ensure they are working properly. These checks detect problems with your instance that require AWS involvement to repair. When a system status check fails, you can choose to wait for AWS to fix the issue or you can resolve it yourself (for example, by stopping and restarting or terminating and replacing an instance). Examples of problems that cause system status checks to fail include: • Loss of network connectivity • Loss of system power • Software issues on the physical host

API Version 2014-10-01 344

Amazon Elastic Compute Cloud User Guide for Linux Manual Monitoring Tools

• Hardware issues on the physical host For more information, see Monitoring Instances with Status Checks (p. 346). • Instance Status Checks - monitor the software and network configuration of your individual instance. These checks detect problems that require your involvement to repair. When an instance status check fails, typically you will need to address the problem yourself (for example by rebooting the instance or by making modifications in your operating system). Examples of problems that may cause instance status checks to fail include: • Failed system status checks • Misconfigured networking or startup configuration • Exhausted memory • Corrupted file system • Incompatible kernel For more information, see Monitoring Instances with Status Checks (p. 346). • Amazon CloudWatch Alarms - watch a single metric over a time period you specify, and perform one or more actions based on the value of the metric relative to a given threshold over a number of time periods. The action is a notification sent to an Amazon Simple Notification Service (Amazon SNS) topic or Auto Scaling policy. Alarms invoke actions for sustained state changes only. CloudWatch alarms will not invoke actions simply because they are in a particular state, the state must have changed and been maintained for a specified number of periods. For more information, see Monitoring Your Instances with CloudWatch (p. 354). • Amazon EC2 Monitoring Scripts - Perl and PowerShell scripts that can monitor memory, disk, and page/swap file usage in your instances. For more information, see Monitoring Scripts for Amazon EC2 Instances (p. 405). • AWS Management Pack for Microsoft System Center Operations Manager - links Amazon EC2 instances and the Microsoft Windows or Linux operating systems running inside them. The AWS Management Pack is an extension to Microsoft System Center Operations Manager. It uses a designated computer in your datacenter (called a watcher node) and the Amazon Web Services APIs to remotely discover and collect information about your AWS resources. For more information, see AWS Management Pack for Microsoft System Center.

Manual Monitoring Tools Another important part of monitoring Amazon EC2 involves manually monitoring those items that the monitoring scripts, status checks, and CloudWatch alarms don't cover.The Amazon EC2 and CloudWatch console dashboards provide an at-a-glance view of the state of your Amazon EC2 environment. • Amazon EC2 Dashboard shows: • Service Health and Scheduled Events by region • Instance state • Status checks • Alarm status • Instance metric details (In the navigation pane click Instances, select an instance, and then click the Monitoring tab) • Volume metric details (In the navigation pane click Volumes, select a volume, and then click the Monitoring tab) • Amazon CloudWatch Dashboard shows: • Current alarms and status • Graphs of alarms and resources • Service health status

API Version 2014-10-01 345

Amazon Elastic Compute Cloud User Guide for Linux Best Practices for Monitoring

In addition, you can use CloudWatch to do the following: • Graph Amazon EC2 monitoring data to troubleshoot issues and discover trends • Search and browse all your AWS resource metrics • Create and edit alarms to be notified of problems • See at-a-glance overviews of your alarms and AWS resources

Best Practices for Monitoring Use the following best practices for monitoring to help you with your Amazon EC2 monitoring tasks. • Make monitoring a priority to head off small problems before they become big ones. • Create and implement a monitoring plan that collects monitoring data from all of the parts in your AWS solution so that you can more easily debug a multi-point failure if one occurs. Your monitoring plan should address, at a minimum, the following questions: • What are your goals for monitoring? • What resources you will monitor? • How often you will monitor these resources? • What monitoring tools will you use? • Who will perform the monitoring tasks? • Who should be notified when something goes wrong? • Automate monitoring tasks as much as possible. • Check the log files on your EC2 instances.

Monitoring the Status of Your Instances You can monitor the status of your instances by viewing status checks and scheduled events for your instances. A status check gives you the information that results from automated checks performed by Amazon EC2. These automated checks detect whether specific issues are affecting your instances. The status check information, together with the data provided by Amazon CloudWatch, gives you detailed operational visibility into each of your instances. You can also see status on specific events scheduled for your instances. Events provide information about upcoming activities such as rebooting or retirement that are planned for your instances, along with the scheduled start and end time of each event. Contents • Monitoring Instances with Status Checks (p. 346) • Monitoring Events for Your Instances (p. 351)

Monitoring Instances with Status Checks With instance status monitoring you can quickly determine whether Amazon EC2 has detected any problems that may prevent your instances from running applications. Amazon EC2 performs automated checks on every running Amazon EC2 instance to identify hardware and software issues. You can view the results of these status checks to identify specific and detectable problems. This data augments the information that Amazon EC2 already provides about the intended state of each instance (pending, running, stopping, etc.) as well as the utilization metrics that Amazon CloudWatch monitors (CPU utilization, network traffic, and disk activity).

API Version 2014-10-01 346

Amazon Elastic Compute Cloud User Guide for Linux Monitoring Instances with Status Checks

Status checks are performed every minute and each returns a pass or a fail status. If all checks pass, the overall status of the instance is OK. If one or more checks fail, the overall status is impaired. Status checks are built into Amazon EC2, so they cannot be disabled or deleted. You can, however create or delete alarms that are triggered based on the result of the status checks. For example, you can create an alarm to warn you if status checks fail on a specific instance. For more information, see Creating and Editing Status Check Alarms (p. 349). There are two types of status checks: system status checks and instance status checks. System status checks monitor the AWS systems required to use your instance to ensure they are working properly. These checks detect problems with your instance that require AWS involvement to repair. When a system status check fails, you can choose to wait for AWS to fix the issue or you can resolve it yourself (for example, by stopping and restarting or terminating and replacing an instance). Examples of problems that cause system status checks to fail include: • • • •

Loss of network connectivity Loss of system power Software issues on the physical host Hardware issues on the physical host

Instance status checks monitor the software and network configuration of your individual instance. These checks detect problems that require your involvement to repair. When an instance status check fails, typically you will need to address the problem yourself (for example, by rebooting the instance or by making modifications in your operating system). Examples of problems that may cause instance status checks to fail include: • • • • •

Failed system status checks Misconfigured networking or startup configuration Exhausted memory Corrupted file system Incompatible kernel

Viewing Status AWS provides you with several ways to view and work with status checks: You can use the AWS Management Console, interact directly with the API, or use the command line interface.

Amazon EC2 Console To view status checks using the console 1. 2.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. In the navigation pane, click Instances.

3. 4.

On the Instances page, the Status Checks column lists the operational status of each instance. To view an individual instance’s status, select the instance, and then click the Status Checks tab.

API Version 2014-10-01 347

Amazon Elastic Compute Cloud User Guide for Linux Monitoring Instances with Status Checks

Note If you have an instance with a failed status check and the instance has been unreachable for over 20 minutes, you can click Contact AWS Support to submit a request for assistance. To try and troubleshoot system or instance status check failures yourself, see Troubleshooting Instances with Failed Status Checks (p. 639).

Command Line Interface To do this

Run this command

Get the status of all instances

describe-instance-status

Get the status of all instances with a instance status describe-instance-status --filters of impaired Name=instance-status.status,Values=impaired Get the status of a single instance with instance ID describe-instance-status --instance-ids i-15a4417c -i-15a4417c

For more information about using the describe-instance-status command, see describe-instance-status in the AWS Command Line Interface Reference.

Note If you have an instance with a failed status check, see Troubleshooting Instances with Failed Status Checks (p. 639)

API You can use the DescribeInstanceStatus action to retrieve the status of your instances. For more information, see DescribeInstanceStatus in the Amazon EC2 API Reference.

Reporting Status You can provide feedback about your instances if you are having problems with an instance whose status is not shown as impaired, or to send AWS additional details about the problems you are experiencing with an impaired instance. We use reported feedback to identify issues impacting multiple customers, but do not respond to individual account issues reported via this form. Providing feedback does not change the status check results that you currently see for this instance. If you are in need of technical assistance specific to your account, please post your question to the Developer Forums or contact Premium Support.

API Version 2014-10-01 348

Amazon Elastic Compute Cloud User Guide for Linux Monitoring Instances with Status Checks

Amazon EC2 Console To report status feedback using the console 1. 2. 3.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. In the navigation pane, click Instances. On the Instances page, click on the instance on which you want to report status.

4. 5.

Click the Status Checks tab, and then click Submit feedback. Complete the information on the Report Instance Status page.

Command Line Interface Use the report-instance-status command to send status feedback using the command line interface. The command uses the following syntax: aws ec2 report-instance-status [--instances ...] [--status ...] [--reason-codes] ..]

For more information about using the report-instance-status command, see the report-instancestatus command in the AWS Command Line Interface Reference.

API You can use the ReportInstanceStatus action to submit feedback about a running instance's status. If your experience with the instance differs from the instance status returned by the DescribeInstanceStatus action, use ReportInstanceStatus to report your experience with the instance. Amazon EC2 collects this information to improve the accuracy of status checks. For more information, see ReportInstanceStatus in the Amazon EC2 API Reference.

Creating and Editing Status Check Alarms You can create instance status and system status alarms to notify you when an instance has a failed status check. To create or change these alarms, you can use either the AWS Management Console or the command line interface (CLI).

AWS Management Console To create a status check alarm You can create status check alarms for an existing instance to monitor instance status or system status. You can configure the alarm to send you a notification by email when an instance fails an instance check or system status check. 1.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

2. 3. 4.

In the navigation pane, click Instances. Select an instance, and then on the Status Checks tab, click Create Status Check Alarm. In the Create Alarm dialog box, select the Send a notification to check box, and then choose an existing Amazon Simple Notification Service (SNS) topic or create a new SNS topic to use for this alarm.

5.

In the With these recipients box, type your email address (e.g., [emailprotected]) and the addresses of any additional recipients, separated by commas. In the Whenever drop-down list, select the status check you want to be notified about (e.g., Status Check Failed (Any), Status Check Failed (Instance), or Status Check Failed (System)).

6.

API Version 2014-10-01 349

Amazon Elastic Compute Cloud User Guide for Linux Monitoring Instances with Status Checks

7.

8.

In the For at least box, set the number of periods you want to evaluate (for example, 2) and in the consecutive periods drop-down menu, select the evaluation period duration (for example, 5 minutes) before triggering the alarm and sending an email To change the default name for the alarm, in the Name of alarm box, type a friendly name for the alarm (for example, StatusCheckFailed), and then click Create Alarm.

Important If you added an email address to the list of recipients or created a new topic, Amazon SNS will send a subscription confirmation email message to each new address shortly after you create an alarm. Remember to click the link contained in that message, which confirms your subscription. Alert notifications are sent only to confirmed addresses.

To edit a status check alarm If you need to make changes to an instance status alarm, you can edit it. 1. 2. 3. 4. 5.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. In the navigation pane, click Instances. Select an instance, click Actions, and then click Add/Edit Alarms. In the Alarm Details dialog box, click the name of the alarm. In the Edit Alarm dialog box, make the desired changes, and then click Save.

Command Line Interface To create a status check alarm using the CLI You can create a status check alarm using the AWS CLI. In the following example, the alarm publishes a notification to a specific SNS topic that has the ARN arn:aws:sns:us-east1:1111111111:StatusCheckNotifications when instance i-ab12345 fails either the instance check or system status check for at least two periods. (The metric is StatusCheckFailed.) For more information, see the put-metric-alarm command in the AWS Command Line Interface Reference. 1. 2. 3.

At a command prompt, type aws cloudwatch list-metrics to view the list of all available Amazon CloudWatch metrics for the services in AWS that you're using. In the list of metrics, review the Status Check metrics that have the AWS/EC2 namespace. These are the status check metrics that you can use to create a status check alarm. At the command prompt, enter the following command: $ aws cloudwatch put-metric-alarm --alarm-name StatusCheckFailed-Alarm-for-iab12345 --alarm-description "Alarm when StatusCheckFailed metric has a value of one for two periods" --metric-name StatusCheckFailed --namespace AWS/EC2 --statistic Maximum --dimensions Name=InstanceId,Value=i-ab12345 --period 300 --unit Count --evaluation-periods 2 --threshold 1 --comparison-operator GreaterThanThreshold --alarm-actions arn:aws:sns:us-east1:1111111111StatusCheckNotifications

Where: The --alarm-name is the name of the alarm. This is required. The --alarm-description is a friendly description of the alarm. The --metric-name is one of the available status metrics (e.g., StatusCheckFailed, StatusCheckFailed_Instance, or StatusCheckFailed_System). This is required. API Version 2014-10-01 350

Amazon Elastic Compute Cloud User Guide for Linux Monitoring Events for Your Instances

The --namespace is the metric’s namespace (e.g., AWS/EC2). This is required. The --statistic is one of the following values: Average, Sum, Minimum, or Maximum. This is required. The --dimensions are associated with the metric (e.g., InstanceId=i-ab12345). The --period is the time frame (in seconds) in which Amazon CloudWatch metrics are collected. In this example, you would enter 300, which is 60 seconds multiplied by 5 minutes. This is required. The --unit is unit for the alarm's associated metric. The --evaluation-periods is the number of consecutive periods for which the value of the metric must be compared to the threshold. This is required. The --threshold is the value to which the metric will be compared (e.g., 1). This is required. The --alarm-actions is the list of actions to perform when this alarm is triggered. Each action is specified as an Amazon Resource Number (ARN). In this example, we want the alarm to send us an email using Amazon SNS.

Note You can find the ARN for the Amazon SNS topic that the alarm will use in the Amazon SNS console: 1. 2. 3.

Open the Amazon SNS console at https://console.aws.amazon.com/sns/. In the navigation pane, under My Topics, select the topic you want the alarm to send mail to. The ARN is located in the Topic ARN field on the Topic Details pane.

The --unit is the unit of the metric on which to alarm (e.g., Count).

Monitoring Events for Your Instances Instance status describes specific events that AWS may schedule for your instances, such as a reboot or retirement. These scheduled events are not frequent. If one of your instances will be affected by a scheduled event, the email address that's associated with your AWS account receives an email prior to the scheduled event with details about the event, as well as a start and end date. (To update the contact information for your account, go to the Account Settings page.) You can also view scheduled events for your instance by using the Amazon EC2 console, API, or CLI. For more information, see Viewing Scheduled Events (p. 352). There are different types of scheduled events: • Reboot: A reboot can be either an instance reboot or a system reboot. • System maintenance: An instance may be temporarily affected by network maintenance or power maintenance. • Instance retirement: An instance that's scheduled for retirement will be stopped or terminated. • Instance stop: An instance may need to be stopped in order to migrate it to new hardware. If one of your instances is scheduled for any of the above events, you may be able to take actions to control the timing of the event, or to minimize downtime. For more information, see Working with an Instance That Has a Scheduled Event (p. 352). Contents • Viewing Scheduled Events (p. 352)

API Version 2014-10-01 351

Amazon Elastic Compute Cloud User Guide for Linux Monitoring Events for Your Instances

• Working with an Instance That Has a Scheduled Event (p. 352)

Viewing Scheduled Events You can view scheduled events for your instances using the Amazon EC2 console, the command line interface (CLI), or the API.

Amazon EC2 Console To view scheduled events for your instances using the console 1. 2. 3.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. In the navigation pane, click Events. You can see a list of all resources with events associated with them. You can filter by instance or volume, or by specific status types. Alternatively, you can do the following to view upcoming scheduled events: a.

In the navigation pane, click the EC2 Dashboard.

b.

Under Scheduled Events, you can see the events associated with your Amazon EC2 instances and volumes.

Command Line Interface and API To view the status of your instances, use the ec2-describe-instance-status command, or the DescribeInstanceStatus API action.

Working with an Instance That Has a Scheduled Event If your instance has a scheduled event, your course of action will depend on whether your instance’s root device volume is an Amazon EBS volume or an instance store volume.You can determine the root device type for an instance by checking the value of the Root device type field in the details pane on the Instances page.

Instances Scheduled for Reboot AWS may schedule instances for a reboot in order to perform tasks such as applying patches, upgrades, or maintenance to the underlying host. There are two types of reboot events: system reboot and instance reboot. During a system reboot, your instance and the hardware supporting your instance is rebooted. During an instance reboot, your instance is rebooted, but the hardware supporting your instance is not rebooted.You can find out which type of reboot event is scheduled for your instance by using the Amazon EC2 console.

To view the type of scheduled reboot events 1. 2. 3. 4.

Sign in to the AWS Management Console and open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. In the navigation pane, click Events. Select Instance resources from the filter list, and locate your instance. Look under the Event Type column. The column should indicate system-reboot or instancereboot.

Actions Required for System Reboot

API Version 2014-10-01 352

Amazon Elastic Compute Cloud User Guide for Linux Monitoring Events for Your Instances

No action is required on your part if one of your instances is scheduled for a system reboot - you can wait for the reboot to occur automatically within its scheduled maintenance window. However, you can also reboot your instance manually at a time that is convenient for you before the reboot event is scheduled to begin. For more information, see Reboot Your Instance (p. 312). The reboot typically completes in a matter of minutes. After the reboot completes, you can begin using your instance again. It is not necessary to wait until the scheduled end time. To verify that the reboot has occurred, check your scheduled events and verify that the instance no longer shows a scheduled event. We recommend that you check whether the software on your instance is operating as you expect. Actions Required for Instance Reboot No action is required on your part if one of your instances is scheduled for an instance reboot - you can wait for the reboot to occur automatically within its scheduled maintenance window. However, you can also reboot your instance manually at a time that is convenient for you before the reboot event is scheduled to begin. For more information, see Reboot Your Instance (p. 312). After you reboot your instance, the scheduled event for the instance reboot is canceled immediately and the event's description is updated. The pending maintenance to the underlying host is completed, and you can begin using your instance again after it has fully booted.

Instances Scheduled to Be Stopped or Retired An instance is scheduled to be stopped or retired when AWS detects irreparable failure of the underlying hardware hosting your instance. When an instance reaches its scheduled retirement date, it is stopped or terminated by AWS. If your instance's root device is an Amazon EBS volume, the instance is stopped, and you can start it again at any time. If your instance's root device is an instance store volume, the instance is terminated, and cannot be used again. Actions Required for Instances Scheduled to Be Stopped or Retired If your instance's root device is an Amazon EBS volume, you can wait for the instance to be stopped or retired at the scheduled event start time. Alternatively, you can stop and start the instance yourself. Doing so migrates your instance to new hardware and help reduce unforeseen downtime. For more information about stopping your instance, as well as information about changes to your instance configuration when it's stopped, see Stop and Start Your Instance (p. 309). If your instance's root device is an instance store volume, we recommend that you launch a replacement instance from your most recent AMI, and migrate all necessary data to the replacement instance before the scheduled retirement.You can then terminate the instance, or wait for it to be automatically terminated when it's retired. For more information about instances scheduled for retirement and how to manage them, see Instance Retirement (p. 312).

Important Any data stored on instance store volumes is lost when the instance is stopped or terminated, and cannot be recovered. This includes instance store volumes that are attached to an instance that has an Amazon EBS volume as the root device. Before the instance is stopped or terminated, ensure you retrieve any data from the instance store volume that you will need later.

Instances Scheduled for Maintenance Instances are scheduled for maintenance when underlying Amazon EC2 hardware requires maintenance. There are two types of maintenance events: network maintenance and power maintenance. During network maintenance, scheduled instances lose network connectivity for a brief period of time. Normal network connectivity to your instance will be restored after maintenance is complete. During power maintenance, scheduled instances are offline for a brief period, and then rebooted. API Version 2014-10-01 353

Amazon Elastic Compute Cloud User Guide for Linux Monitoring Your Instances with CloudWatch

Actions Required for Instances Scheduled for Maintenance No action is required on your part if one of your instances is scheduled for maintenance. However, if you want to maintain normal operation during this time, you can launch a replacement instance from your most recent AMI, and migrate all necessary data to the replacement instance before the scheduled maintenance. Replacement instances are not affected by the same scheduled network or power maintenance. For power maintenance, when a reboot is performed, all of your instance's configuration settings are retained.

Monitoring Your Instances with CloudWatch You can monitor your Amazon EC2 instances using Amazon CloudWatch, which collects and processes raw data from Amazon EC2 into readable, near real-time metrics. These statistics are recorded for a period of two weeks, so that you can access historical information and gain a better perspective on how your web application or service is performing. By default, Amazon EC2 metric data is automatically sent to CloudWatch in 5-minute periods. You can, however, enable detailed monitoring on an Amazon EC2 instance, which sends data to CloudWatch in 1-minute periods. For more information about Amazon CloudWatch, see the Amazon CloudWatch Developer Guide. The following table describes basic and detailed monitoring for Amazon EC2 instances. Type

Description

Basic

Data is available automatically in 5-minute periods at no charge.

Detailed

Data is available in 1-minute periods at an additional cost. To get this level of data, you must specifically enable it for the instance. For the instances where you've enabled detailed monitoring, you can also get aggregated data across groups of similar instances. For information about pricing, see the Amazon CloudWatch product page.

You can get monitoring data for your Amazon EC2 instances using either the Amazon CloudWatch API or the AWS Management Console. The console displays a series of graphs based on the raw data from the Amazon CloudWatch API. Depending on your needs, you might prefer to use either the data from the API or the graphs in the console. Contents • Enabling or Disabling Detailed Monitoring on an Amazon EC2 Instance (p. 355) • View Amazon EC2 Metrics (p. 358) • Get Statistics for Metrics (p. 364) • Graphing Metrics (p. 380) • Create a CloudWatch Alarm (p. 384) • Create Alarms That Stop or Terminate an Instance (p. 391)

API Version 2014-10-01 354

Amazon Elastic Compute Cloud User Guide for Linux Enabling or Disabling Detailed Monitoring on an Amazon EC2 Instance

Enabling or Disabling Detailed Monitoring on an Amazon EC2 Instance This section describes how to enable or disable detailed monitoring on either a new instance (as you launch it) or on a running or stopped instance. After you enable detailed monitoring, the Amazon EC2 console displays monitoring graphs with a 1-minute period for the instance. You can enable or disable detailed monitoring using the console or the command line interface (CLI).

AWS Management Console To enable detailed monitoring of an existing EC2 instance You can enable detailed monitoring of your EC2 instances, which provides data about your instance in 1-minute periods. (There is an additional charge for 1-minute monitoring.) Detailed data is then available for the instance in the AWS Management Console graphs or through the API. To get this level of data, you must specifically enable it for the instance. For the instances on which you've enabled detailed monitoring, you can also get aggregated data across groups of similar instances. An instance must be running or stopped to enable detailed monitoring. 1. 2. 3. 4. 5.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. In the navigation pane, click Instances. In the list of instances, select a running or stopped instance, click Actions, and then click Enable Detailed Monitoring. In the Enable Detailed Monitoring dialog box, click Yes, Enable. In the Enable Detailed Monitoring confirmation dialog box, click Close. Detailed data (collected with a 1-minute period) is then available for the instance in the AWS Management Console graphs or through the API.

To enable detailed monitoring when launching an EC2 instance When launching an instance with the AWS Management Console, select the Monitoring check box on the Configure Instance Details page of the launch wizard. After the instance is launched, you can select the instance in the console and view its monitoring graphs on the instance's Monitoring tab in the lower pane.

To disable detailed monitoring of an EC2 instance When you no longer want to monitor your instances at 1-minute intervals, you can disable detailed monitoring and use basic monitoring instead. Basic monitoring provides data in 5-minute periods at no charge. 1. 2.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. In the navigation pane, click Instances.

3.

In the list of instances, select a running or stopped instance, click Actions, and then click Disable Detailed Monitoring.

4. 5.

In the Disable Detailed Monitoring dialog box, click Yes, Disable. In the Disable Detailed Monitoring confirmation dialog box, click Close.

For information about launching instances, see Launch Your Instance (p. 289).

API Version 2014-10-01 355

Amazon Elastic Compute Cloud User Guide for Linux Enabling or Disabling Detailed Monitoring on an Amazon EC2 Instance

Command Line Interface To enable detailed monitoring on an existing instance Use the monitor-instances command with one or more instance IDs. For more information about using the monitor-instances command, see monitor-instances in the AWS Command Line Interface Reference. $ aws ec2 monitor-instances --instance-ids i-570e5a28 { "InstanceMonitorings": [ { "InstanceId": "i-570e5a28", "Monitoring": { "State": "pending" } } ] }

Detailed data (collected with a 1-minute period) is then available for the instance in the AWS Management Console graphs or through the API. To enable detailed monitoring when launching an instance Use the run-instances command with the --monitoring flag. For more information about using the run-instances command, see run-instances in the AWS Command Line Interface Reference. $ aws ec2 run-instances --image-id ami-09092360 --key-name MyKeyPair --monitoring Enabled=value

Amazon EC2 returns output similar to the following example. The status of monitoring is listed as pending. { "OwnerId": "111122223333", "ReservationId": "r-25fad905", "Groups": [ { "GroupName": "default", "GroupId": "sg-eafe1b82" } ], "Instances": [ { "Monitoring": { "State": "pending" }, "PublicDnsName": null, "Platform": "windows", "State": { "Code": 0, "Name": "pending" }, "EbsOptimized": false, "LaunchTime": "2014-02-24T18:02:49.000Z", "ProductCodes": [],

API Version 2014-10-01 356

Amazon Elastic Compute Cloud User Guide for Linux Enabling or Disabling Detailed Monitoring on an Amazon EC2 Instance "StateTransitionReason": null, "InstanceId": "i-31283b11", "ImageId": "ami-09092360", "PrivateDnsName": null, "KeyName": "MyKeyPair", "SecurityGroups": [ { "GroupName": "default", "GroupId": "sg-eafe1b82" } ], "ClientToken": null, "InstanceType": "m1.small", "NetworkInterfaces": [], "Placement": { "Tenancy": "default", "GroupName": null, "AvailabilityZone": "us-east-1b" }, "Hypervisor": "xen", "BlockDeviceMappings": [], "Architecture": "x86_64", "StateReason": { "Message": "pending", "Code": "pending" }, "VirtualizationType": "hvm", "RootDeviceType": "instance-store", "AmiLaunchIndex": 0 } ] }

After the instance is running, detailed data (collected with a 1-minute period) is then available for the instance in the AWS Management Console graphs or through the API. To disable detailed monitoring of an instance Use the unmonitor-instances command with one or more instance IDs. For more information about using the unmonitor-instances command, see unmonitor-instances in the AWS Command Line Interface Reference. $ aws ec2 unmonitor-instances --instance-ids i-570e5a28 { "InstanceMonitorings": [ { "InstanceId": "i-570e5a28", "Monitoring": { "State": "disabling" } } ] }

API Version 2014-10-01 357

Amazon Elastic Compute Cloud User Guide for Linux View Amazon EC2 Metrics

View Amazon EC2 Metrics Only those services in AWS that you're using send metrics to Amazon CloudWatch. You can use the Amazon CloudWatch console, the mon-list-metrics command, or the ListMetrics API to view the metrics that Amazon EC2 sends to CloudWatch. If you've enabled detailed monitoring, each data point covers the instance's previous 1 minute of activity. Otherwise, each data point covers the instance's previous 5 minutes of activity. Metric

Description

CPUCreditUsage

(Only valid for T2 instances) The number of CPU credits consumed during the specified period. This metric identifies the amount of time during which physical CPUs were used for processing instructions by virtual CPUs allocated to the instance.

Note CPU Credit metrics are available at a 5 minute frequency. Units: Count CPUCreditBalance

(Only valid for T2 instances) The number of CPU credits that an instance has accumulated. This metric is used to determine how long an instance can burst beyond its baseline performance level at a given rate.

Note CPU Credit metrics are available at a 5 minute frequency. Units: Count CPUUtilization

The percentage of allocated EC2 compute units that are currently in use on the instance. This metric identifies the processing power required to run an application upon a selected instance. Units: Percent

DiskReadOps

Completed read operations from all ephemeral disks available to the instance in a specified period of time. If your instance uses Amazon EBS volumes, see Amazon EBS Metrics (p. 535).

Note To calculate the average I/O operations per second (IOPS) for the period, divide the total operations in the period by the number of seconds in that period. Units: Count DiskWriteOps

Completed write operations to all ephemeral disks available to the instance in a specified period of time. If your instance uses Amazon EBS volumes, see Amazon EBS Metrics (p. 535).

Note To calculate the average I/O operations per second (IOPS) for the period, divide the total operations in the period by the number of seconds in that period. Units: Count

API Version 2014-10-01 358

Amazon Elastic Compute Cloud User Guide for Linux View Amazon EC2 Metrics

Metric

Description

DiskReadBytes

Bytes read from all ephemeral disks available to the instance (if your instance uses Amazon EBS, see Amazon EBS Metrics (p. 535).) This metric is used to determine the volume of the data the application reads from the hard disk of the instance. This can be used to determine the speed of the application. Units: Bytes

DiskWriteBytes

Bytes written to all ephemeral disks available to the instance (if your instance uses Amazon EBS, see Amazon EBS Metrics (p. 535).) This metric is used to determine the volume of the data the application writes onto the hard disk of the instance. This can be used to determine the speed of the application. Units: Bytes

NetworkIn

The number of bytes received on all network interfaces by the instance. This metric identifies the volume of incoming network traffic to an application on a single instance. Units: Bytes

NetworkOut

The number of bytes sent out on all network interfaces by the instance. This metric identifies the volume of outgoing network traffic to an application on a single instance. Units: Bytes

StatusCheckFailed

A combination of StatusCheckFailed_Instance and StatusCheckFailed_System that reports if either of the status checks has failed. Values for this metric are either 0 (zero) or 1 (one.) A zero indicates that the status check passed. A one indicates a status check failure.

Note Status check metrics are available at 1 minute frequency. For a newly launched instance, status check metric data will only be available after the instance has completed the initialization state. Status check metrics will become available within a few minutes of being in the running state. Units: Count StatusCheckFailed_Instance Reports whether the instance has passed the EC2 instance status check in the last minute. Values for this metric are either 0 (zero) or 1 (one.) A zero indicates that the status check passed. A one indicates a status check failure.

Note Status check metrics are available at 1 minute frequency. For a newly launched instance, status check metric data will only be available after the instance has completed the initialization state. Status check metrics will become available within a few minutes of being in the running state. Units: Count

API Version 2014-10-01 359

Amazon Elastic Compute Cloud User Guide for Linux View Amazon EC2 Metrics

Metric

Description

StatusCheckFailed_System Reports whether the instance has passed the EC2 system status check in the last minute. Values for this metric are either 0 (zero) or 1 (one.) A zero indicates that the status check passed. A one indicates a status check failure.

Note Status check metrics are available at 1 minute frequency. For a newly launched instance, status check metric data will only be available after the instance has completed the initialization state. Status check metrics will become available within a few minutes of being in the running state. Units: Count

You can use the dimensions in the following table to refine the metrics returned for your instances. Dimension

Description

AutoScalingGroupName

This dimension filters the data you request for all instances in a specified capacity group. An AutoScalingGroup is a collection of instances you define if you're using the Auto Scaling service. This dimension is available only for EC2 metrics when the instances are in such an AutoScalingGroup. Available for instances with Detailed or Basic Monitoring enabled.

ImageId

This dimension filters the data you request for all instances running this EC2 Amazon Machine Image (AMI). Available for instances with Detailed Monitoring enabled.

InstanceId

This dimension filters the data you request for the identified instance only. This helps you pinpoint an exact instance from which to monitor data. Available for instances with Detailed Monitoring enabled.

InstanceType

This dimension filters the data you request for all instances running with this specified instance type. This helps you categorize your data by the type of instance running. For example, you might compare data from an m1.small instance and an m1.large instance to determine which has the better business value for your application. Available for instances with Detailed Monitoring enabled.

For more information about using the GetMetricStatistics action, see GetMetricStatistics in the Amazon CloudWatch API Reference.

AWS Management Console To view available metrics by category You can view metrics by category. Metrics are grouped first by Namespace, and then by the various Dimension combinations within each Namespace. For example, you can view all EC2 metrics, or EC2 metrics grouped by instance ID, instance type, image (AMI) ID, or Auto Scaling Group. 1. 2.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints.

API Version 2014-10-01 360

Amazon Elastic Compute Cloud User Guide for Linux View Amazon EC2 Metrics

3.

In the navigation pane, click Metrics.

4.

In the CloudWatch Metrics by Category pane, under EC2 Metrics, select Per-Instance Metrics, and then in the upper pane, scroll down to view the full list of metrics.

API Version 2014-10-01 361

Amazon Elastic Compute Cloud User Guide for Linux View Amazon EC2 Metrics

Command Line Interface To list available metrics across multiple Amazon EC2 instances Enter the list-metrics command and specify the AWS/EC2 namespace to limit the results to Amazon EC2. For more information about the list-metrics command, see list-metrics in the AWS Command Line Interface Reference. $ aws cloudwatch list-metrics --namespace AWS/EC2

CloudWatch returns the following (partial listing): { "Namespace": "AWS/EC2", "Dimensions": [ { "Name": "InstanceType", "Value": "t1.micro" } ], "MetricName": "CPUUtilization" }, { "Namespace": "AWS/EC2", "Dimensions": [ { "Name": "InstanceId", "Value": "i-570e5a28" } ], "MetricName": "DiskWriteOps" },

API Version 2014-10-01 362

Amazon Elastic Compute Cloud User Guide for Linux View Amazon EC2 Metrics

{ "Namespace": "AWS/EC2", "Dimensions": [ { "Name": "InstanceType", "Value": "t1.micro" } ], "MetricName": "NetworkOut" }, { "Namespace": "AWS/EC2", "Dimensions": [ { "Name": "ImageId", "Value": "ami-6cb90605" } ], "MetricName": "CPUUtilization" }, { "Namespace": "AWS/EC2", "Dimensions": [ { "Name": "ImageId", "Value": "ami-6cb90605" } ], "MetricName": "NetworkIn" }, { "Namespace": "AWS/EC2", "Dimensions": [ { "Name": "InstanceType", "Value": "t1.micro" } ], "MetricName": "DiskReadBytes" }, { "Namespace": "AWS/EC2", "Dimensions": [ { "Name": "InstanceId", "Value": "i-570e5a28" } ], "MetricName": "StatusCheckFailed_System" }, { "Namespace": "AWS/EC2", "Dimensions": [ { "Name": "InstanceId", "Value": "i-570e5a28" } ],

API Version 2014-10-01 363

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

"MetricName": "NetworkOut" }, { "Namespace": "AWS/EC2", "Dimensions": [ { "Name": "InstanceId", "Value": "i-0c986c72" } ], "MetricName": "DiskWriteBytes" } ] }

Get Statistics for Metrics This set of scenarios shows you how you can use the AWS Management Console, the get-metricstatistics command, or the GetMetricStatistics API to get a variety of statistics.

Note Start and end times must be within the last 14 days. Contents • Get Statistics for a Specific EC2 Instance (p. 364) • Aggregating Statistics Across Instances (p. 368) • Get Statistics Aggregated by Auto Scaling Group (p. 373) • Get Statistics Aggregated by Image (AMI) ID (p. 376)

Get Statistics for a Specific EC2 Instance The following scenario walks you through how to use the AWS Management Console or the get-metricstatistics command to determine the maximum CPU utilization of a specific EC2 instance.

Note Start and end times must be within the last 14 days. For this example, we assume that you have an EC2 instance ID. You can get an active EC2 instance ID through the AWS Management Console or with the describe-instances command.

AWS Management Console To display the average CPU utilization for a specific instance 1. 2.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints.

API Version 2014-10-01 364

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

3. 4.

In the navigation pane, click Metrics. In the CloudWatch Metrics by Category pane, select EC2: Metrics.

5.

The metrics available for individual instances appear in the upper pane. Select a row that contains CPUUtilization for a specific InstanceId. A graph showing average CPUUtilization for a single instance appears in the details pane.

6.

To change the Statistic, e.g., Average, for the metric, choose a different value from the pop-up list.

API Version 2014-10-01 365

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

7.

To change the Period, e.g., 5 Minutes, to view data in more granular detail, choose a different value from the pop-up list.

Command Line Interface To get the CPU utilization per EC2 instance Enter the get-metric-statistics command with the following parameters. For more information about the get-metric-statistics command, see get-metric-statistics in the AWS Command Line Interface Reference. $ aws cloudwatch get-metric-statistics --metric-name CPUUtilization --starttime 2014-02-18T23:18:00 --end-time 2014-02-19T23:18:00 --period 3600 --namespace AWS/EC2 --statistics Maximum --dimensions Name=InstanceId,Value=

The AWS CLI returns the following: { "Datapoints": [ { "Timestamp": "2014-02-19T00:18:00Z", "Maximum": 0.33000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T03:18:00Z", "Maximum": 99.670000000000002, "Unit": "Percent"

API Version 2014-10-01 366

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

}, { "Timestamp": "2014-02-19T07:18:00Z", "Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T12:18:00Z", "Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T02:18:00Z", "Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T01:18:00Z", "Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T17:18:00Z", "Maximum": 3.3900000000000001, "Unit": "Percent" }, { "Timestamp": "2014-02-19T13:18:00Z", "Maximum": 0.33000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-18T23:18:00Z", "Maximum": 0.67000000000000004, "Unit": "Percent" }, { "Timestamp": "2014-02-19T06:18:00Z", "Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T11:18:00Z", "Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T10:18:00Z", "Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T19:18:00Z", "Maximum": 8.0, "Unit": "Percent" }, { "Timestamp": "2014-02-19T15:18:00Z",

API Version 2014-10-01 367

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

"Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T14:18:00Z", "Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T16:18:00Z", "Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T09:18:00Z", "Maximum": 0.34000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T04:18:00Z", "Maximum": 2.0, "Unit": "Percent" }, { "Timestamp": "2014-02-19T08:18:00Z", "Maximum": 0.68000000000000005, "Unit": "Percent" }, { "Timestamp": "2014-02-19T05:18:00Z", "Maximum": 0.33000000000000002, "Unit": "Percent" }, { "Timestamp": "2014-02-19T18:18:00Z", "Maximum": 6.6699999999999999, "Unit": "Percent" } ], "Label": "CPUUtilization" }

The returned statistics are six-minute values for the requested two-day time interval. Each value represents the maximum CPU utilization percentage for a single EC2 instance.

Aggregating Statistics Across Instances Aggregate statistics are available for the instances that have detailed monitoring enabled. Instances that use basic monitoring are not included in the aggregates. In addition, Amazon CloudWatch does not aggregate data across Regions. Therefore, metrics are completely separate between Regions. Before you can get statistics aggregated across instances, you must enable detailed monitoring (at an additional charge), which provides data in 1-minute periods.This scenario shows you how to use detailed monitoring with either the AWS Management Console, the GetMetricStatistics API, or the get-metricstatistics command to get the average CPU usage for your EC2 instances. Because no dimension is specified, CloudWatch returns statistics for all dimensions in the AWS/EC2 namespace. To get statistics for other metrics, see Amazon CloudWatch Namespaces, Dimensions, and Metrics Reference.

API Version 2014-10-01 368

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

Important This technique for retrieving all dimensions across an AWS namespace does not work for custom namespaces that you publish to Amazon CloudWatch. With custom namespaces, you must specify the complete set of dimensions that are associated with any given data point to retrieve statistics that include the data point.

AWS Management Console To display average CPU utilization for your Amazon EC2 instances 1. 2.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints.

3. 4.

In the navigation pane, click Metrics. In the CloudWatch Metrics by Category pane, under EC2 Metrics, select Across All Instances.

5.

The metrics available across all instances are displayed in the upper pane. In the upper pane, select the row that contains CPUUtilization. A graph showing CPUUtilization for your EC2 instances is displayed in the details pane.

API Version 2014-10-01 369

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

6.

To change the Statistic, e.g., Average, for the metric, choose a different value from the pop-up list.

7.

To change the Period, e.g., 5 Minutes, to view data in more granular detail, choose a different value from the pop-up list.

API Version 2014-10-01 370

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

Command Line Interface To get average CPU utilization across your Amazon EC2 instances Enter the get-metric-statistics command with the following parameters. For more information about the get-metric-statistics command, see get-metric-statistics in the AWS Command Line Interface Reference. $ aws cloudwatch get-metric-statistics --metric-name CPUUtilization --starttime 2014-02-11T23:18:00 --end-time 2014-02-12T23:18:00 --period 3600 --namespace AWS/EC2 --statistics "Average" "SampleCount"

The AWS CLI returns the following: { "Datapoints": [ { "SampleCount": 238.0, "Timestamp": "2014-02-12T07:18:00Z", "Average": 0.038235294117647062, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T09:18:00Z", "Average": 0.16670833333333332, "Unit": "Percent" }, { "SampleCount": 238.0, "Timestamp": "2014-02-11T23:18:00Z", "Average": 0.041596638655462197, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T16:18:00Z", "Average": 0.039458333333333345, "Unit": "Percent" }, { "SampleCount": 239.0, "Timestamp": "2014-02-12T21:18:00Z", "Average": 0.041255230125523033, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T01:18:00Z", "Average": 0.044583333333333336, "Unit": "Percent" }, { "SampleCount": 239.0, "Timestamp": "2014-02-12T18:18:00Z", "Average": 0.043054393305439344, "Unit": "Percent"

API Version 2014-10-01 371

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

}, { "SampleCount": 240.0, "Timestamp": "2014-02-12T13:18:00Z", "Average": 0.039458333333333345, "Unit": "Percent" }, { "SampleCount": 238.0, "Timestamp": "2014-02-12T15:18:00Z", "Average": 0.041260504201680689, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T19:18:00Z", "Average": 0.037666666666666668, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T06:18:00Z", "Average": 0.037541666666666675, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T20:18:00Z", "Average": 0.039333333333333338, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T08:18:00Z", "Average": 0.039250000000000014, "Unit": "Percent" }, { "SampleCount": 239.0, "Timestamp": "2014-02-12T03:18:00Z", "Average": 0.037740585774058588, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T11:18:00Z", "Average": 0.039500000000000007, "Unit": "Percent" }, { "SampleCount": 238.0, "Timestamp": "2014-02-12T02:18:00Z", "Average": 0.039789915966386563, "Unit": "Percent" }, { "SampleCount": 238.0, "Timestamp": "2014-02-12T22:18:00Z",

API Version 2014-10-01 372

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

"Average": 0.039705882352941181, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T14:18:00Z", "Average": 0.082458333333333328, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T05:18:00Z", "Average": 0.04287500000000001, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T17:18:00Z", "Average": 0.039458333333333345, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T10:18:00Z", "Average": 0.083416666666666667, "Unit": "Percent" }, { "SampleCount": 236.0, "Timestamp": "2014-02-12T00:18:00Z", "Average": 0.036567796610169498, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T12:18:00Z", "Average": 0.039541666666666676, "Unit": "Percent" }, { "SampleCount": 240.0, "Timestamp": "2014-02-12T04:18:00Z", "Average": 0.043000000000000003, "Unit": "Percent" } ], "Label": "CPUUtilization" }

Get Statistics Aggregated by Auto Scaling Group This scenario shows you how to use the AWS Management Console, the get-metric-statistics command, or the GetMetricStatistics API with the DiskWriteBytes metric to retrieve the total bytes written to disk for one Auto Scaling group. The total is computed for one-minute periods for a 24-hour interval across all EC2 instances in the specified AutoScalingGroupName.

Note Start and end times must be within the last 14 days. API Version 2014-10-01 373

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

We assume for this example that an EC2 application is running and has an Auto Scaling group named test-group-1.

AWS Management Console To display total DiskWriteBytes for an Auto-Scaled EC2 application 1. 2.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints.

3. 4.

In the navigation pane, click Metrics. In the CloudWatch Metrics by Category pane, under EC2 Metrics, select By Auto Scaling Group.

5.

The metrics available for Auto Scaling groups are displayed in the upper pane. Select the row that contains DiskWriteBytes. A graph showing DiskWriteBytes for all EC2 instances appears in the details pane.

API Version 2014-10-01 374

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

6.

To change the Statistic, e.g., Average, for the metric, choose a different value from the pop-up list.

7.

To change the Period, e.g., 5 Minutes, to view data in more granular detail, choose a different value from the pop-up list.

Command Line Interface To get total DiskWriteBytes for an auto-scaled EC2 application Enter the get-metric-statistics command with the following parameters. For more information about the get-metric-statistics command, see get-metric-statistics in the AWS Command Line Interface Reference. $ aws cloudwatch get-metric-statistics --metric-name DiskWriteBytes --starttime 2014-02-16T23:18:00 --end-time 2014-02-18T23:18:00 --period 360 --namespace AWS/EC2 --statistics "Sum" "SampleCount" --dimensions Name=AutoScalingGroup Name,Value=test-group-1

The AWS CLI returns the following: { "Datapoints": [ { "SampleCount": 18.0, "Timestamp": "2014-02-19T21:36:00Z", "Sum": 0.0, "Unit": "Bytes" }, { "SampleCount": 5.0,

API Version 2014-10-01 375

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

"Timestamp": "2014-02-19T21:42:00Z", "Sum": 0.0, "Unit": "Bytes" } ], "Label": "DiskWriteBytes" }

Get Statistics Aggregated by Image (AMI) ID This scenario shows you how to use the AWS Management Console, the get-metric-statistics command, or the GetMetricStatistics API to determine average CPU utilization for all instances that match a given image ID. The average is over 60-second time intervals for a one-day period.

Note Start and end times must be within the last 14 days. In this scenario, the EC2 instances are running an image ID of ami-c5e40dac.

AWS Management Console To display the average CPU utilization for an image ID 1. 2.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints.

3. 4.

In the navigation pane, click Metrics. In the CloudWatch Metrics by Category pane, under EC2 Metrics, select By Image (AMI) Id. The metrics available for image IDs appear in the upper pane.

5.

Select a row that contains CPUUtilization and an image ID. A graph showing average CPUUtilization for all EC2 instances based on the ami-c5e40dac image ID appears in the details pane.

API Version 2014-10-01 376

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

6.

To change the Statistic, e.g., Average, for the metric, choose a different value from the pop-up list.

7.

To change the Period, e.g., 5 Minutes, to view data in more granular detail, choose a different value from the pop-up list.

Command Line Interface To get the average CPU utilization for an image ID API Version 2014-10-01 377

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

Enter the get-metric-statistics command as in the following example. For more information about the get-metric-statistics command, see get-metric-statistics in the AWS Command Line Interface Reference. $ aws cloudwatch get-metric-statistics --metric-name CPUUtilization --starttime 2014-02-10T00:00:00 --end-time 2014-02-11T00:00:00 --period 3600 --statist ics Average --namespace AWS/EC2 --dimensions Name="ImageId",Value=ami-3c47a355"

The AWS CLI returns the following: { "Datapoints": [ { "Timestamp": "2014-02-10T07:00:00Z", "Average": 0.041000000000000009, "Unit": "Percent" }, { "Timestamp": "2014-02-10T14:00:00Z", "Average": 0.079579831932773085, "Unit": "Percent" }, { "Timestamp": "2014-02-10T06:00:00Z", "Average": 0.036000000000000011, "Unit": "Percent" }, { "Timestamp": "2014-02-10T13:00:00Z", "Average": 0.037625000000000013, "Unit": "Percent" }, { "Timestamp": "2014-02-10T18:00:00Z", "Average": 0.042750000000000003, "Unit": "Percent" }, { "Timestamp": "2014-02-10T21:00:00Z", "Average": 0.039705882352941188, "Unit": "Percent" }, { "Timestamp": "2014-02-10T20:00:00Z", "Average": 0.039375000000000007, "Unit": "Percent" }, { "Timestamp": "2014-02-10T02:00:00Z", "Average": 0.041041666666666671, "Unit": "Percent" }, { "Timestamp": "2014-02-10T01:00:00Z", "Average": 0.041083333333333354, "Unit": "Percent" },

API Version 2014-10-01 378

Amazon Elastic Compute Cloud User Guide for Linux Get Statistics for Metrics

{ "Timestamp": "2014-02-10T23:00:00Z", "Average": 0.038016877637130804, "Unit": "Percent" }, { "Timestamp": "2014-02-10T15:00:00Z", "Average": 0.037666666666666668, "Unit": "Percent" }, { "Timestamp": "2014-02-10T12:00:00Z", "Average": 0.039291666666666676, "Unit": "Percent" }, { "Timestamp": "2014-02-10T03:00:00Z", "Average": 0.036000000000000004, "Unit": "Percent" }, { "Timestamp": "2014-02-10T04:00:00Z", "Average": 0.042666666666666672, "Unit": "Percent" }, { "Timestamp": "2014-02-10T19:00:00Z", "Average": 0.038305084745762719, "Unit": "Percent" }, { "Timestamp": "2014-02-10T22:00:00Z", "Average": 0.039291666666666676, "Unit": "Percent" }, { "Timestamp": "2014-02-10T09:00:00Z", "Average": 0.17126050420168065, "Unit": "Percent" }, { "Timestamp": "2014-02-10T08:00:00Z", "Average": 0.041166666666666678, "Unit": "Percent" }, { "Timestamp": "2014-02-10T11:00:00Z", "Average": 0.082374999999999962, "Unit": "Percent" }, { "Timestamp": "2014-02-10T17:00:00Z", "Average": 0.037625000000000013, "Unit": "Percent" }, { "Timestamp": "2014-02-10T10:00:00Z", "Average": 0.039458333333333345,

API Version 2014-10-01 379

Amazon Elastic Compute Cloud User Guide for Linux Graphing Metrics

"Unit": "Percent" }, { "Timestamp": "2014-02-10T05:00:00Z", "Average": 0.039250000000000007, "Unit": "Percent" }, { "Timestamp": "2014-02-10T00:00:00Z", "Average": 0.037625000000000013, "Unit": "Percent" }, { "Timestamp": "2014-02-10T16:00:00Z", "Average": 0.041512605042016815, "Unit": "Percent" } ], "Label": "CPUUtilization" }

The operation returns statistics that are one-minute values for the one-day interval. Each value represents an average CPU utilization percentage for EC2 instances running the specified machine image.

Graphing Metrics After you launch an instance, you can go to the Amazon EC2 console and view the instance's monitoring graphs. They're displayed when you select the instance on the Instances page in the EC2 Dashboard. A Monitoring tab is displayed next to the instance's Description tab. The following graphs are available: • • • • • • • •

Average CPU Utilization (Percent) Average Disk Reads (Bytes) Average Disk Writes (Bytes) Maximum Network In (Bytes) Maximum Network Out (Bytes) Summary Disk Read Operations (Count) Summary Disk Write Operations (Count) Summary Status (Any)

• Summary Status Instance (Count) • Summary Status System (Count) You can also use the CloudWatch console to graph metric data generated by Amazon EC2 and other AWS services to make it easier to see what's going on. You can use the following procedures to graph metrics in CloudWatch. Contents • Graph a Metric (p. 381) • Graph a Metric Across Resources (p. 382)

API Version 2014-10-01 380

Amazon Elastic Compute Cloud User Guide for Linux Graphing Metrics

Graph a Metric You can select a metric and create a graph of the data in CloudWatch. For example, you can select the CPUUtilization metric for an Amazon EC2 instance and display a graph of CPU usage over time for that instance.

To graph a metric 1. 2.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints in the Amazon Web Services General Reference.

3. 4.

In the navigation pane, click Metrics. In the CloudWatch Metrics by Category pane, use the Search Metrics box and categories to find a metric by metric name, AWS resource, or other metadata. Use the scroll bar and next and previous arrows above the metrics list to page through the full list of metrics Select the metric to view, for example, CPUUtilization. A graph appears in the details pane.

5. 6.

API Version 2014-10-01 381

Amazon Elastic Compute Cloud User Guide for Linux Graphing Metrics

7.

To save this graph and access it later, in the details pane, under Tools, click Copy URL, and then in the Copy Graph URL dialog box, select the URL and paste it into your browser.

Graph a Metric Across Resources You can graph a metric across all resources to see everything on one graph. For example, you can graph the CPUUtilization metric for all Amazon EC2 instances on one graph.

To graph a metric across resources 1. 2.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints.

3.

In the navigation pane, click Metrics.

4.

In the CloudWatch Metrics by Category pane, select a metric category. For example, under EC2 Metrics, select Per-Instance Metrics.

API Version 2014-10-01 382

Amazon Elastic Compute Cloud User Guide for Linux Graphing Metrics

5. 6.

In the metric list, in the Metric Name column, click a metric. For example CPUUtilization. At the top of the metric list, click Select All. The graph shows all data for all occurrences of the selected metric. In the example below, CPUUtilization for all Amazon EC2 instances is shown.

7.

To save this graph and access it later, in the details pane, under Tools, click Copy URL, and then in the Copy Graph URL dialog box, select the URL and paste it into your browser.

API Version 2014-10-01 383

Amazon Elastic Compute Cloud User Guide for Linux Create a CloudWatch Alarm

Create a CloudWatch Alarm You can create an Amazon CloudWatch alarm that monitors any one of your Amazon EC2 instance's CloudWatch metrics. CloudWatch will automatically send you a notification when the metric reaches a threshold you specify. You can create a CloudWatch alarm on the Amazon EC2 console of the AWS Management Console, or you can use the CloudWatch console and configure more advanced options. Contents • Send Email Based on CPU Usage Alarm (p. 384) • Send Email Based on Load Balancer Alarm (p. 386) • Send Email Based on Storage Throughput Alarm (p. 388)

Send Email Based on CPU Usage Alarm This scenario walks you through how to use the AWS Management Console or the command line interface to create an Amazon CloudWatch alarm that sends an Amazon Simple Notification Service email message when the alarm changes state from OK to ALARM. In this scenario, you configure the alarm to change to the ALARM state when the average CPU use of an EC2 instance exceeds 70 percent for two consecutive five-minute periods.

AWS Management Console To create an alarm that sends email based on CPU usage 1. 2.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints.

3. 4.

In the navigation pane, click Alarms. Click Create Alarm, and then in CloudWatch Metrics by Category, select a metric category, for example, EC2 Metrics. In the list of metrics, select a row that contains CPUUtilization for a specific instance ID.

5.

A graph showing average CPUUtilization for a single instance appears in the lower pane.

API Version 2014-10-01 384

Amazon Elastic Compute Cloud User Guide for Linux Create a CloudWatch Alarm

6. 7.

Select Average from the Statistic drop-down list. Select a period from the Period drop-down list, for example: 5 minutes.

8.

Click Next, and then under Alarm Threshold, in the Name field, enter a unique name for the alarm, for example: myHighCpuAlarm.

9.

In the Description field, enter a description of the alarm, for example: CPU usage exceeds 70 percent.

10. In the is drop-down list, select >. 11. In the box next to the is drop-down list, enter 70 and in the for field, enter 10. A graphical representation of the threshold is shown under Alarm Preview. 12. Under Actions, in the Whenever this alarm drop-down list, select State is ALARM. 13. In the Send notification to drop-down list, select an existing Amazon SNS topic or create a new one. 14. To create a new Amazon SNS topic, select New list. In the Send notification to field, enter a name for the new Amazon SNS topic for example: myHighCpuAlarm, and in the Email list field, enter a comma-separated list of email addresses to be notified when the alarm changes to the ALARM state. 15. Click Create Alarm to complete the alarm creation process.

API Version 2014-10-01 385

Amazon Elastic Compute Cloud User Guide for Linux Create a CloudWatch Alarm

Command Line Interface To send an Amazon Simple Notification Service email message when CPU utilization exceeds 70 percent 1.

Set up an Amazon Simple Notification Service topic or retrieve the Topic Resource Name of the topic you intend to use. For help on setting up an Amazon Simple Notification Service topic, see Set Up Amazon Simple Notification Service.

2.

Create an alarm with the put-metric-alarm command. For more information about the putmetric-alarm command, see put-metric-alarm in the AWS Command Line Interface Reference. Use the values from the following example, but replace the values for InstanceID and alarm-actions with your own values. $ aws cloudwatch put-metric-alarm --alarm-name cpu-mon --alarm-description "Alarm when CPU exceeds 70%" --metric-name CPUUtilization --namespace AWS/EC2 --statistic Average --period 300 --threshold 70 --comparison-operator GreaterThanThreshold -dimensions Name=InstanceId,Value=i-12345678 --evaluation-periods 2 --alarmactions arn:aws:sns:us-east-1:111122223333:MyTopic --unit Percent

3.

The AWS CLI returns to the command prompt if the command succeeds. Test the alarm by forcing an alarm state change with the set-alarm-state command. a.

Change the alarm state from INSUFFICIENT_DATA to OK: $ aws cloudwatch set-alarm-state "initializing" --state-value OK

b.

--alarm-name cpu-mon --state-reason

The AWS CLI returns to the command prompt if the command succeeds. Change the alarm state from OK to ALARM: $ aws cloudwatch set-alarm-state --alarm-name cpu-mon --state-reason "initializing" --state-value ALARM

c.

The AWS CLI returns to the command prompt if the command succeeds. Check that an email has been received.

Send Email Based on Load Balancer Alarm This scenario walks you through how to use the AWS Management Console or the command line interface to set up an Amazon Simple Notification Service notification and configure an alarm that monitors load balancer latency exceeding 100 ms.

AWS Management Console To create a load balancer alarm that sends email 1. 2.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints.

API Version 2014-10-01 386

Amazon Elastic Compute Cloud User Guide for Linux Create a CloudWatch Alarm

3. 4.

In the navigation pane, click Alarms. Click Create Alarm, and then in the CloudWatch Metrics by Category pane, select a metric category, for example, ELB Metrics.

5.

In the list of metrics, select a row that contains Latency for a specific load balancer. A graph showing average Latency for a single load balancer appears in the lower pane.

6.

Select Average from the Statistic drop-down list.

7. 8.

Select 1 Minute from the Period drop-down list. Click Next, and then under Alarm Threshold, in the Name field, enter a unique name for the alarm, for example: myHighCpuAlarm.

9.

In the Description field, enter a description of the alarm, for example: Alarm when Latency exceeds 100ms. API Version 2014-10-01 387

Amazon Elastic Compute Cloud User Guide for Linux Create a CloudWatch Alarm

10. In the is drop-down list, select >. 11. In the box next to the is drop-down list, enter 0.1 and in the for field, enter 3. A graphical representation of the threshold is shown under Alarm Preview. 12. Under Actions, in the Whenever this alarm drop-down list, select State is ALARM. 13. In the Send notification to drop-down list, select an existing Amazon SNS topic or create a new one. 14. To create a new Amazon SNS topic, select New list. In the Send notification to field, enter a name for the new Amazon SNS topic for example: myHighCpuAlarm, and in the Email list field, enter a comma-separated list of email addresses to be notified when the alarm changes to the ALARM state. 15. Click Create Alarm to complete the alarm creation process.

Command Line Interface To send an Amazon Simple Notification Service email message when LoadBalancer Latency Exceeds 100 milliseconds 1. 2.

Create an Amazon Simple Notification Service topic. See instructions for creating an Amazon SNS topic in Set Up Amazon Simple Notification Service. Use the put-metric-alarm command to create an alarm. For more information about the putmetric-alarm command, see put-metric-alarm in the AWS Command Line Interface Reference. $ aws cloudwatch put-metric-alarm --alarm-name lb-mon --alarm-description "Alarm when Latency exceeds 100ms" --metric-name Latency --namespace AWS/ELB --statistic Average --period 60 --threshold 100 --comparison-operator GreaterThanThreshold --dimensions Name=LoadBalancerName,Value=my-server -evaluation-periods 3 --alarm-actions arn:aws:sns:us-east-1:1234567890:mytopic --unit Milliseconds

3.

The AWS CLI returns to the command prompt if the command succeeds. Test the alarm. • Force an alarm state change to ALARM: $ aws cloudwatch set-alarm-state --alarm-name lb-mon --state-reason "ini tializing" --state OK $ aws cloudwatch set-alarm-state --alarm-name lb-mon --state-reason "ini tializing" --state ALARM

The AWS CLI returns to the command prompt if the command succeeds. • Check that an email has been received.

Send Email Based on Storage Throughput Alarm This scenario walks you through how to use the AWS Management Console or the command line interface to set up an Amazon Simple Notification Service notification and to configure an alarm that sends email when EBS exceeds 100 MB throughput.

API Version 2014-10-01 388

Amazon Elastic Compute Cloud User Guide for Linux Create a CloudWatch Alarm

AWS Management Console To create a storage throughput alarm that sends email 1. 2.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints.

3. 4.

In the navigation pane, click Alarms. Click Create Alarm, and then in the CloudWatch Metrics by Category pane, select a metric category, for example, EBS Metrics. In the list of metrics, select a row that contains VolumeWriteBytes for a specific VolumeId.

5.

A graph showing average VolumeWriteBytes for a single volume appears in the lower pane.

API Version 2014-10-01 389

Amazon Elastic Compute Cloud User Guide for Linux Create a CloudWatch Alarm

6. 7.

Select Average from the Statistic drop-down list. Select 5 Minutes from the Period drop-down list.

8.

Click Next, and then under Alarm Threshold, in the Name field, enter a unique name for the alarm, for example: myHighWriteAlarm.

9.

In the Description field, enter a description of the alarm, for example: VolumeWriteBytes exceeds 100,000 KiB/s.

10. In the is drop-down list, select >. 11. In the box next to the is drop-down list, enter 100000 and in the for field, enter 15. A graphical representation of the threshold is shown under Alarm Preview. 12. Under Actions, in the Whenever this alarm drop-down list, select State is ALARM. 13. In the Send notification to drop-down list, select an existing Amazon SNS topic or create a new one. 14. To create a new Amazon SNS topic, select New list. In the Send notification to field, enter a name for the new Amazon SNS topic for example: myHighCpuAlarm, and in the Email list field, enter a comma-separated list of email addresses to be notified when the alarm changes to the ALARM state. 15. Click Create Alarm to complete the alarm creation process.

Command Line Interface To send an Amazon Simple Notification Service email message when EBS exceeds 100 MB throughput 1. 2.

Create an Amazon Simple Notification Service topic. See instructions for creating an Amazon SNS topic in Set Up Amazon Simple Notification Service. Use the put-metric-alarm command to create an alarm. For more information about the putmetric-alarm command, see put-metric-alarm in the AWS Command Line Interface Reference. $ aws cloudwatch put-metric-alarm --alarm-name ebs-mon --alarm-description "Alarm when EBS volume exceeds 100MB throughput" --metric-name VolumeRead Bytes --namespace AWS/EBS --statistic Average --period 300 --threshold 100000000 --comparison-operator GreaterThanThreshold --dimensions Name=VolumeId,Value=my-volume-id --evaluation-periods 3 --alarm-actions arn:aws:sns:us-east-1:1234567890:my-alarm-topic --insufficient-data-actions arn:aws:sns:us-east-1:1234567890:my-insufficient-data-topic

3.

The AWS CLI returns to the command prompt if the command succeeds. Test the alarm. • Force an alarm state change to ALARM. $ aws cloudwatch set-alarm-state --alarm-name lb-mon --state-reason "ini tializing" --state-value OK $ aws cloudwatch set-alarm-state --alarm-name lb-mon --state-reason "ini tializing" --state-value ALARM $ aws cloudwatch set-alarm-state --alarm-name lb-mon --state-reason "ini tializing" --state-value INSUFFICIENT_DATA

• Check that two emails have been received.

API Version 2014-10-01 390

Amazon Elastic Compute Cloud User Guide for Linux Create Alarms That Stop or Terminate an Instance

Create Alarms That Stop or Terminate an Instance Using Amazon CloudWatch alarm actions, you can create alarms that automatically stop or terminate your Amazon Elastic Compute Cloud (Amazon EC2) instances when you no longer need them to be running. For example, you might have instances dedicated to batch payroll processing jobs or scientific computing tasks that run for a period of time and then complete their work. Rather than leave those instances sitting idle (and accruing charges), you can stop or terminate them which can help you to save money. The main difference between using the stop and the terminate alarm actions is that you can easily restart a stopped instance if you need to run it again later, and you can keep the same instance ID and root volume. However, you cannot restart a terminated instance. Instead, you must launch a new instance. You can add the stop or terminate alarm actions to any alarm that is set on an Amazon EC2 instance metric, including basic and detailed monitoring metrics provided by Amazon CloudWatch (in the AWS/EC2 namespace), as well as any custom metrics that include the “InstanceId=” dimension, as long as the InstanceId value refers to a valid running Amazon EC2 instance. Contents • Adding Actions to Amazon CloudWatch Alarms (p. 391) • Amazon CloudWatch Alarm Action Scenarios (p. 400)

Adding Actions to Amazon CloudWatch Alarms You can configure alarm actions using either the Amazon EC2 console or the Amazon CloudWatch console, or you can use the Amazon CloudWatch command line interface (CLI), API, or the AWS SDKs. For information about using the Amazon CloudWatch API with the AWS SDKs, see Sample Code & Libraries.

Using the Amazon EC2 Console to Create an Alarm to Stop an Instance You can create an alarm that stops an Amazon EC2 instance when a certain threshold has been met. For example, you may run development or test instances and occasionally forget to shut them off. You can create an alarm that is triggered when the average CPU utilization percentage has been lower than 10 percent for 24 hours, signaling that it is idle and no longer in use.You can adjust the threshold, duration, and period to suit your needs, plus you can add an Amazon Simple Notification Service (Amazon SNS) notification, so that you will receive an email when the alarm is triggered. Amazon EC2 instances that use an Amazon Elastic Block Store volume as the root device can be stopped or terminated, whereas instances that use the instance store as the root device can only be terminated.

Note If you are using an AWS Identity and Access Management (IAM) account to create or modify an alarm, you must have the following Amazon EC2 permissions: ec2:DescribeInstanceStatus, ec2:DescribeInstances, ec2:StopInstances, and ec2:TerminateInstances in order for the alarm action to be performed. If you have read/write permissions for Amazon CloudWatch but not for Amazon EC2, you can still create an alarm but the stop or terminate actions won’t be performed on the Amazon EC2 instance. However, if you are later granted permission to use the associated Amazon EC2 APIs, the alarm actions you created earlier will be performed. For more information about IAM permissions, see Permissions and Policies in Using IAM. If you are using an IAM role (e.g. Amazon EC2 instance profile), you cannot stop or terminate the instance using alarm actions. However, you can still see the alarm state and perform any other actions such as Amazon SNS notifications or Auto Scaling policies. If you are using temporary security credentials granted using the AWS Security Token Service (AWS STS), you cannot stop or terminate an Amazon EC2 instance using alarm actions.

API Version 2014-10-01 391

Amazon Elastic Compute Cloud User Guide for Linux Create Alarms That Stop or Terminate an Instance

To create an alarm to stop an idle instance 1.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

2. 3. 4.

If necessary, change the region. From the navigation bar, select the region where your instance is running. For more information, see Regions and Endpoints. In the navigation pane, under INSTANCES, click Instances. In the upper pane, right-click an instance, and then click Add/Edit Alarms.

5.

Or, you can also select the instance, and then in the lower pane on the Monitoring tab, click Create Alarm. In the Alarm Details for dialog box, click Create Alarm.

6.

If you want to receive an email when the alarm is triggered, in the Create Alarm for dialog box, in the Send a notification to box, select an existing Amazon SNS topic, or click Create Topic to create a new one. If you create a new topic, in the Send a notification to box type a name for the topic, and then in the With these recipients box, type the email addresses of the recipients (separated by commas). Later, after you create the alarm, you will receive a subscription confirmation email that you must accept before you will get email for this topic.

7.

Select the Take the action check box, and then choose the Stop radio button.

API Version 2014-10-01 392

Amazon Elastic Compute Cloud User Guide for Linux Create Alarms That Stop or Terminate an Instance

8.

In the Whenever boxes, choose the statistic you want to use and then select the metric. In this example, choose Average and CPU Utilization. 9. In the Is boxes, define the metric threshold. In this example, enter 10 percent. 10. In the For at least box, choose the sampling period for the alarm. In this example, enter 24 consecutive periods of one hour. 11. To change the name of the alarm, in the Name this alarm box, type a new name. If you don't type a name for the alarm, Amazon CloudWatch automatically creates one for you.

Note You can adjust the alarm configuration based on your own requirements before creating the alarm, or you can edit them later. This includes the metric, threshold, duration, action, and notification settings. However, after you create an alarm, you cannot edit its name later. 12. Click Create Alarm.

Using the Amazon EC2 Console to Create an Alarm that Terminates an Instance You can create an alarm that terminates an EC2 instance automatically when a certain threshold has been met (as long as termination protection is not enabled for the instance). For example, you might want to terminate an instance when it has completed its work, and you don’t need the instance again. If you might want to use the instance later, you should stop the instance instead of terminating it. For information about enabling and disabling termination protection for an instance, see Enabling Termination Protection for an Instance (p. 316).

Note If you are using an AWS Identity and Access Management (IAM) account to create or modify an alarm, you must have the following Amazon EC2 permissions: ec2:DescribeInstanceStatus, ec2:DescribeInstances, ec2:StopInstances, and ec2:TerminateInstances in order for the alarm action to be performed. If you have read/write permissions for Amazon CloudWatch but not for Amazon EC2, you can still create an alarm but the stop or terminate actions won’t be performed on the Amazon EC2 instance. However, if you are later granted permission to use the associated Amazon EC2 APIs, the alarm actions you created earlier will be performed. For more information about IAM permissions, see Permissions and Policies in Using IAM. If you are using an IAM role (e.g. Amazon EC2 instance profile), you cannot stop or terminate the instance using alarm actions. However, you can still see the alarm state and perform any other actions such as Amazon SNS notifications or Auto Scaling policies. If you are using temporary security credentials granted using the AWS Security Token Service (AWS STS), you cannot stop or terminate an Amazon EC2 instance using alarm actions.

To create an alarm to terminate an idle instance 1. 2. 3.

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. If necessary, change the region. From the navigation bar, select the region where your instance is running. For more information, see Regions and Endpoints. In the navigation pane, under INSTANCES, click Instances.

4.

In the upper pane, right-click an instance, and then click Add/Edit Alarms.

5.

Or, select the instance and then in the lower pane, on the Monitoring tab, click Create Alarm. In the Alarm Details for dialog box, click Create Alarm.

API Version 2014-10-01 393

Amazon Elastic Compute Cloud User Guide for Linux Create Alarms That Stop or Terminate an Instance

6.

If you want to receive an email when the alarm is triggered, in the Create Alarm for dialog box, in the Send a notification to box, select an existing SNS topic, or click Create Topic to create a new one. If you create a new topic, in the Send a notification to box type a name for the topic, and then in the With these recipients box, type the email addresses of the recipients (separated by commas). Later, after you create the alarm, you will receive a subscription confirmation email that you must accept before you will get email for this topic.

7.

Select the Take the action check box, and then choose the Terminate radio button.

8.

In the Whenever boxes, choose the statistic you want to use and then select the metric. In this example, choose Average and CPU Utilization. 9. In the Is boxes, define the metric threshold. In this example, enter 10 percent. 10. In the For at least box, choose the sampling period for the alarm. In this example, enter 24 consecutive periods of one hour. 11. To change the name of the alarm, in the Name this alarm box, type a new name. If you don't type a name for the alarm, Amazon CloudWatch automatically creates one for you.

Note You can adjust the alarm configuration based on your own requirements before creating the alarm, or you can edit them later. This includes the metric, threshold, duration, action, and notification settings. However, after you create an alarm, you cannot edit its name later. API Version 2014-10-01 394

Amazon Elastic Compute Cloud User Guide for Linux Create Alarms That Stop or Terminate an Instance

12. Click Create Alarm.

Using the Amazon CloudWatch Console to Create an Alarm that Stops an Instance You can create an alarm that stops an Amazon EC2 instance when a certain threshold has been met. For example, you may run development or test instances and occasionally forget to shut them off. You can create an alarm that is triggered when the average CPU utilization percentage has been lower than 10 percent for 24 hours, signaling that it is idle and no longer in use.You can adjust the threshold, duration, and period to suit your needs, plus you can add an Amazon Simple Notification Service (Amazon SNS) notification, so that you will receive an email when the alarm is triggered. Amazon CloudWatch alarm actions can stop an EBS-backed Amazon EC2 instances but they cannot stop instance store-backed Amazon EC2 instances. However, Amazon CloudWatch alarm actions can terminate either type of Amazon EC2 instance.

Note If you are using an AWS Identity and Access Management (IAM) account to create or modify an alarm, you must have the following Amazon EC2 permissions: ec2:DescribeInstanceStatus, ec2:DescribeInstances, ec2:StopInstances, and ec2:TerminateInstances in order for the alarm action to be performed. If you have read/write permissions for Amazon CloudWatch but not for Amazon EC2, you can still create an alarm but the stop or terminate actions won’t be performed on the Amazon EC2 instance. However, if you are later granted permission to use the associated Amazon EC2 APIs, the alarm actions you created earlier will be performed. For more information about IAM permissions, see Permissions and Policies in Using IAM. If you are using an IAM role (e.g. Amazon EC2 instance profile), you cannot stop or terminate the instance using alarm actions. However, you can still see the alarm state and perform any other actions such as Amazon SNS notifications or Auto Scaling policies. If you are using temporary security credentials granted using the AWS Security Token Service (AWS STS), you cannot stop or terminate an Amazon EC2 instance using alarm actions.

To create an alarm to stop an idle instance 1. 2.

6.

Open the Amazon CloudWatch console at https://console.aws.amazon.com/cloudwatch/. If necessary, change the region. From the navigation bar, select the region where your instance is running. For more information, see Regions and Endpoints. In the navigation pane, click Alarms. Click Create Alarm, and then in the CloudWatch Metrics by Category pane, under EC2 Metrics, select Per-Instance Metrics. In the list of metrics, select the instance and metric you want to create an alarm for. You can also type an instance ID in the search box to go the instance that you want. Select Average from the Statistic drop-down list.

7.

Select a period from the Period drop-down list, for example: 1 Day.

8.

Click Next, and then under Alarm Threshold, in the Name field, enter a unique name for the alarm, for example: Stop EC2 instance.

9.

In the Description field, enter a description of the alarm, for example: Stop EC2 instance when CPU is idle for too long.

3. 4. 5.

10. In the is drop-down list, select

[PDF] ec2 ug - Free Download PDF (2024)
Top Articles
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 5721

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.