
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"
}
}
]
}
]
}
The aws ec2 terminate-instances command can then be used to terminate (delete) the EC2 instance.
~]$ aws ec2 terminate-instances --instance-id i-09112345cf1abcdd2
{
"TerminatingInstances": [
{
"CurrentState": {
"Code": 48,
"Name": "terminated"
},
"InstanceId": "i-0839ae934c1298530",
"PreviousState": {
"Code": 80,
"Name": "stopped"
}
}
]
}
You can then re-issue the aws ec2 describe-instances command and the State should be terminated. Be aware that it will take about 1 hour for the instance to complete it's termination.
{
"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": 48,
"Name": "terminated"
}
}
]
}
]
}
Did you find this article helpful?
If so, consider buying me a coffee over at