How to terminate EC2 instance by IP from terminal

Here’s an quick command line shortcut to terminate an AWS EC2 instance if you know the private IP address but not the instance ID.

# Function to terminate EC2 instance by IP
function terminate_instance(){
  instance_id=$(aws ec2 describe-instances            \
    --filter Name=private-ip-address,Values=$1        \
    --query "Reservations[].Instances[].[InstanceId]" \
    --output text)

  aws ec2 terminate-instances --instance-ids $instance_id

# Usage
# $ terminate_instance <private IP address>

# Example
# $ terminate_instance

This shortcut often saves me visits to the EC2 Dashboard 😄

Leave a Comment