How to control EC2 instances using the AWS Command Line Interface

Learn how to manage AWS EC2 instances using the Command Line Interface (CLI) by starting, stopping, and terminating instances with ease.

The AWS Management Console is the first interface that everyone uses to get started with AWS but is not the only one. If your account has programmatic access enabled you can use as well the AWS CLI (Command Line Interface). The CLI interacts directly with the AWS API and authorizes operations through your Access Keys. Those operations can be performed without being logged on the AWS Management Console and chances are that you will perform simple operations way faster.

In this post, we will see how to control EC2 instance lifecycle using the command line. Before continuing, be sure to enable programmatic access and install the AWS CLI interface on your desktop.

List EC2 instances

To list your EC2 instance type:

aws ec2 describe-instances

The command will return, a JSON object that contains the complete information of each instance. The output is quite long and we are interested only in knowing the "InstanceId" field. The --query parameter tells the backend to return only the instance name (encapsulated in the "Tags" array) and the corresponding Id.

aws ec2 describe-instances --query 'Reservations[*].Instances[*].[Tags[*],InstanceId]' --output text

The --output text parameter returns the output in a more compact and human-readable string:

i-01234abc56b01aaaa

Name my-instance-1

i-01234abc56b01bbbb

Name my-instance-2

Start/Stop EC2 instances

The "InstanceId" is a unique string that identifies an EC2 instance and we will need to change the instance state.

A running instance can be stopped:

aws ec2 stop-instances --instance-ids <i-01234abc56b01aaaa> --output text

The command output will show the current and the previous instance state. Similarly, a stopped instance can be resumed using:

aws ec2 start-instances --instance-ids <i-01234abc56b01aaaa> --output text

Terminating EC2 instances

Be careful, this command will destroy your EC2 instance without confirmation dialogs!

$ aws ec2 terminate-instances --instance-ids <i-01234abc56b01aaaa> --output text

Conclusions

In this post, we have learned how to start, stop and terminate AWS EC2 instances using the AWS CLI.

References

Did you find this article valuable?

Support Marco's blog by becoming a sponsor. Any amount is appreciated!