Aws Cli
Aws Cli
User Guide
AWS Command Line Interface User Guide
Table of Contents
What Is the AWS CLI? ......................................................................................................................... 1
Using the Examples in this Guide ................................................................................................. 2
About Amazon Web Services ....................................................................................................... 3
Install ............................................................................................................................................... 4
Linux ........................................................................................................................................ 5
Python .............................................................................................................................. 6
on Amazon Linux 2017 ....................................................................................................... 6
Troubleshooting ................................................................................................................. 7
Installing Pip ..................................................................................................................... 8
Installing the AWS CLI with Pip ........................................................................................... 9
Windows ................................................................................................................................... 9
MSI Installer .................................................................................................................... 10
Windows ......................................................................................................................... 11
Adding the AWS CLI Executable to your Command Line Path ................................................. 12
macOS .................................................................................................................................... 12
Install Python, pip, and the AWS CLI on macOS ................................................................... 12
Adding the AWS CLI Executable to your Command Line Path ................................................. 13
Virtualenv ................................................................................................................................ 13
Bundled Installer ...................................................................................................................... 14
Prerequisites .................................................................................................................... 15
Install the AWS CLI Using the Bundled Installer .................................................................... 15
Install the AWS CLI Without Sudo (Linux, macOS, or Unix) ..................................................... 16
Uninstalling ..................................................................................................................... 16
Congure ........................................................................................................................................ 17
Quick Conguration .................................................................................................................. 17
Conguration Settings and Precedence ....................................................................................... 19
Conguration and Credential Files .............................................................................................. 19
Named Proles ........................................................................................................................ 20
Using Proles with the AWS CLI ......................................................................................... 21
Environment Variables .............................................................................................................. 21
Command Line Options ............................................................................................................ 22
Instance Metadata .................................................................................................................... 23
Using an HTTP Proxy ................................................................................................................ 23
Authenticating to a Proxy .................................................................................................. 23
Using a proxy on EC2 Instances ......................................................................................... 24
Assuming a Role ...................................................................................................................... 24
Conguring and Using a Role ............................................................................................ 24
Using Multifactor Authentication ........................................................................................ 26
Cross Account Roles .......................................................................................................... 26
Command Completion .............................................................................................................. 26
Identify Your Shell ............................................................................................................ 27
Locate the AWS Completer ................................................................................................ 27
Enable Command Completion ............................................................................................ 28
Test Command Completion ............................................................................................... 28
Tutorial: Using Amazon EC2 ............................................................................................................... 29
Install the AWS CLI ................................................................................................................... 29
Windows ......................................................................................................................... 29
Linux, macOS, or Unix ....................................................................................................... 29
Congure the CLI and Launch an EC2 Instance ............................................................................. 30
Step 1: Congure the AWS CLI ........................................................................................... 30
Step 2: Create a Security Group, Key Pair, and Role for the EC2 Instance .................................. 30
Step 3: Launch and Connect to the Instance ........................................................................ 31
Using the AWS CLI ........................................................................................................................... 33
Getting Help ............................................................................................................................ 33
iii
AWS Command Line Interface User Guide
iv
AWS Command Line Interface User Guide
The AWS CLI is an open source tool built on top of the AWS SDK for Python (Boto) that provides
commands for interacting with AWS services. With minimal conguration, you can start using all of the
functionality provided by the AWS Management Console from your favorite terminal program.
Linux shells Use common shell programs such as Bash, Zsh, and tsch to run commands in Linux,
macOS, or Unix.
Windows command line On Microsoft Windows, run commands in either PowerShell or the Windows
Command Processor.
Remotely Run commands on Amazon EC2 instances through a remote terminal such as PuTTY or
SSH, or with Amazon EC2 systems manager.
The AWS CLI provides direct access to AWS services' public APIs. Explore a service's capabilities with the
AWS CLI, and develop shell scripts to manage your resources. Or take what you've learned to develop
programs in other languages with the AWS SDK.
In addition to the low level, API equivalent commands, the AWS CLI also provides customizations for
several services. Customizations are higher level commands that simplify using a service with a complex
API. For example, the aws s3 set of commands provide a familiar syntax for managing les in Amazon
S3.
aws s3 cp provides a shell-like copy command, and automatically performs a multipart upload to
transfer large les quickly and resiliently.
Performing the same task with the low level commands (available under aws s3api) would take a lot
more eort.
Depending on your use case, you may want to use the AWS SDK, a toolkit, or the AWS Tools for Windows
PowerShell.
1
AWS Command Line Interface User Guide
Using the Examples in this Guide
You can viewand forkthe source code for the AWS CLI on GitHub in the aws-cli repository. Join
the community of users on GitHub to provide feedback, request features, and submit your own
contributions!
Prompt The command prompt is displayed as a dollar sign ('$'). Do not include the prompt when you
type commands.
Directory When commands must be executed from a specic directory, the directory name is shown
before the prompt symbol.
User Input Command text that you should enter at the command line is formatted as user input.
Replaceable Text Variable text, including names of resources that you choose, or IDs generated by
AWS services that you must include in commands, is formatted as replaceable text. In multiple line
commands or commands where specic keyboard input is required, keyboard commands can also be
shown as replaceable text.
Output Output returned by AWS services is shown beneath user input without any special
formatting.
For example, the following command includes user input, replaceable text, and output:
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: ENTER
To use this example, type aws configure at the command line and press Enter. aws configure is the
command. This command is interactive, so the AWS CLI outputs lines of texts, prompting you to enter
additional information. Enter each of your access keys in turn and press Enter. Then, enter a region name
in the format shown, press Enter, and press Enter a nal time to skip the output format setting. The nal
Enter command is shown as replaceable text because there is no user input for that line. Otherwise, it
would be implied.
The following example shows a simple non-interactive command with output from the service in JSON
format:
2
AWS Command Line Interface User Guide
About Amazon Web Services
To use this example, enter the full text of the command (the highlighted text after the prompt) and press
Enter. The name of the security group, my-sg is replaceable. In this case, you can use the group name as
shown, but you will probably want to use a more descriptive name.
Note
Arguments that must be replaced (such as AWS Access Key ID), and those that should be
replaced (such as group name), are both shown as replaceable text. If an argument must be
replaced, it will be noted in the text describing the example.
The JSON document, including the curly braces, is output. If you congure your CLI to output in text or
table format, the output will be formatted dierently. JSON is the default output format.
3
AWS Command Line Interface User Guide
The primary distribution method for the AWS CLI on Linux, Windows, and macOS is pip, a package
manager for Python that provides an easy way to install, upgrade, and remove Python packages and
their dependencies.
Current AWS CLI Version
The AWS CLI is updated frequently with support for new services and commands. To see if you
have the latest version, see the releases page on GitHub.
Requirements
If you already have pip and a supported version of Python, you can install the AWS CLI with the
following command:
The --upgrade option tells pip to upgrade any requirements that are already installed. The --user
option tells pip to install the program to a subdirectory of your user directory to avoid modifying
libraries used by your operating sytem.
If you encounter issues when you attempt to install the AWS CLI with pip, you can install the AWS CLI
in a virtual environment (p. 13) to isolate the tool and its dependencies, or use a dierent version of
Python than you normally do.
Standalone Installers
For oine or automated installations on Linux, macOS, or Unix, try the bundled
installer (p. 14). The bundled installer includes the AWS CLI, its dependencies, and a shell
script that performs the installation for you.
4
AWS Command Line Interface User Guide
Linux
On Windows, you can also use the MSI installer (p. 10). Both of these methods simplify the
initial installation, with the tradeo of being more dicult to upgrade when a new version of
the AWS CLI is released.
After you install the AWS CLI, you may need to add the path to the executable le to your PATH variable.
For platform specic instructions, see the following topics:
Verify that the AWS CLI installed correctly by running aws --version.
$ aws --version
aws-cli/1.11.84 Python/3.5.2 Linux/4.4.0-59-generic botocore/1.5.47
The AWS CLI is updated regularly to add support for new services and commands. To update to the latest
version of the AWS CLI, run the installation command again.
If you don't have Python and pip, use the procedure for your operating system:
Sections
Install the AWS Command Line Interface on Linux (p. 5)
Install the AWS Command Line Interface on Microsoft Windows (p. 9)
Install the AWS Command Line Interface on macOS (p. 12)
Install the AWS Command Line Interface in a Virtual Environment (p. 13)
Install the AWS CLI Using the Bundled Installer (Linux, macOS, or Unix) (p. 14)
Important
The awscli package is available in repositories for other package managers such as APT and
yum, but it is not guaranteed to be the latest version unless you get it from pip or use the
bundled installer (p. 14)
If you already have pip, follow the instructions in the main installation topic (p. 4). Run pip --
version to see if your version of Linux already includes Python and pip.
$ pip --version
If you don't have pip, check to see which version of Python is installed.
5
AWS Command Line Interface User Guide
Python
$ python --version
or
$ python3 --version
If you don't have Python 2 version 2.6.5+ or Python 3 version 3.3+, install Python (p. 6). Otherwise,
install pip and the AWS CLI.
$ python --version
Note
If your Linux distribution came with Python, you may need to install the Python developer
package in order to get the headers and libraries required to compile extensions and install
the AWS CLI. Install the developer package (typically named python-dev or python-devel)
using your package manager.
2. If Python 2.7 or later is not installed, install Python with your distribution's package manager. The
command and package name varies:
3. Open a command prompt or shell and run the following command to verify that Python installed
correctly:
$ python3 --version
Python 3.5.2
6
AWS Command Line Interface User Guide
Troubleshooting
$ aws --version
aws-cli/1.11.83 Python/2.7.12 Linux/4.9.20-11.31.amzn1.x86_64 botocore/1.5.46
You can use sudo yum update to get the latest version available in the yum repository, but this may not
be the latest version. Use pip to get the latest version.
1. Use pip install to install the latest version of the AWS CLI.
$ aws --version
aws-cli/1.11.85 Python/2.7.12 Linux/4.9.20-11.31.amzn1.x86_64 botocore/1.5.48
If you don't have root privileges, install the AWS CLI in user mode.
1. Use pip install to install the latest version of the AWS CLI.
$ export PATH=/home/ec2-user/.local/bin:$PATH
Add this command to the end of ~/.bashrc to maintain the change between sessions.
3. Verify the new version with aws --version.
$ aws --version
aws-cli/1.11.85 Python/2.7.12 Linux/4.9.20-11.31.amzn1.x86_64 botocore/1.5.48
Example AWS CLI install location - Linux with pip (user mode)
~/.local/bin
If you see an error message like -bash: aws: command not found when you try to use the AWS CLI, add
the location of the executable to your PATH environment variable.
1. Find your shell's prole script in your user folder. If you are not sure which shell you have, run echo
$SHELL.
7
AWS Command Line Interface User Guide
Installing Pip
$ ls -a ~
. .. .bash_logout .bash_profile .bashrc Desktop Documents Downloads
export PATH=~/.local/bin:$PATH
This command adds a path, ~/.local/bin in this example, to the current PATH variable.
3. Load the prole into your current session.
$ source ~/.bash_profile
If you see permission denied when you try to use the AWS CLI, make sure that the aws script has a le
mode that is executable. For example, 755.
$ which aws
~/.local/bin
$ chmod +x ~/.local/bin
Sections
Installing Pip (p. 8)
Installing the AWS CLI with Pip (p. 9)
Installing Pip
If you don't have pip, install pip with the script provided by the Python Packaging Authority.
To install pip
$ curl -O https://bootstrap.pypa.io/get-pip.py
The script downloads and installs the latest version of pip and another required package named
setuptools.
2. Run the script with Python:
8
AWS Command Line Interface User Guide
Installing the AWS CLI with Pip
1. Find your shell's prole script in your user folder. If you are not sure which shell you have, run
echo $SHELL.
$ ls -a ~
. .. .bash_logout .bash_profile .bashrc Desktop Documents Downloads
export PATH=~/.local/bin:$PATH
This command adds a path, ~/.local/bin in this example, to the current PATH variable.
3. Load the prole into your current session.
$ source ~/.bash_profile
$ pip --version
pip 8.1.2 from ~/.local/lib/python3.4/site-packages (python 3.4)
$ aws --version
aws-cli/1.11.84 Python/3.5.2 Linux/4.4.0-59-generic botocore/1.5.47
If you get an error, see Troubleshooting AWS CLI Installations on Linux (p. 7).
9
AWS Command Line Interface User Guide
MSI Installer
Sections
MSI Installer (p. 10)
Install Python, pip, and the AWS CLI on Windows (p. 11)
Adding the AWS CLI Executable to your Command Line Path (p. 12)
MSI Installer
The AWS CLI is supported on Microsoft Windows XP or later. For Windows users, the MSI installation
package oers a familiar and convenient way to install the AWS CLI without installing any other
prerequisites.
When updates are released, you must repeat the installation process to get the latest version of the AWS
CLI. If you prefer to update frequently, consider using pip (p. 11) for easier updates.
Note
The MSI installer for the AWS CLI does not work with Windows Server 2008 (version
6.0.6002). Use pip (p. 11) to install with this version of Windows.
2. Run the downloaded MSI installer.
3. Follow the instructions that appear.
Don't include the prompt symbol ('>' above) when you type a command. These are included in program
listings to dierentiate commands that you type from output returned by the CLI. The rest of this guide
uses the generic prompt symbol '$' except in cases where a command is Windows-specic.
If Windows is unable to nd the executable, you may need to re-open the command prompt or add the
installation directory to your PATH (p. 12) environment variable manually.
Uninstalling
To uninstall the AWS CLI, open the Control Panel and select Programs and Features. Select the entry
named AWS Command Line Interface and click Uninstall to launch the uninstaller. Conrm that you wish
to uninstall the AWS CLI when prompted.
10
AWS Command Line Interface User Guide
Windows
You can also launch the Programs and Features menu from the command line with the following
command:
> appwiz.cpl
1. Download and install Python 3.4 from the downloads page of Python.org.
2. Add the Python home and scripts directories to the Windows Path system variable:
C:\WINDOWS\system32;C:\WINDOWS;C:\Python34;C:\Python34\Scripts;%USERPROFILE%\AppData
\Roaming\Python\Scripts
11
AWS Command Line Interface User Guide
Adding the AWS CLI Executable
to your Command Line Path
$ pip --version
Sections
Install Python, pip, and the AWS CLI on macOS (p. 12)
Adding the AWS CLI Executable to your Command Line Path (p. 13)
1. Download and install Python 3.6 from the downloads page of Python.org.
2. Install pip with the script provided by the Python Packaging Authority.
$ curl -O https://bootstrap.pypa.io/get-pip.py
$ python3 get-pip.py --user
12
AWS Command Line Interface User Guide
Adding the AWS CLI Executable
to your Command Line Path
$ aws --version
AWS CLI 1.11.84 (Python 3.6.1)
If the executable is not found, add it to your command line path (p. 13).
Example AWS CLI install location - macOS with Python 3.6 and pip (user mode)
~/Library/Python/3.6/bin
1. Find your shell's prole script in your user folder. If you are not sure which shell you have, run echo
$SHELL.
$ ls -a ~
. .. .bash_logout .bash_profile .bashrc Desktop Documents Downloads
export PATH=~/.local/bin:$PATH
This command adds a path, ~/.local/bin in this example, to the current PATH variable.
3. Load the prole into your current session.
$ source ~/.bash_profile
13
AWS Command Line Interface User Guide
Bundled Installer
$ virtualenv ~/cli-ve
You can use the -p option to use a Python executable other than the default.
$ source ~/cli-ve/bin/activate
Windows
$ %USERPROFILE%\cli-ve\Scripts\activate
$ aws --version
aws-cli/1.11.84 Python/3.5.2 Linux/4.4.0-59-generic botocore/1.5.47
You can use the deactivate command to exit the virtual environment. Whenever you start a new session,
run the activation command again.
Sections
Prerequisites (p. 15)
14
AWS Command Line Interface User Guide
Prerequisites
Install the AWS CLI Using the Bundled Installer (p. 15)
Install the AWS CLI Without Sudo (Linux, macOS, or Unix) (p. 16)
Uninstalling (p. 16)
Prerequisites
Linux, macOS, or Unix
Python 2 version 2.6.5+ or Python 3 version 3.3+
$ python --version
If your computer doesn't already have Python installed, or you would like to install a dierent version of
Python, follow the procedure in Install the AWS Command Line Interface on Linux (p. 5).
$ unzip awscli-bundle.zip
Note
If you don't have unzip, use your Linux distribution's built in package manager to install it.
3. Run the install executable.
Note
By default, the install script runs under the system default version of Python. If you have
installed an alternative version of Python and want to use that to install the AWS CLI, run
the install script with that version by absolute path to the Python executable. For example:
The installer installs the AWS CLI at /usr/local/aws and create the symlink aws at the /usr/local/bin
directory. Using the -b option to create a symlink eliminates the need to specify the install directory
in the user's $PATH variable. This should enable all users to call the AWS CLI by typing aws from any
directory.
15
AWS Command Line Interface User Guide
Install the AWS CLI Without Sudo (Linux, macOS, or Unix)
$ ./awscli-bundle/install -h
This installs the AWS CLI to the default location (~/.local/lib/aws) and create a symbolic link (symlink)
at ~/bin/aws. Make sure that ~/bin is in your PATH environment variable for the symlink to work:
$ echo $PATH | grep ~/bin // See if $PATH contains ~/bin (output will be empty if it
doesn't)
$ export PATH=~/bin:$PATH // Add ~/bin to $PATH if necessary
Tip
To ensure that your $PATH settings are retained between sessions, add the export line to your
shell prole (~/.prole, ~/.bash_prole, etc).
Uninstalling
The bundled installer does not put anything outside of the installation directory except the optional
symlink, so uninstalling is as simple as deleting those two items.
16
AWS Command Line Interface User Guide
Quick Conguration
This section explains how to congure settings that the AWS Command Line Interface uses when
interacting with AWS, such as your security credentials and the default region.
Note
The AWS CLI signs requests on your behalf, and includes a date in the signature. Ensure that
your computer's date and time are set correctly; if not, the date in the signature may not match
the date of the request, and AWS rejects the request.
Sections
Quick Conguration (p. 17)
Conguration Settings and Precedence (p. 19)
Conguration and Credential Files (p. 19)
Named Proles (p. 20)
Environment Variables (p. 21)
Command Line Options (p. 22)
Instance Metadata (p. 23)
Using an HTTP Proxy (p. 23)
Assuming a Role (p. 24)
Command Completion (p. 26)
Quick Conguration
For general use, the aws configure command is the fastest way to set up your AWS CLI installation.
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json
The AWS CLI will prompt you for four pieces of information. AWS Access Key ID and AWS Secret Access
Key are your account credentials.
17
AWS Command Line Interface User Guide
Quick Conguration
Access keys consist of an access key ID and secret access key, which are used to sign programmatic
requests that you make to AWS. If you don't have access keys, you can create them by using the AWS
Management Console. We recommend that you use IAM access keys instead of AWS root account access
keys. IAM lets you securely control access to AWS services and resources in your AWS account.
Note
To create access keys, you must have permissions to perform the required IAM actions. For more
information, see Granting IAM User Permission to Manage Password Policy and Credentials in
the IAM User Guide.
Your secret key will no longer be available through the AWS Management Console; you will have the
only copy. Keep it condential in order to protect your account, and never email it. Do not share it
outside your organization, even if an inquiry appears to come from AWS or Amazon.com. No one
who legitimately represents Amazon will ever ask you for your secret key.
Related topics
Default region is the name of the region you want to make calls against by default. This is usually the
region closest to you, but it can be any region.
Note
You must specify an AWS region when using the AWS CLI. For a list of services and available
regions, see Regions and Endpoints.
Default output format can be either json, text, or table. If you don't specify an output format, json will be
used.
If you have multiple proles, you can congure additional, named proles by using the --profile
option.
To update any of your settings, simply run aws configure again and enter new values as appropriate.
The next sections contains more information on the les that aws configure creates, additional settings,
and named proles.
18
AWS Command Line Interface User Guide
Conguration Settings and Precedence
The AWS CLI looks for credentials and conguration settings in the following order:
1. Command Line Options region, output format and prole can be specied as command options to
override default settings.
2. Environment Variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, etc.
3. The AWS credentials le located at ~/.aws/credentials on Linux, macOS, or Unix, or at C:\Users
\USERNAME \.aws\credentials on Windows. This le can contain multiple named proles in addition
to a default prole.
4. The CLI conguration le typically located at ~/.aws/config on Linux, macOS, or Unix, or at C:
\Users\USERNAME \.aws\config on Windows. This le can contain a default prole, named proles,
and CLI specic conguration parameters for each.
5. Instance prole credentials these credentials can be used on EC2 instances with an assigned
instance role, and are delivered through the Amazon EC2 metadata service.
For example, the following commands list the contents of the .aws folder:
$ ls ~/.aws
Windows
In order to separate credentials from less sensitive options, region and output format are stored in a
separate le named config in the same folder.
The default le location for the cong le can be overridden by setting the AWS_CONFIG_FILE
environment variable to another local path. See Environment Variables (p. 21) for details.
Storing Credentials in Cong
The AWS CLI will also read credentials from the cong le. If you want to keep all of your prole
settings in a single le, you can. If there are ever credentials in both locations for a prole (say
you used aws configure to update the prole's keys), the keys in the credentials le will take
precedence.
If you use one of the SDKs in addition to the AWS CLI, you may notice additional warnings if
credentials are not stored in their own le.
The les generated by the CLI for the prole congured in the previous section look like this:
~/.aws/credentials
[default]
19
AWS Command Line Interface User Guide
Named Proles
aws_access_key_id=AKIAIOSFODNN7EXAMPLE
aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
~/.aws/config
[default]
region=us-west-2
output=json
aws_session_token AWS session token. A session token is only required if you are using temporary
security credentials.
Named Proles
The AWS CLI supports named proles stored in the cong and credentials les. You can congure
additional proles by using aws configure with the --profile option or by adding entries to the cong
and credentials les.
~/.aws/credentials
[default]
aws_access_key_id=AKIAIOSFODNN7EXAMPLE
aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
[user2]
aws_access_key_id=AKIAI44QH8DHBEXAMPLE
aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY
Each prole uses dierent credentialsperhaps from two dierent IAM usersand can also use dierent
regions and output formats.
~/.aws/config
[default]
region=us-west-2
output=json
[profile user2]
region=us-east-1
output=text
Important
The AWS credentials le uses a dierent naming format than the CLI cong le for named
proles. Do not include the 'prole ' prex when conguring a named prole in the AWS
credentials le.
20
AWS Command Line Interface User Guide
Using Proles with the AWS CLI
If you are going to use a named prole for multiple commands, you can avoid specifying the prole in
every command by setting the AWS_DEFAULT_PROFILE environment variable at the command line:
$ export AWS_DEFAULT_PROFILE=user2
Windows
Setting the environment variable changes the default prole until the end of your shell session, or until
you set the variable to a dierent value. More on variables in the next section.
Environment Variables
Environment variables override conguration and credential les and can be useful for scripting or
temporarily setting a named prole as the default.
AWS_SECRET_ACCESS_KEY AWS secret key. Access and secret key variables override credentials stored
in credential and cong les.
AWS_SESSION_TOKEN session token. A session token is only required if you are using temporary
security credentials.
AWS_DEFAULT_REGION AWS region. This variable overrides the default region of the in-use prole, if
set.
AWS_DEFAULT_PROFILE name of the CLI prole to use. This can be the name of a prole stored in a
credential or cong le, or default to use the default prole.
If the cong le variable is set, aws configure will write region and output settings to the specied le,
and the CLI will attempt to read proles' settings from there instead of the default le (~/.aws/cong).
Credentials will still be read from and written to the default credentials le (~/.aws/credentials).
The following example shows how you would congure environment variables for the default user from
earlier in this guide.
$ export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
21
AWS Command Line Interface User Guide
Command Line Options
$ export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
$ export AWS_DEFAULT_REGION=us-west-2
Windows
--endpoint-url The endpoint to make the call against. The endpoint can be the address of a proxy or
an endpoint URL for the in-use AWS region. Specifying an endpoint is not required for normal use as the
AWS CLI determines which endpoint to call based on the in-use region.
The above options override the corresponding prole settings for a single operation. Each takes a string
argument with a space or equals sign ("=") separating the argument from the option name. Quotes
around the argument are not required unless the argument string contains a space.
Tip
You can use the --prole option with aws configure to set up additional proles
Common uses for command line options include checking your resources in multiple regions and
changing output format for legibility or ease of use when scripting. For example, if you are not sure
which region your instance is running in you could run the describe-instances command against each
region until you nd it:
22
AWS Command Line Interface User Guide
Instance Metadata
|+-------------------------------------+------------------------------------+|
||| Instances |||
||+------------------------+-----------------------------------------------+||
||| AmiLaunchIndex | 0 |||
||| Architecture | x86_64 |||
...
Command line option parameter types (string, boolean, etc.) are discussed in detail in the Specifying
Parameter Values for the AWS Command Line Interface (p. 37) section later in this guide.
Instance Metadata
To use the CLI from an EC2 instance, create a role that has access to the resources needed and assign
that role to the instance when it is launched. Launch the instance and check to see if the AWS CLI is
already installed (it comes pre-installed on Amazon Linux).
Install the AWS CLI if necessary and congure a default region to avoid having to specify it in every
command. You can set the region using aws configure without entering credentials by pressing enter
twice to skip the rst two prompts:
$ aws configure
AWS Access Key ID [None]: ENTER
AWS Secret Access Key [None]: ENTER
Default region name [None]: us-west-2
Default output format [None]: json
The AWS CLI will read credentials from the instance metadata. For more information, see Granting
Applications that Run on Amazon EC2 Instances Access to AWS Resources in IAM User Guide.
$ export HTTP_PROXY=http://a.b.c.d:n
$ export HTTPS_PROXY=http://w.x.y.z:m
Windows
In these examples, http://a.b.c.d:n and http://w.x.y.z:m are the IP addresses and ports for the HTTP
and HTTPS proxies.
Authenticating to a Proxy
The AWS CLI supports HTTP Basic authentication. Specify a username and password in the proxy URL like
this:
23
AWS Command Line Interface User Guide
Using a proxy on EC2 Instances
$ export HTTP_PROXY=http://username:[email protected]:n
$ export HTTPS_PROXY=http://username:[email protected]:m
Windows
Note
The AWS CLI does not support NTLM proxies. If you use an NTLM or Kerberos proxy, you may be
able to connect through an authentication proxy like Cntlm.
$ export NO_PROXY=169.254.169.254
Windows
Assuming a Role
You can congure the AWS Command Line Interface to use a role by creating a prole for the role in the
~/.aws/config le. The following example shows a role prole named marketingadmin that is assumed
by the default prole.
[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadmin
source_profile = default
In this case, the default prole is an IAM user with credentials and permission to assume a role named
marketingadmin. To access the role, you create a named prole. Instead of conguring this prole with
credentials, you specify the ARN of the role and the name of the prole that has access to it.
Sections
Conguring and Using a Role (p. 24)
Using Multifactor Authentication (p. 26)
Cross Account Roles (p. 26)
24
AWS Command Line Interface User Guide
Conguring and Using a Role
call sts:assume-role against the role, and the role must have a trust relationship with the source prole
to allow itself to be assumed.
Create a new role in IAM with the permissions that you want users to assume by following the
procedure under Creating a Role to Delegate Permissions to an IAM User in the AWS Identity and Access
Management User Guide. If the role and the target IAM user are in the same account, you can enter your
own account ID when conguring the role's trust relationship.
After creating the role, modify the trust relationship to allow the IAM user to assume it. The following
example shows a trust relationship that allows a role to be assumed by an IAM user named jonsmith:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::123456789012:user/jonsmith"
},
"Action": "sts:AssumeRole"
}
]
}
Next, grant your IAM user permission to assume the role. The following example shows an AWS Identity
and Access Management policy that allows an IAM user to assume the marketingadmin role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::123456789012:role/marketingadmin"
}
]
}
The user doesn't need to have any additional permissions to run commands using the role prole. If you
want your users to be able to access AWS resources without using the role, apply additional inline or
managed policies for those resources.
With the role prole, role permissions, trust relationship and user permissions applied, you can assume
the role at the command line by using the profile option, for example:
To use the role for multiple calls, you can set the AWS_DEFAULT_PROFILE environment variable for the
current session from the command line:
$ export AWS_DEFAULT_PROFILE=marketingadmin
Windows
25
AWS Command Line Interface User Guide
Using Multifactor Authentication
For more information on conguring IAM users and roles, see Users and Groups and Roles in the AWS
Identity and Access Management User Guide.
First, modify the trust relationship on the role to require multifactor authentication:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::123456789012:user/jonsmith" },
"Action": "sts:AssumeRole",
"Condition": { "Bool": { "aws:MultiFactorAuthPresent": true } }
}
]
}
Next, add a line to the role prole that species the ARN of the user's MFA device:
[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadmin
source_profile = default
mfa_serial = arn:aws:iam::123456789012:mfa/jonsmith
The mfa_serial setting can take an ARN, as shown, or the serial number of a hardware MFA token.
If you use an external ID to provide additional control over who can assume a role across accounts, add
an external_id parameter to the role prole:
[profile crossaccountrole]
role_arn = arn:aws:iam::234567890123:role/xaccount
source_profile = default
mfa_serial = arn:aws:iam::123456789012:mfa/jonsmith
external_id = 123456
Command Completion
On Unix-like systems, the AWS CLI includes a command-completion feature that enables you to use the
TAB key to complete a partially typed command. This feature is not automatically installed so you need
to congure it manually.
Conguring command completion requires two pieces of information: the name of the shell you are
using and the location of the aws_completer script.
26
AWS Command Line Interface User Guide
Identify Your Shell
Sections
Identify Your Shell (p. 27)
Locate the AWS Completer (p. 27)
Enable Command Completion (p. 28)
Test Command Completion (p. 28)
echo $SHELL show the shell's installation directory. This will usually match the in-use shell, unless you
launched a dierent shell after logging in.
$ echo $SHELL
/bin/bash
ps show the processes running for the current user. The shell will be one of them.
$ ps
PID TTY TIME CMD
2148 pts/1 00:00:00 bash
8756 pts/1 00:00:00 ps
Package Manager programs such as pip, yum, brew and apt-get typically install the AWS completer (or
a symlink to it) to a standard path location. In this case, which will locate the completer for you.
$ which aws_completer
/usr/local/bin/aws_completer
Bundled Installer if you used the bundled installer per the instructions in the previous section, the
AWS completer will be located in the bin subfolder of the installation directory.
$ ls /usr/local/aws/bin
activate
activate.csh
activate.fish
activate_this.py
aws
aws.cmd
aws_completer
...
If all else fails, you can use find to search your entire le system for the AWS completer.
27
AWS Command Line Interface User Guide
Enable Command Completion
Note
/usr/local/bin is the default installation directory when you install the AWS CLI with pip. See
Locate the AWS Completer (p. 27) if you are not sure where the AWS CLI was installed.
tcsh complete for tcsh takes a word type and pattern to dene the completion behavior.
% source /usr/local/bin/aws_zsh_completer.sh
The AWS CLI uses bash compatibility auto completion (bashcompinit) for zsh support. For further details,
refer to the top of aws_zsh_completer.sh.
Note
If you installed the AWS CLI using the bundled installer, add the install location to your PATH
variable to allow command completion to nd it.
$ export PATH=/usr/local/aws/bin:$PATH
$ aws sTAB
s3 ses sqs sts swf
s3api sns storagegateway support
Finally, to ensure that completion continues to work after a reboot, add the conguration command that
you used to enable command completion to your shell prole. If you added a directory to your PATH
variable, put the export statement in your prole as well.
The following example appends the prole for a bash user who installed the AWS CLI to /usr/local/aws
using the bundled installer:
28
AWS Command Line Interface User Guide
Install the AWS CLI
Deploying a Development
Environment in Amazon EC2 Using
the AWS Command Line Interface
This tutorial details how to set up a development environment in Amazon EC2 using the AWS CLI. It
includes a short version of the installation and conguration instructions, and it can be run start to nish
on Windows, Linux, macOS, or Unix.
Topics
Install the AWS CLI (p. 29)
Congure the CLI and Launch an EC2 Instance (p. 30)
Windows
1. Download the MSI installer.
29
AWS Command Line Interface User Guide
Congure the CLI and Launch an EC2 Instance
1. Download and run the installation script from the pip website:
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json
The AWS CLI will prompt you for the following information:
AWS Access Key ID and AWS Secret Access Key These are your account credentials. If you don't have
keys, see How Do I Get Security Credentials? in the Amazon Web Services General Reference.
Default region name This is the name of the region you want to make calls against by default.
Note
Use us-west-2 for this tutorial (the AMI we will use is specic to this region). You can change
the default region later by running aws configure again.
Default output format This format can be either json, text, or table. If you don't specify an output
format, json will be used.
1. First, create a new security group and add a rule that allows incoming trac over port 22 for SSH.
Note the security group ID for later use.
30
AWS Command Line Interface User Guide
Step 3: Launch and Connect to the Instance
2. Replace the CIDR range in the above with the one that you will connect from for more security. You
can use the aws ec2 describe-security-groups command to admire your handiwork.
3. Next, create a key pair, which allows you to connect to the instance.
$ aws ec2 create-key-pair --key-name devenv-key --query 'KeyMaterial' --output text >
devenv-key.pem
1. Run the following command, replacing the security group ID output in the previous step.
The image ID ami-29ebb519 species the Amazon Machine Image (AMI) that Amazon EC2 uses
to bootstrap the instance. You can nd image IDs for other regions and operating systems in the
Amazon EC2 Management Console Launch Instance Wizard.
Note
T2 instance types require a VPC. If you don't have a default VPC, you can specify a subnet in
a custom VPC with the --subnet-id option. If you don't have any VPCs, choose a dierent
instance type such as t1.micro.
2. The instance will take a few moments to launch. Once the instance is up and running, the following
command will retrieve the public IP address that you will use to connect to the instance.
3. To connect to the instance, use the public IP address and private key with your preferred terminal
program. On Linux, macOS, or Unix, you can do this from the command line with the following
command:
If you get an error like Permission denied (publickey) when attempting to connect to your instance,
check that the following are correct:
31
AWS Command Line Interface User Guide
Step 3: Launch and Connect to the Instance
Key The key specied with the -i option must be at the path indicated and must be the private
key, not the public one. Permissions on the key must be restricted to the owner.
User name The user name must match the user associated with the key pair on the instance. For
Ubuntu instances, this is ubuntu. For Amazon Linux, it is ec2-user.
Instance The public IP address or DNS name of the instance. Verify that the address is public and
that port 22 is open to your local machine on the instance's security group.
You can also use the -v option to view additional information related to the error.
SSH on Windows
On Windows, you can use the PuTTY terminal application available here. Get putty.exe and
puttygen.exe from the downloads page.
Use puttygen.exe to convert your private key to a .ppk le required by PuTTY. Launch
putty.exe, enter the public IP address of the instance in the Host Name eld, and set the
connection type to SSH.
In the Category panel, navigate to Connection > SSH > Auth, and click Browse to select
your .ppk le, and then click Open to connect.
4. The terminal will prompt you to accept the server's public key. Type yes and click Enter to complete
the connection.
You've now congured a security group, created a key pair, launched an EC2 instance, and connected to it
without ever leaving the command line.
32
AWS Command Line Interface User Guide
Getting Help
This section introduces the common features and calling patterns used throughout the AWS Command
Line Interface.
Note
The AWS CLI makes API calls to services over HTTPS. Outbound connections on TCP port 443
must be enabled in order to perform calls.
Topics
Getting Help with the AWS Command Line Interface (p. 33)
Command Structure in the AWS Command Line Interface (p. 37)
Specifying Parameter Values for the AWS Command Line Interface (p. 37)
Generate CLI Skeleton and CLI Input JSON Parameters (p. 43)
Controlling Command Output from the AWS Command Line Interface (p. 45)
Using Shorthand Syntax with the AWS Command Line Interface (p. 52)
Using the AWS Command Line Interface's Pagination Options (p. 53)
$ aws help
The following command lists the available subcommands for Amazon EC2.
33
AWS Command Line Interface User Guide
Getting Help
The next example lists the detailed help for the EC2 DescribeInstances operation, including descriptions
of its input parameters, lters, and output. Check the examples section of the help if you are not sure
how to phrase a command.
NAME
describe-instances -
Description a description of the API operation that the command invokes, pulled from the API
documentation for the command's service.
DESCRIPTION
Describes one or more of your instances.
If you specify one or more instance IDs, Amazon EC2 returns information
for those instances. If you do not specify instance IDs, Amazon EC2
returns information for all relevant instances. If you specify an
instance ID that is not valid, an error is returned. If you specify an
instance that you do not own, it is not included in the returned
results.
...
Synopsis list of the command and its options. If an option is shown in square brackets, it is either
optional, has a default value, or has an alternative option that can be used instead.
SYNOPSIS
describe-instances
[--dry-run | --no-dry-run]
[--instance-ids <value>]
[--filters <value>]
[--cli-input-json <value>]
[--starting-token <value>]
[--page-size <value>]
[--max-items <value>]
[--generate-cli-skeleton]
describe-instances has a default behavior that describes all instances in the current account and
region. You can optionally specify a list of instance-ids to describe one or more instances. dry-run is an
optional boolean ag that doesn't take a value. To use a boolean ag, specify either shown value, in this
case --dry-run or --no-dry-run. Likewise, --generate-cli-skeleton does not take a value. If there are
conditions on an option's use, they should be described in the OPTIONS section, or shown in the examples.
OPTIONS
--dry-run | --no-dry-run (boolean)
Checks whether you have the required permissions for the action,
without actually making the request, and provides an error response.
If you have the required permissions, the error response is DryRun-
Operation . Otherwise, it is UnauthorizedOperation .
34
AWS Command Line Interface User Guide
Getting Help
--instance-ids (list)
One or more instance IDs.
Examples examples showing the usage of the command and its options. If no example is available for
a command or use case that you need, please request one using the feedback link on this page, or in the
AWS CLI command reference on the help page for the command.
EXAMPLES
To describe an Amazon EC2 instance
Command:
Command:
Command:
Output descriptions of each of the elds and datatypes returned in the response from AWS.
For describe-instances, the output is a list of reservation objects, each of which contains several elds
and objects that contain information about the instance(s) associated with it. This information comes
from the API documentation for the reservation datatype used by Amazon EC2.
OUTPUT
Reservations -> (list)
One or more reservations.
(structure)
Describes a reservation.
(structure)
Describes a security group.
35
AWS Command Line Interface User Guide
AWS CLI Documentation
(structure)
Describes an instance.
When the output is rendered into JSON by the AWS CLI, it becomes an array of reservation objects, like
this:
{
"Reservations": [
{
"OwnerId": "012345678901",
"ReservationId": "r-4c58f8a0",
"Groups": [],
"RequesterId": "012345678901",
"Instances": [
{
"Monitoring": {
"State": "disabled"
},
"PublicDnsName": "ec2-52-74-16-12.us-west-2.compute.amazonaws.com",
"State": {
"Code": 16,
"Name": "running"
},
...
Each reservation object contains elds describing the reservation and an array of instance objects, each
with its own elds (e.g. PublicDnsName) and objects (e.g. State) that describe it.
Windows Users
Pipe the output of the help command to more to view the help le one page at a time. Press the
space bar or Page Down to view more of the document, and q to quit.
Help les sometimes contain links that cannot be viewed or followed from the command line view; these
are preserved in the online AWS CLI reference.
36
AWS Command Line Interface User Guide
API Documentation
API Documentation
All subcommands in the AWS CLI correspond to calls made against a service's public API. Each service
with a public API, in turn, has a set of API reference documentation that can be found from the service's
homepage on the AWS Documentation website.
The content of an API reference varies based on how the API is constructed and which protocol is used.
Typically, an API reference will contain detailed information on actions supported by the API, data sent
to and from the service, and possible error conditions.
Actions Detailed information on parameters (including constraints on length or content) and errors
specic to an action. Actions correspond to subcommands in the AWS CLI.
Data Types May contain additional information about object data returned by a subcommand.
Common Parameters Detailed information about parameters that are used by all of a service's
actions.
Common Errors Detailed information about errors returned by all of a service's actions.
The name and availability of each section may vary depending on the service.
Service-Specic CLIs
Some services have a separate CLI from before a single AWS CLI was created that works with
all services. These service-specic CLIs have separate documentation that is linked from the
service's documentation page. Documentation for service-specic CLIs does not apply to the
AWS CLI.
Parameters can take various types of input values, such as numbers, strings, lists, maps, and JSON
structures.
37
AWS Command Line Interface User Guide
Common Parameter Types
Strings without any space characters may be quoted or unquoted. However, strings that include one
or more space characters must be quoted. Use a single quote (') in Linux, macOS, or Unix and Windows
PowerShell, or use a double quote (") in the Windows command prompt, as shown in the following
examples.
You can also use an equals sign instead of a space. This is typically only necessary if the value of the
parameter starts with a hyphen:
Topics
Common Parameter Types (p. 38)
Using JSON for Parameters (p. 39)
Loading Parameters from a File (p. 41)
The help for each subcommand describes its function, options, output, and examples. The options
section includes the name and description of each option with the option's parameter type in
parentheses.
String String parameters can contain alphanumeric characters, symbols, and whitespace from the
ASCII character set. Strings that contain whitespace must be surrounded by quotes. Use of symbols and
whitespace other than the standard space character is not recommended and may cause issues when
using the AWS CLI.
Some string parameters can accept binary data from a le. See Binary Files (p. 42) for an example.
Timestamp Timestamps are formatted per the ISO 8601 standard. These are sometimes referred to as
"DateTime" or "Date" type parameters.
38
AWS Command Line Interface User Guide
Using JSON for Parameters
The output indicates whether the command was well formed or not. This command also includes a no-
dry-run version of the parameter that can be used to explicitly indicate that the command should be run
normally, although including it is not necessary as this is the default behavior.
Blob Binary object. Blob parameters take a path to a local le that contains binary data. The path
should not contain any protocol identier such as http:// or file://.
Map A sequence of key value pairs specied in JSON or shorthand syntax (p. 52). The following
example reads an item from a DynamoDB table named my-table with a map parameter, --key. The
parameter species the primary key named id with a number value of 1 in a nested JSON structure.
The following example species the equivalent list of lters in a JSON array. Square brackets are used to
create an array of JSON objects separated by commas. Each object is a comma separated list of key-value
pairs ("Name" and "Values" are both keys in this instance).
39
AWS Command Line Interface User Guide
Using JSON for Parameters
Note that value to the right of the "Values" key is itself an array. This is required, even if the array
contains only one value string.
[
{
"Name": "instance-type",
"Values": ["t2.micro", "m1.medium"]
},
{
"Name": "availability-zone",
"Values": ["us-west-2c"]
}
]
The outermost brackets, on the other hand, are only required if more than one lter is specied. A single
lter version of the above command, formatted in JSON, looks like this:
Some operations require data to be formatted as JSON. For example, to pass parameters to the --block-
device-mappings parameter in the ec2 run-instances command, you need to format the block device
information as JSON.
This example shows the JSON to specify a single 20 GiB Elastic Block Store device to be mapped at /dev/
sdb on the launching instance.
{
"DeviceName": "/dev/sdb",
"Ebs": {
"VolumeSize": 20,
"DeleteOnTermination": false,
"VolumeType": "standard"
}
}
To attach multiple devices, list the objects in an array like in the next example.
[
{
"DeviceName": "/dev/sdb",
"Ebs": {
"VolumeSize": 20,
"DeleteOnTermination": false,
"VolumeType": "standard"
}
},
{
"DeviceName": "/dev/sdc",
"Ebs": {
"VolumeSize": 10,
"DeleteOnTermination": true,
"VolumeType": "standard"
}
}
]
You can either enter the JSON directly on the command line (see Quoting Strings (p. 41)), or save it to
a le that is referenced from the command line (see Loading Parameters from a File (p. 41)).
40
AWS Command Line Interface User Guide
Loading Parameters from a File
When passing in large blocks of data, you might nd it easier to save the JSON to a le and reference it
from the command line. JSON data in a le is easier to read, edit, and share with others. This technique is
described in the next section.
For more information about JSON, see Wikipedia - JSON and RFC4627 - The application/json Media Type
for JSON.
Quoting Strings
The way you enter JSON-formatted parameters on the command line diers depending upon your
operating system. Linux, macOS, or Unix and Windows PowerShell use the single quote (') to enclose the
JSON data structure, as in the following example:
The Windows command prompt, on the other hand, uses the double quote (") to enclose the JSON data
structure. In addition, a backslash (\) escape character is required for each double quote (") within the
JSON data structure itself, as in the following example:
Windows PowerShell requires a single quote (') to enclose the JSON data structure, as well as a backslash
(\) to escape each double quote (") within the JSON structure, as in the following example:
If the value of a parameter is itself a JSON document, escape the quotes on the embedded JSON
document. For example, the attribute parameter for aws sqs create-queue can take a RedrivePolicy
key. The value of RedrivePolicy is a JSON document, which must be escaped:
Windows
41
AWS Command Line Interface User Guide
Loading Parameters from a File
The file:// prex option supports Unix-style expansions including '~/', './', and '../'. On Windows, the
'~/' expression expands to your user directory, stored in the %USERPROFILE% environment variable. For
example, on Windows 7 you would typically have a user directory under C:\Users\User Name\.
JSON documents that are provided as the value of a parameter key must still be escaped:
attributes.json
{
"RedrivePolicy":"{\"deadLetterTargetArn\":\"arn:aws:sqs:us-
west-2:0123456789012:deadletter\", \"maxReceiveCount\":\"5\"}"
}
Binary Files
For commands that take binary data as a parameter, specify that the data is binary content by using the
fileb:// prex. Commands that accept binary data include:
The following example generates a binary 256 bit AES key using a Linux command line tool and then
provides it to Amazon S3 to encrypt an uploaded le server-side:
Remote Files
The AWS CLI also supports loading parameters from a le hosted on the Internet with an http:// or
https:// URL. The following example references a le in an Amazon S3 bucket. This allows you to access
parameter les from any computer, but requires the le to be stored in a publically accessible location.
In the preceding examples, the filename.json le contains the following JSON data.
[
{
"DeviceName": "/dev/sdb",
"Ebs": {
42
AWS Command Line Interface User Guide
Generate CLI Skeleton
"VolumeSize": 20,
"DeleteOnTermination": false,
"VolumeType": "standard"
}
}
]
For another example referencing a le containing more complex JSON-formatted parameters, see Set an
IAM Policy for an IAM User (p. 72).
Generate CLI Skeleton outputs JSON that outlines all of the parameters that can be specied for the
operation.
1. Execute the run-instances command with the --generate-cli-skeleton option to view the JSON
skeleton.
43
AWS Command Line Interface User Guide
Generate CLI Skeleton
"NoDevice": ""
}
],
"Monitoring": {
"Enabled": true
},
"SubnetId": "",
"DisableApiTermination": true,
"InstanceInitiatedShutdownBehavior": "",
"PrivateIpAddress": "",
"ClientToken": "",
"AdditionalInfo": "",
"NetworkInterfaces": [
{
"NetworkInterfaceId": "",
"DeviceIndex": 0,
"SubnetId": "",
"Description": "",
"PrivateIpAddress": "",
"Groups": [
""
],
"DeleteOnTermination": true,
"PrivateIpAddresses": [
{
"PrivateIpAddress": "",
"Primary": true
}
],
"SecondaryPrivateIpAddressCount": 0,
"AssociatePublicIpAddress": true
}
],
"IamInstanceProfile": {
"Arn": "",
"Name": ""
},
"EbsOptimized": true
}
3. Open the skeleton in a text editor and remove any parameters that you will not use:
{
"DryRun": true,
"ImageId": "",
"KeyName": "",
"SecurityGroups": [
""
],
"InstanceType": "",
"Monitoring": {
"Enabled": true
}
}
Leave the DryRun parameter set to true to use EC2's dry run feature, which lets you test your
conguration without creating resources.
4. Fill in the values for the instance type, key name, security group and AMI in your default region. In
this example, ami-dfc39aef is a 64-bit Amazon Linux image in the us-west-2 region.
44
AWS Command Line Interface User Guide
Controlling Command Output
{
"DryRun": true,
"ImageId": "ami-dfc39aef",
"KeyName": "mykey",
"SecurityGroups": [
"my-sg"
],
"InstanceType": "t2.micro",
"Monitoring": {
"Enabled": true
}
}
5. Pass the JSON conguration to the --cli-input-json parameter using the file:// prex:
The dry run error indicates that the JSON is formed correctly and the parameter values are valid.
If any other issues are reported in the output, x them and repeat the above step until the dry run
error is shown.
6. Set the DryRun parameter to false to disable the dry run feature.
{
"DryRun": false,
"ImageId": "ami-dfc39aef",
"KeyName": "mykey",
"SecurityGroups": [
"my-sg"
],
"InstanceType": "t2.micro",
"Monitoring": {
"Enabled": true
}
}
Topics
How to Select the Output Format (p. 46)
How to Filter the Output with the --query Option (p. 46)
45
AWS Command Line Interface User Guide
How to Select the Output Format
JSON (json)
Tab-delimited text (text)
ASCII-formatted table (table)
As explained in the conguration (p. 17) topic, the output format can be specied in three dierent ways:
Using the output option in the conguration le. The following example sets the output to text:
[default]
output=text
$ export AWS_DEFAULT_OUTPUT="table"
Note
If the output format is specied in multiple ways, the usual AWS CLI precedence rules (p. 19)
apply. For example, using the AWS_DEFAULT_OUTPUT environment variable overrides any value
set in the cong le with output, and a value passed to an AWS CLI command with --output
overrides any value set in the environment or in the cong le.
JSON is best for handling the output programmatically via various languages or jq (a command-
line JSON processor). The table format is easy for humans to read, and text format works well with
traditional Unix text processing tools, such as sed, grep, and awk, as well as Windows PowerShell scripts.
46
AWS Command Line Interface User Guide
How to Filter the Output with the --query Option
"DeleteOnTermination": true,
"Device": "/dev/sda1"
}
],
"VolumeType": "standard",
"VolumeId": "vol-e11a5288",
"State": "in-use",
"SnapshotId": "snap-f23ec1c8",
"CreateTime": "2013-09-17T00:55:03.000Z",
"Size": 30
},
{
"AvailabilityZone": "us-west-2a",
"Attachments": [
{
"AttachTime": "2013-09-18T20:26:16.000Z",
"InstanceId": "i-4b41a37c",
"VolumeId": "vol-2e410a47",
"State": "attached",
"DeleteOnTermination": true,
"Device": "/dev/sda1"
}
],
"VolumeType": "standard",
"VolumeId": "vol-2e410a47",
"State": "in-use",
"SnapshotId": "snap-708e8348",
"CreateTime": "2013-09-18T20:26:15.000Z",
"Size": 8
}
]
}
First, we can display only the rst volume from the Volumes list with the following command.
Now, we use the wildcard notation [*] to iterate over the entire list and also lter out three elements:
VolumeId, AvailabilityZone, and Size. Note that the dictionary notation requires that you provide
an alias for each key, like this: {Alias1:Key1,Alias2:Key2}. A dictionary is inherently unordered, so the
ordering of the key-aliases within a structure may not be consistent in some cases.
47
AWS Command Line Interface User Guide
How to Filter the Output with the --query Option
{
"AZ": "us-west-2a",
"ID": "vol-e11a5288",
"Size": 30
},
{
"AZ": "us-west-2a",
"ID": "vol-2e410a47",
"Size": 8
}
]
In the dictionary notation, you can also use chained keys such as key1.key2[0].key3 to lter
elements deeply nested within the structure. The example below demonstrates this with the
Attachments[0].InstanceId key, aliased to simply InstanceId.
You can also lter multiple elements with the list notation: [key1, key2]. This will format all ltered
attributes into a single ordered list per object, regardless of type.
To lter results by the value of a specic eld, use the JMESPath "?" operator. The following example
query outputs only volumes in the us-west-2a availability zone:
Note
When specifying a literal value such as "us-west-2" above in a JMESPath query expression, you
must surround the value in backticks (`) in order for it to be read properly.
48
AWS Command Line Interface User Guide
JSON Output Format
Combined with the three output formats that will be explained in more detail in the following sections,
the --query option is a powerful tool you can use to customize the content and style of outputs. For
more examples and the full spec of JMESPath, the underlying JSON-processing library, visit http://
jmespath.org/specication.html.
The text output format follows the basic structure shown below. The columns are sorted alphabetically
by the corresponding key names of the underlying JSON object.
We strongly recommend that the text output be used along with the --query option to ensure consistent
behavior. This is because the text format alphabetically orders output columns, and similar resources may
not always have the same collection of keys. For example, a JSON representation of a Linux EC2 instance
may have elements that are not present in the JSON representation of a Windows instance, or vice versa.
Also, resources may have key-value elements added or removed in future updates, altering the column
ordering. This is where --query augments the functionality of the text output to enable complete control
over the output format. In the example below, the command pre-selects which elements to display
and denes the ordering of the columns with the list notation [key1, key2, ...]. This gives users full
condence that the correct key values will always be displayed in the expected column. Finally, notice
how the AWS CLI outputs 'None' as values for keys that don't exist.
Below is an example of how grep and awk can be used along with a text output from aws ec2 describe-
instances command. The rst command displays the Availability Zone, state, and instance ID of each
49
AWS Command Line Interface User Guide
Table Output Format
instance in text output. The second command outputs only the instance IDs of all running instances in
the us-west-2a Availability Zone.
The next command shows a similar example for all stopped instances and takes it one step further to
automate changing instance types for each stopped instance.
The text output is useful in Windows PowerShell as well. Because AWS CLI's text output is tab-delimited,
it is easily split into an array in PowerShell using the `t delimiter. The following command displays the
value of the third column (InstanceId) if the rst column (AvailabilityZone) matches us-west-2a.
50
AWS Command Line Interface User Guide
Table Output Format
The --query option can be used with the table format to display a set of elements pre-selected from the
raw output. Note the output dierences in dictionary and list notations: column names are alphabetically
ordered in the rst example, and unnamed columns are ordered as dened by the user in the second
example.
51
AWS Command Line Interface User Guide
Shorthand Syntax
Structure Parameters
The shorthand syntax in the AWS CLI makes it easier for users to input parameters that are at (non-
nested structures). The format is a comma separate list of key value pairs:
--option key1=value1,key2=value2,key3=value3
Windows PowerShell
--option "key1=value1,key2=value2,key3=value3"
--option '{"key1":"value1","key2":"value2","key3":"value3"}'
There must be no whitespace between each comma-separated key/value pair. Here is an example of the
DynamoDB update-table command with the --provisioned-throughput option specied in shorthand.
List Parameters
Input parameters in a list form can be specied in two ways: JSON and shorthand. The AWS CLI's
shorthand syntax is designed to make it easier to pass in lists with number, string, or non-nested
structures. The basic format is shown here, where values in the list are separated by a single space.
52
AWS Command Line Interface User Guide
Pagination
--option '[value1,value2,value3]'
As previously mentioned, you can specify a list of numbers, a list of strings, or a list of non-nested
structures in shorthand. The following is an example of the stop-instances command for Amazon EC2,
where the input parameter (list of strings) for the --instance-ids option is specied in shorthand.
Next is an example of the Amazon EC2 create-tags command, which takes a list of non-nested
structures for the --tags option. The --resources option species the ID of the instance to be tagged.
This is equivalent to the following example formatted in JSON. The JSON parameter is written in
multiple lines for readability.
By default, the CLI uses a page size of 1000 and retrieves all available items. For example, if you run
aws s3api list-objects on an Amazon S3 bucket containing 3500 objects, the CLI makes four calls to
Amazon S3, handling the service specic pagination logic in the background.
If you see issues when running list commands on a large number of resources, the default page size may
be too high, causing calls to AWS services to time out. You can use the --page-size option to specify
a smaller page size to solve this issue. The CLI will still retrieve the full list, but will perform a larger
number of calls in the background, retrieving a smaller number of items with each call:
To retrieve fewer items, use the --max-items option. The CLI will handle pagination in the same way, but
will only print out the number of items that you specify:
53
AWS Command Line Interface User Guide
Pagination
{
"NextToken": "None___100",
"Contents": [
...
If the number of items output (--max-items) is fewer than the total number of items, the output includes
a NextToken that you can pass in a subsequent command to retrieve the next set of items:
The starting token is a CLI-specic construct that indicates the page token (if any) and the location of the
rst item on that page after the output. For example, when you specify a starting token of None___100
in the above example, the CLI retrieves the rst page of 1000 items and prints out the next set of items
starting with item 100.
After the rst page of items is exhausted, the None is replaced by the service-specic pagination token
that species the current page. You can see this in action by specifying a page-size that is smaller than
the number of items that you retrieve:
The value of the token varies per service. For Amazon S3 it is the name of the item that starts the page.
For other services, like IAM, it may be a randomly generated token:
If the pagination token is not the name of an object, it's possible that the service doesn't return listings
in any guaranteed order. If you specify a next token in the middle of a page, you may see dierent results
that you expect. To prevent this, use the same number for --page-size and --max-items, or retrieve the
whole list and perform any necessary parsing operations locally.
54
AWS Command Line Interface User Guide
DynamoDB
This section provides examples of using the AWS Command Line Interface to access AWS services. These
examples are intended to demonstrate how to use the AWS CLI to perform administrative tasks.
For a complete reference to all of the available commands for each service, see the AWS Command Line
Interface Reference or use the built-in command line help. For more information, see Getting Help with
the AWS Command Line Interface (p. 33).
Topics
Using Amazon DynamoDB with the AWS Command Line Interface (p. 55)
Using Amazon EC2 through the AWS Command Line Interface (p. 57)
Using Amazon Glacier with the AWS Command Line Interface (p. 68)
AWS Identity and Access Management from the AWS Command Line Interface (p. 71)
Using Amazon S3 with the AWS Command Line Interface (p. 74)
Using the AWS Command Line Interface with Amazon SNS (p. 80)
Using Amazon Simple Workow Service with the AWS Command Line Interface (p. 82)
The command line format consists of an Amazon DynamoDB API name, followed by the parameters for
that API. The AWS CLI supports a shorthand syntax for the parameter values, as well as JSON.
For example, the following command will create a table named MusicCollection.
Note
For readability, long commands in this section are broken into separate lines. The backslash
character lets you copy and paste (or type) multiple lines into a Linux terminal. If you are using
a shell that does not use backslash to escape characters, replace the backslash with another
escape character, or remove the backslashes and put the entire command on a single line.
55
AWS Command Line Interface User Guide
DynamoDB
--table-name MusicCollection \
--attribute-definitions \
AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \
--key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
--provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1
The following commands will add new items to the table. These example use a combination of
shorthand syntax and JSON.
On the command line, it can be dicult to compose valid JSON; however, the AWS CLI can read JSON
les. For example, consider the following JSON snippet, which is stored in a le named expression-
attributes.json:
Example expression-attributes.json
{
":v1": {"S": "No One You Know"},
":v2": {"S": "Call Me Today"}
}
You can now issue a Query request using the AWS CLI. In this example, the contents of the expression-
attributes.json le are used for the --expression-attribute-values parameter:
56
AWS Command Line Interface User Guide
Amazon EC2
For more documentation on using the AWS CLI with DynamoDB, go to http://docs.aws.amazon.com/cli/
latest/reference/dynamodb/index.html.
In addition to DynamoDB, you can use the AWS CLI with DynamoDB Local. DynamoDB Local is a small
client-side database and server that mimics the DynamoDB service. DynamoDB Local enables you to
write applications that use the DynamoDB API, without actually manipulating any tables or data in
DynamoDB. Instead, all of the API actions are rerouted to DynamoDB Local. When your application
creates a table or modies data, those changes are written to a local database. This lets you save on
provisioned throughput, data storage, and data transfer fees.
For more information about DynamoDB Local and how to use it with the AWS CLI, see the following
sections of the Amazon DynamoDB Developer Guide:
DynamoDB Local
Using the AWS CLI with DynamoDB Local
Before you run any commands, set your default credentials. For more information, see Conguring the
AWS CLI (p. 17).
For examples of common tasks for Amazon EC2, see the following topics.
Topics
Using Key Pairs (p. 57)
Using Security Groups (p. 59)
Using Amazon EC2 Instances (p. 62)
Topics
57
AWS Command Line Interface User Guide
Using Key Pairs
$ aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text >
MyKeyPair.pem
Note that for Windows PowerShell, the > file redirection defaults to UTF-8 encoding, which cannot be
used with some SSH clients. So, you must explicitly specify ASCII encoding in the out-file command.
> aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text | out-
file -encoding ascii -filepath MyKeyPair.pem
-----BEGINRSAPRIVATEKEY-----
EXAMPLEKEYKCAQEAy7WZhaDsrA1W3mRlQtvhwyORRX8gnxgDAfRt/gx42kWXsT4rXE/b5CpSgie/
vBoU7jLxx92pNHoFnByP+Dc21eyyz6CvjTmWA0JwfWiW5/akH7iO5dSrvC7dQkW2duV5QuUdE0QW
Z/aNxMniGQE6XAgfwlnXVBwrerrQo+ZWQeqiUwwMkuEbLeJFLhMCvYURpUMSC1oehm449ilx9X1F
G50TCFeOzfl8dqqCP6GzbPaIjiU19xX/azOR9V+tpUOzEL+wmXnZt3/nHPQ5xvD2OJH67km6SuPW
oPzev/D8V+x4+bHthfSjR9Y7DvQFjfBVwHXigBdtZcU2/wei8D/HYwIDAQABAoIBAGZ1kaEvnrqu
/uler7vgIn5m7lN5LKw4hJLAIW6tUT/fzvtcHK0SkbQCQXuriHmQ2MQyJX/0kn2NfjLV/ufGxbL1
mb5qwMGUnEpJaZD6QSSs3kICLwWUYUiGfc0uiSbmJoap/GTLU0W5Mfcv36PaBUNy5p53V6G7hXb2
bahyWyJNfjLe4M86yd2YK3V2CmK+X/BOsShnJ36+hjrXPPWmV3N9zEmCdJjA+K15DYmhm/tJWSD9
81oGk9TopEp7CkIfatEATyyZiVqoRq6k64iuM9JkA3OzdXzMQexXVJ1TLZVEH0E7bhlY9d8O1ozR
oQs/FiZNAx2iijCWyv0lpjE73+kCgYEA9mZtyhkHkFDpwrSM1APaL8oNAbbjwEy7Z5Mqfql+lIp1
YkriL0DbLXlvRAH+yHPRit2hHOjtUNZh4Axv+cpg09qbUI3+43eEy24B7G/Uh+GTfbjsXsOxQx/x
p9otyVwc7hsQ5TA5PZb+mvkJ5OBEKzet9XcKwONBYELGhnEPe7cCgYEA06Vgov6YHleHui9kHuws
ayav0elc5zkxjF9nfHFJRry21R1trw2Vdpn+9g481URrpzWVOEihvm+xTtmaZlSp//lkq75XDwnU
WA8gkn6O3QE3fq2yN98BURsAKdJfJ5RL1HvGQvTe10HLYYXpJnEkHv+Unl2ajLivWUt5pbBrKbUC
gYBjbO+OZk0sCcpZ29sbzjYjpIddErySIyRX5gV2uNQwAjLdp9PfN295yQ+BxMBXiIycWVQiw0bH
oMo7yykABY7Ozd5wQewBQ4AdSlWSX4nGDtsiFxWiI5sKuAAeOCbTosy1s8w8fxoJ5Tz1sdoxNeGs
Arq6Wv/G16zQuAE9zK9vvwKBgF+09VI/1wJBirsDGz9whVWfFPrTkJNvJZzYt69qezxlsjgFKshy
WBhd4xHZtmCqpBPlAymEjr/TOlbxyARmXMnIOWIAnNXMGB4KGSyl1mzSVAoQ+fqR+cJ3d0dyPl1j
jjb0Ed/NY8frlNDxAVHE8BSkdsx2f6ELEyBKJSRr9snRAoGAMrTwYneXzvTskF/S5Fyu0iOegLDa
NWUH38v/nDCgEpIXD5Hn3qAEcju1IjmbwlvtW+nY2jVhv7UGd8MjwUTNGItdb6nsYqM2asrnF3qS
VRkAKKKYeGjkpUfVTrW0YFjXkfcrR/V+QFL5OndHAKJXjW7a4ejJLncTzmZSpYzwApc=
-----ENDRSAPRIVATEKEY-----
Your private key is not stored in AWS and can only be retrieved when it is created.
If you're using an SSH client on a Linux computer to connect to your instance, use the following
command to set the permissions of your private key le so that only you can read it.
58
AWS Command Line Interface User Guide
Using Security Groups
EC2 management console or by calling aws ec2 describe-key-pairs. For example, you can view the
ngerprint for MyKeyPair by using the following command:
For more information on keys and ngerprints, see the Amazon EC2 Key Pairs page in the Amazon EC2
User Guide.
You can use the AWS CLI to create, add rules to, and delete your security groups.
Note
Before you try the example commands, set your default credentials.
Topics
Creating a Security Group (p. 59)
Adding Rules to Your Security Group (p. 60)
Deleting Your Security Group (p. 62)
EC2-Classic
The following command creates a security group for EC2-Classic:
To view the initial information for my-sg, use the describe-security-groups command as follows:
59
AWS Command Line Interface User Guide
Using Security Groups
"IpPermissionsEgress": [],
"Description": "My security group"
"IpPermissions": [],
"GroupName": "my-sg",
"OwnerId": "123456789012",
"GroupId": "sg-903004f8"
}
]
}
EC2-VPC
The following command creates a security group named my-sg for the specied VPC:
$ aws ec2 create-security-group --group-name my-sg --description "My security group" --vpc-
id vpc-1a2b3c4d
{
"GroupId": "sg-903004f8"
}
To view the initial information for my-sg, use the describe-security-groups command as follows. Note
that you can't reference a security group for EC2-VPC by name.
60
AWS Command Line Interface User Guide
Using Security Groups
EC2-Classic
The following command adds a rule for RDP to the security group my-sg:
The following command adds a rule for SSH to the security group for my-sg:
EC2-VPC
The following command adds a rule for RDP to the security group with the ID sg-903004f8:
The following command adds a rule for SSH to the security group with the ID sg-903004f8:
61
AWS Command Line Interface User Guide
Using Instances
"IpPermissionsEgress": [
{
"IpProtocol": "-1",
"IpRanges": [
{
"CidrIp": "0.0.0.0/0"
}
],
"UserIdGroupPairs": []
}
],
"Description": "My security group"
"IpPermissions": [
{
"ToPort": 22,
"IpProtocol": "tcp",
"IpRanges": [
{
"CidrIp": "203.0.113.0/24"
}
]
"UserIdGroupPairs": [],
"FromPort": 22
}
],
"GroupName": "my-sg",
"OwnerId": "123456789012",
"GroupId": "sg-903004f8"
}
]
}
EC2-Classic
The following command deletes the security group named my-sg:
EC2-VPC
The following command deletes the security group with the ID sg-903004f8:
If you launch an instance that is not within the Free Usage Tier, you are billed after you launch the
instance and charged for the time that the instance is running, even if it remains idle.
62
AWS Command Line Interface User Guide
Using Instances
Note
Before you try the example command, set your default credentials.
Topics
Launching an Instance (p. 63)
Adding a Block Device Mapping to Your Instance (p. 66)
Adding a Name Tag to Your Instance (p. 66)
Connecting to Your Instance (p. 67)
Listing Your Instances (p. 67)
Terminating Your Instance (p. 67)
Launching an Instance
To launch a single Amazon EC2 instance using the AMI you selected, use the run-instances command.
Depending on the platforms that your account supports, you can launch the instance into EC2-Classic or
EC2-VPC.
Initially, your instance is in the pending state, but will be in the running state in a few minutes.
EC2-Classic
The following command launches a t1.micro instance in EC2-Classic:
63
AWS Command Line Interface User Guide
Using Instances
"InstanceType": "t1.micro",
"NetworkInterfaces": [],
"Placement": {
"Tenancy": "default",
"GroupName": null,
"AvailabilityZone": "us-west-2b"
},
"Hypervisor": "xen",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda1",
"Ebs": {
"Status": "attached",
"DeleteOnTermination": true,
"VolumeId": "vol-877166c8",
"AttachTime": "2013-07-19T02:42:39.000Z"
}
}
],
"Architecture": "x86_64",
"StateReason": {
"Message": "pending",
"Code": "pending"
},
"RootDeviceName": "/dev/sda1",
"VirtualizationType": "hvm",
"RootDeviceType": "ebs",
"Tags": [
{
"Value": "MyInstance",
"Key": "Name"
}
],
"AmiLaunchIndex": 0
}
]
}
EC2-VPC
The following command launches a t1.micro instance in the specied subnet:
64
AWS Command Line Interface User Guide
Using Instances
"EbsOptimized": false,
"LaunchTime": "2013-07-19T02:42:39.000Z",
"PrivateIpAddress": "10.0.1.114",
"ProductCodes": [],
"VpcId": "vpc-1a2b3c4d",
"InstanceId": "i-5203422c",
"ImageId": "ami-173d747e",
"PrivateDnsName": ip-10-0-1-114.ec2.internal,
"KeyName": "MyKeyPair",
"SecurityGroups": [
{
"GroupName": "my-sg",
"GroupId": "sg-903004f8"
}
],
"ClientToken": null,
"SubnetId": "subnet-6e7f829e",
"InstanceType": "t1.micro",
"NetworkInterfaces": [
{
"Status": "in-use",
"SourceDestCheck": true,
"VpcId": "vpc-1a2b3c4d",
"Description": "Primary network interface",
"NetworkInterfaceId": "eni-a7edb1c9",
"PrivateIpAddresses": [
{
"PrivateDnsName": "ip-10-0-1-114.ec2.internal",
"Primary": true,
"PrivateIpAddress": "10.0.1.114"
}
],
"PrivateDnsName": "ip-10-0-1-114.ec2.internal",
"Attachment": {
"Status": "attached",
"DeviceIndex": 0,
"DeleteOnTermination": true,
"AttachmentId": "eni-attach-52193138",
"AttachTime": "2013-07-19T02:42:39.000Z"
},
"Groups": [
{
"GroupName": "my-sg",
"GroupId": "sg-903004f8"
}
],
"SubnetId": "subnet-6e7f829e",
"OwnerId": "123456789012",
"PrivateIpAddress": "10.0.1.114"
}
],
"SourceDestCheck": true,
"Placement": {
"Tenancy": "default",
"GroupName": null,
"AvailabilityZone": "us-west-2b"
},
"Hypervisor": "xen",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda1",
"Ebs": {
"Status": "attached",
"DeleteOnTermination": true,
"VolumeId": "vol-877166c8",
"AttachTime": "2013-07-19T02:42:39.000Z"
65
AWS Command Line Interface User Guide
Using Instances
}
}
],
"Architecture": "x86_64",
"StateReason": {
"Message": "pending",
"Code": "pending"
},
"RootDeviceName": "/dev/sda1",
"VirtualizationType": "hvm",
"RootDeviceType": "ebs",
"Tags": [
{
"Value": "MyInstance",
"Key": "Name"
}
],
"AmiLaunchIndex": 0
}
]
}
To add a block device mapping to your instance, specify the --block-device-mappings option when you
use run-instances.
The following example adds a standard Amazon EBS volume, mapped to /dev/sdf, that's 20 GB in size.
--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"Ebs\":{\"VolumeSize\":20,
\"DeleteOnTermination\":false}}]"
The following example adds an Amazon EBS volume, mapped to /dev/sdf, based on a snapshot. When
you specify a snapshot, it isn't necessary to specify a volume size, but if you do, it must be greater than
or equal to the size of the snapshot.
--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"Ebs\":{\"SnapshotId\":
\"snap-xxxxxxxx\"}}]"
The following example adds two instance store volumes. Note that the number of instance store
volumes available to your instance depends on its instance type.
--block-device-mappings "[{\"DeviceName\":\"/dev/sdf\",\"VirtualName\":\"ephemeral0\"},
{\"DeviceName\":\"/dev/sdg\",\"VirtualName\":\"ephemeral1\"}]"
The following example omits a mapping for a device specied by the AMI used to launch the instance (/
dev/sdj):
--block-device-mappings "[{\"DeviceName\":\"/dev/sdj\",\"NoDevice\":\"\"}]"
For more information, see Block Device Mapping in the Amazon EC2 User Guide for Linux Instances.
66
AWS Command Line Interface User Guide
Using Instances
For more information, see Tagging Your Resources in the Amazon EC2 User Guide for Linux Instances.
When you are nished with the instance, use the terminate-instances command as follows:
67
AWS Command Line Interface User Guide
Amazon Glacier
For more information, see Terminate Your Instance in the Amazon EC2 User Guide for Linux Instances.
Topics
Create an Amazon Glacier Vault (p. 68)
Prepare a File for Uploading (p. 68)
Initiate a Multipart Upload and Upload Files (p. 69)
Complete the Upload (p. 70)
Note
All glacier commands require an account ID parameter. Use a hyphen to specify the current
account.
dd is a utility that copies a number of bytes from an input le to an output le. The above example uses
the device le /dev/urandom as a source of random data. fsutil performs a similar function in Windows:
Windows
68
AWS Command Line Interface User Guide
Initiate a Multipart Upload and Upload Files
Note
HJ-Split is a free le splitter for Windows and many other platforms.
Amazon Glacier requires the size of each part in bytes (1 MiB in this example), your vault name, and
an account ID in order to congure the multipart upload. The AWS CLI outputs an upload ID when the
operation is complete. Save the upload ID to a shell variable for later use.
$ UPLOADID="19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-
OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ"
Windows
Next, use the aws glacier upload-multipart-part command to upload each part.
69
AWS Command Line Interface User Guide
Complete the Upload
Note
The above example uses the dollar sign ("$") to dereference the UPLOADID shell variable. On the
Windows command line, use two percent signs (i.e. %UPLOADID%).
You must specify the byte range of each part when you upload it so it can be reassembled in the proper
order by Amazon Glacier. Each piece is 1048576 bytes, so the rst piece occupies bytes 0-1048575, the
second 1048576-2097151, and the third 2097152-3145727.
The key to calculating a tree hash correctly when using command line utilities is to store each hash in
binary format and only convert to hexadecimal at the last step. Combining or hashing the hexadecimal
version of any hash in the tree will cause an incorrect result.
Note
Windows users can use the type command in place of cat. OpenSSL is available for Windows at
OpenSSL.org.
3. Combine the rst two hashes and take the binary hash of the result.
4. Combine the parent hash of chunks aa and ab with the hash of chunk ac and hash the result, this
time outputing hexadecimal. Store the result in a shell variable.
Finally, complete the upload with the aws glacier complete-multipart-upload command. This
command takes the original le's size in bytes, the nal tree hash value in hexadecimal, and your account
ID and vault name.
70
AWS Command Line Interface User Guide
AWS Identity and Access Management
{
"archiveId": "d3AbWhE0YE1m6f_fI1jPG82F8xzbMEEZmrAlLGAAONJAzo5QdP-
N83MKqd96Unspoa5H5lItWX-sK8-QS0ZhwsyGiu9-R-kwWUyS1dSBlmgPPWkEbeFfqDSav053rU7FvVLHfRc6hg",
"checksum": "9628195fcdbcbbe76cdde932d4646fa7de5f219fb39823836d81f0cc0e18aa67",
"location": "/123456789012/vaults/myvault/archives/
d3AbWhE0YE1m6f_fI1jPG82F8xzbMEEZmrAlLGAAONJAzo5QdP-N83MKqd96Unspoa5H5lItWX-sK8-
QS0ZhwsyGiu9-R-kwWUyS1dSBlmgPPWkEbeFfqDSav053rU7FvVLHfRc6hg"
}
You can also check the status of the vault using aws glacier describe-vault:
It is now safe to remove the part and hash les you created:
$ rm chunk* hash*
For more information on multipart uploads, see Uploading Large Archives in Parts and Computing
Checksums in the Amazon Glacier Developer Guide.
The commands shown here assume that you have set default credentials and a default region.
Topics
Create New IAM Users and Groups (p. 71)
Set an IAM Policy for an IAM User (p. 72)
Set an Initial Password for an IAM User (p. 73)
Create Security Credentials for an IAM User (p. 73)
71
AWS Command Line Interface User Guide
Set an IAM Policy for an IAM User
"Group": {
"GroupName": "MyIamGroup",
"CreateDate": "2012-12-20T03:03:52.834Z",
"GroupId": "AKIAI44QH8DHBEXAMPLE",
"Arn": "arn:aws:iam::123456789012:group/MyIamGroup",
"Path": "/"
}
}
3. Finally, use the add-user-to-group command to add the user to the group.
4. To verify that the MyIamGroup group contains the MyUser, use the get-group command.
You can also view IAM users and groups with the AWS Management Console.
{
"Version": "2012-10-17",
"Statement": [
72
AWS Command Line Interface User Guide
Set an Initial Password for an IAM User
{
"Effect": "Allow",
"NotAction": "iam:*",
"Resource": "*"
}
]
}
Verify the policy has been assigned to the user with the list-user-policies command.
Additional Resources
For more information, see Resources for Learning About Permissions and Policies. This topic provides
links to an overview of permissions and policies and links to examples of policies for accessing Amazon
S3, Amazon EC2, and other services.
Use the update-login-profile command to update the password for an IAM user.
73
AWS Command Line Interface User Guide
Amazon S3
"CreateDate": "2013-01-02T22:44:12.897Z",
"UserName": "MyUser",
"AccessKeyId": "AKIAI44QH8DHBEXAMPLE"
}
}
Use the delete-access-key command to delete a set of credentials for an IAM user. Specify which
credentials to delete by using the access key ID.
The rst tier, named s3, consists of high-level commands for frequently used operations, such as
creating, manipulating, and deleting objects and buckets.
The second tier, named s3api, exposes all Amazon S3 operations, including modifying a bucket access
control list (ACL), using cross-origin resource sharing (CORS), or logging policies. It allows you to carry
out advanced operations that may not be possible with the high-level commands alone.
To get a list of all commands available in each tier, use the help argument with the aws s3 or aws s3api
commands:
$ aws s3 help
or
Note
The AWS CLI supports copying, moving, and syncing from Amazon S3 to Amazon S3. These
operations use the service-side COPY operation provided by Amazon S3: Your les are kept in
the cloud, and are not downloaded to the client machine, then back up to Amazon S3.
When operations such as these can be performed completely in the cloud, only the bandwidth
necessary for the HTTP request and response is used.
For examples of Amazon S3 usage, see the following topics in this section.
Topics
Using High-Level s3 Commands with the AWS Command Line Interface (p. 74)
Using API-Level (s3api) Commands with the AWS Command Line Interface (p. 79)
74
AWS Command Line Interface User Guide
Using High-Level Amazon S3 Commands
Managing Buckets
High-level aws s3 commands support commonly used bucket operations, such as creating, removing,
and listing buckets.
Creating Buckets
Use the aws s3 mb command to create a new bucket. Bucket names must be unique and should be DNS
compliant. Bucket names can contain lowercase letters, numbers, hyphens and periods. Bucket names
can only start and end with a letter or number, and cannot contain a period next to a hyphen or another
period.
$ aws s3 mb s3://bucket-name
Removing Buckets
To remove a bucket, use the aws s3 rb command.
$ aws s3 rb s3://bucket-name
By default, the bucket must be empty for the operation to succeed. To remove a non-empty bucket, you
need to include the --force option.
This will rst delete all objects and subfolders in the bucket and then remove the bucket.
Note
If you are using a versioned bucket that contains previously deletedbut retainedobjects, this
command will not allow you to remove the bucket.
Listing Buckets
To list all buckets or their contents, use the aws s3 ls command. Here are some examples of common
usage.
$ aws s3 ls
CreationTime Bucket
------------ ------
2013-07-11 17:08:50 my-bucket
2013-07-24 14:55:44 my-bucket2
The following command lists all objects and folders (prexes) in a bucket.
$ aws s3 ls s3://bucket-name
Bucket: my-bucket
Prefix:
The following command lists the objects in bucket-name/path (in other words, objects in bucket-name
ltered by the prex path).
75
AWS Command Line Interface User Guide
Using High-Level Amazon S3 Commands
$ aws s3 ls s3://bucket-name/path
Bucket: my-bucket
Prefix: path/
Managing Objects
The high-level aws s3 commands make it convenient to manage Amazon S3 objects as well. The object
commands include aws s3 cp, aws s3 ls, aws s3 mv, aws s3 rm, and sync. The cp, ls, mv, and rm
commands work similarly to their Unix counterparts and enable you to work seamlessly across your local
directories and Amazon S3 buckets. The sync command synchronizes the contents of a bucket and a
directory, or two buckets.
Note
All high-level commands that involve uploading objects into an Amazon S3 bucket (aws s3
cp, aws s3 mv, and aws s3 sync) automatically perform a multipart upload when the object is
large.
Failed uploads cannot be resumed when using these commands. If the multipart upload fails
due to a timeout or is manually cancelled by pressing CTRL+C, the AWS CLI cleans up any les
created and aborts the upload. This process can take several minutes.
If the process is interrupted by a kill command or system failure, the in-progress multipart
upload remains in Amazon S3 and must be cleaned up manually in the AWS Management
Console or with the s3api abort-multipart-upload command.
The cp, mv, and sync commands include a --grants option that can be used to grant permissions on the
object to specied users or groups. You set the --grants option to a list of permissions using following
syntax:
--grants Permission=Grantee_Type=Grantee_ID
[Permission=Grantee_Type=Grantee_ID ...]
Permission Species the granted permissions, and can be set to read, readacl, writeacl, or full.
Grantee_Type Species how the grantee is to be identied, and can be set to uri, emailaddress, or
id.
Grantee_ID Species the grantee based on Grantee_Type.
uri The group's URI. For more information, see Who Is a Grantee?
emailaddress The account's email address.
id The account's canonical ID.
The following example copies an object into a bucket. It grants read permissions on the object
to everyone and full permissions (read, readacl, and writeacl) to the account associated with
[email protected].
To specify a non-default storage class (REDUCED_REDUNDANCY or STANDARD_IA) for objects that you upload
to Amazon S3, use the --storage-class option:
76
AWS Command Line Interface User Guide
Using High-Level Amazon S3 Commands
The sync command has the following form. Possible source-target combinations are:
The following example synchronizes the contents of an Amazon S3 folder named path in my-bucket with
the current working directory. s3 sync updates any les that have a dierent size or modied time than
les with the same name at the destination. The output displays specic operations performed during
the sync. Notice that the operation recursively synchronizes the subdirectory MySubdirectory and its
contents with s3://my-bucket/path/MySubdirectory.
Normally, sync only copies missing or outdated les or objects between the source and target. However,
you may supply the --delete option to remove les or objects from the target not present in the source.
The following example, which extends the previous one, shows how this works.
The --exclude and --include options allow you to specify rules to lter the les or objects to be
copied during the sync operation. By default, all items in a specied directory are included in the
sync. Therefore, --include is only needed when specifying exceptions to the --exclude option (for
example, --include eectively means "don't exclude"). The options apply in the order that is specied, as
demonstrated in the following example.
77
AWS Command Line Interface User Guide
Using High-Level Amazon S3 Commands
MyFile2.rtf
MyFile88.txt
'''
$ aws s3 sync . s3://my-bucket/path --exclude '*.txt'
upload: MyFile2.rtf to s3://my-bucket/path/MyFile2.rtf
'''
$ aws s3 sync . s3://my-bucket/path --exclude '*.txt' --include 'MyFile*.txt'
upload: MyFile1.txt to s3://my-bucket/path/MyFile1.txt
upload: MyFile88.txt to s3://my-bucket/path/MyFile88.txt
upload: MyFile2.rtf to s3://my-bucket/path/MyFile2.rtf
'''
$ aws s3 sync . s3://my-bucket/path --exclude '*.txt' --include 'MyFile*.txt' --exclude
'MyFile?.txt'
upload: MyFile2.rtf to s3://my-bucket/path/MyFile2.rtf
upload: MyFile88.txt to s3://my-bucket/path/MyFile88.txt
The --exclude and --include options can also lter les or objects to be deleted during a sync
operation with the --delete option. In this case, the parameter string must specify les to be excluded
from, or included for, deletion in the context of the target directory or bucket. The following shows an
example.
Assume local directory and s3://my-bucket/path currently in sync and each contains 3 files:
MyFile1.txt
MyFile2.rtf
MyFile88.txt
'''
// Delete local .txt files
$ rm *.txt
// Sync with delete, excluding files that match a pattern. MyFile88.txt is deleted, while
remote MyFile1.txt is not.
$ aws s3 sync . s3://my-bucket/path --delete --exclude 'my-bucket/path/MyFile?.txt'
delete: s3://my-bucket/path/MyFile88.txt
'''
// Delete MyFile2.rtf
$ aws s3 rm s3://my-bucket/path/MyFile2.rtf
The sync command also accepts an --acl option, by which you may set the access permissions for les
copied to Amazon S3. The option accepts private, public-read, and public-read-write values.
As previously mentioned, the s3 command set includes cp, mv, ls, and rm, and they work in similar ways
to their Unix counterparts. The following are some examples.
78
AWS Command Line Interface User Guide
Using API Level (s3api) Commands
// Delete s3://my-bucket/path/MyFile.txt
$ aws s3 rm s3://my-bucket/path/MyFile.txt
When the --recursive option is used on a directory/folder with cp, mv, or rm, the command walks the
directory tree, including all subdirectories. These commands also accept the --exclude, --include, and
--acl options as the sync command does.
Custom ACLs
With high-level commands, you can use the --acl option to apply pre-dened access control lists
(ACLs) on Amazon S3 objects, but you cannot set bucket-wide ACLs. You can do this with the API-
level command, put-bucket-acl. The following example grants full control to two AWS users
([email protected] and [email protected]) and read permission to everyone.
For details about custom ACLs, see PUT Bucket acl. The s3api ACL commands, such as put-bucket-acl,
use the same shorthand argument notation.
Logging Policy
The API command put-bucket-logging congures bucket logging policy. The following example sets
the logging policy for MyBucket. The AWS user [email protected] will have full control over the log
les, and all users will have access to them. Note that the put-bucket-acl command is required to grant
Amazon S3's log delivery system the necessary permissions (write and read-acp).
logging.json
{
"LoggingEnabled": {
"TargetBucket": "MyBucket",
"TargetPrefix": "MyBucketLogs/",
79
AWS Command Line Interface User Guide
Amazon SNS
"TargetGrants": [
{
"Grantee": {
"Type": "AmazonCustomerByEmail",
"EmailAddress": "[email protected]"
},
"Permission": "FULL_CONTROL"
},
{
"Grantee": {
"Type": "Group",
"URI": "http://acs.amazonaws.com/groups/global/AllUsers"
},
"Permission": "READ"
}
]
}
}
Topics
Create a Topic (p. 80)
Subscribe to a Topic (p. 80)
Publish to a Topic (p. 81)
Unsubscribe from a Topic (p. 81)
Delete a Topic (p. 81)
Create a Topic
The following command creates a topic named my-topic:
Make a note of the TopicArn, which you will use later to publish a message.
Subscribe to a Topic
The following command subscribes to a topic using the email protocol and an email address for the
notication endpoint:
80
AWS Command Line Interface User Guide
Publish to a Topic
An email message will be sent to the email address listed in the subscribe command. The email message
will have the following text:
After clicking Conrm subscription, a "Subscription conrmed!" notication message should appear in
your browser with information similar to the following:
Subscription confirmed!
Publish to a Topic
The following command publishes a message to a topic:
An email message with the text "Hello World!" will be sent to [email protected]
Delete a Topic
The following command deletes a topic:
81
AWS Command Line Interface User Guide
Amazon SWF
For a list of commands and how to work with domains in Amazon SWF, see the following topics.
Topics
List of Amazon SWF Commands by Category (p. 82)
Working with Amazon SWF Domains Using the AWS Command Line Interface (p. 84)
For an alphabetic list of commands, see the Amazon SWF section of the AWS Command Line Interface
Reference, or use the following command.
To get help for a particular command, use the help directive after the command name. The following
shows an example.
Topics
Commands Related to Activities (p. 82)
Commands Related to Deciders (p. 83)
Commands Related to Workow Executions (p. 83)
Commands Related to Administration (p. 83)
Visibility Commands (p. 84)
poll-for-activity-task
respond-activity-task-completed
respond-activity-task-failed
82
AWS Command Line Interface User Guide
List of Amazon SWF Commands
respond-activity-task-canceled
record-activity-task-heartbeat
poll-for-decision-task
respond-decision-task-completed
request-cancel-workow-execution
start-workow-execution
signal-workow-execution
terminate-workow-execution
Activity Management
register-activity-type
deprecate-activity-type
Workow Management
register-workow-type
deprecate-workow-type
Domain Management
register-domain
deprecate-domain
For more information and examples of these domain management commands, see Working with
Amazon SWF Domains Using the AWS Command Line Interface (p. 84).
83
AWS Command Line Interface User Guide
Working with Amazon SWF Domains
Visibility Commands
Although you can perform visibility actions from the Amazon SWF console, you can use the commands in
this section to build your own console or administrative tools.
Activity Visibility
list-activity-types
describe-activity-type
Workow Visibility
list-workow-types
describe-workow-type
Domain Visibility
list-domains
describe-domain
For more information and examples of these domain visibility commands, see Working with Amazon
SWF Domains Using the AWS Command Line Interface (p. 84).
Topics
Listing Your Domains (p. 85)
Getting Information About a Domain (p. 86)
Registering a Domain (p. 86)
Deprecating a Domain (p. 87)
See Also (p. 88)
84
AWS Command Line Interface User Guide
Working with Amazon SWF Domains
Note
For an example of using DEPRECATED, see Deprecating a Domain (p. 87). As you might guess, it
returns any deprecated domains you have.
Note
The nextPageToken that is returned to you will be much longer. This value is merely an example
for illustrative purposes.
When you make the call again, this time supplying the value of nextPageToken in the --next-page-token
argument, you'll get another page of results:
85
AWS Command Line Interface User Guide
Working with Amazon SWF Domains
}
]
}
When there are no further pages of results to retrieve, nextPageToken will not be returned in the results.
Registering a Domain
To register new domains, use swf register-domain. There are two required parameters, --name, which
takes the domain name, and --workflow-execution-retention-period-in-days, which takes an integer
to specify the number of days to retain workow execution data on this domain, up to a maximum
period of 90 days (for more information, see the Amazon SWF FAQ). If you specify zero (0) for this value,
the retention period is automatically set at the maximum duration. Otherwise, workow execution data
will not be retained after the specied number of days have passed.
When you register a domain, nothing is returned (""), but you can use swf list-domains or swf
describe-domain to see the new domain. For example:
86
AWS Command Line Interface User Guide
Working with Amazon SWF Domains
Deprecating a Domain
To deprecate a domain (you can still see it, but cannot create new workow executions or register types
on it), use swf deprecate-domain. It has a sole required parameter, --name, which takes the name of the
domain to deprecate.
As with register-domain, no output is returned. If you use list-domains to view the registered domains,
however, you will see that the domain no longer appears among them.
You can see deprecated domains by using --registration-status DEPRECATED with list-domains.
You can also use describe-domain to get information about a deprecated domain.
87
AWS Command Line Interface User Guide
Working with Amazon SWF Domains
See Also
deprecate-domain in the AWS Command Line Interface Reference
describe-domain in the AWS Command Line Interface Reference
list-domains in the AWS Command Line Interface Reference
register-domain in the AWS Command Line Interface Reference
88