Bootstrap FreeKB - Amazon Web Services (AWS) - Stop an EC2 instance using the AWS CLI
Amazon Web Services (AWS) - Stop an EC2 instance using the AWS CLI


This assumes you have already configured the aws command line tool. If not, check out my article on Getting Started with the AWS CLI.

The aws ec2 describe-instances command can be used to list your EC2 instances.

aws ec2 describe-instances

 

--filter can be used to only return the JSON for an specific instance.

aws ec2 describe-instances --filters "Name=tag:Name,Values=my-instance"

 

Something like this should be returned (this is just a small subset of the output that would be returned). Notice in this example that the EC2 ID is i-09112345cf1abcdd2.

{
    "Reservations": [
        {
            "Instances": [
                {
                    "AmiLaunchIndex": 0,
                    "ImageId": "ami-09d123474b6cabcda",
                    "InstanceId": "i-09112345cf1abcdd2",
                    "InstanceType": "t2.micro",
                    "KeyName": "aws",
                    "LaunchTime": "2022-11-06T09:23:52+00:00",
                    "Tags": [
                        {
                            "Key": "Name",
                            "Value": "my-instance"
                        }
                    ]
                }
            ]
        }
    ]
}

 

The aws ec2 stop-instances command can be used to stop one or more EC2 instances. Something like this should be returned, where CurrentState is stopping.

~]$ aws ec2 stop-instances --instance-ids i-09112345cf1abcdd2
{
    "StoppingInstances": [
        {
            "CurrentState": {
                "Code": 64,
                "Name": "stopping"
            },
            "InstanceId": "i-09112345cf1abcdd2",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}

 

You can then re-issue the aws ec2 describe-instances command and the State should be stopped.

{
    "Reservations": [
        {
            "Instances": [
                {
                    "AmiLaunchIndex": 0,
                    "ImageId": "ami-09d123474b6cabcda",
                    "InstanceId": "i-09112345cf1abcdd2",
                    "InstanceType": "t2.micro",
                    "KeyName": "aws",
                    "LaunchTime": "2022-11-06T09:23:52+00:00",
                    "State": {
                        "Code": 80,
                        "Name": "stopped"
                    }
                }
            ]
        }
    ]
}

 

You can stop more than one instance in a single command.

aws ec2 stop-instances --instance-ids i-0f9a8d82897695a66 i-0182deb20171e5945

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter af2fa7 in the box below so that we can be sure you are a human.