Search code examples
python-3.xamazon-web-servicesamazon-ec2boto3

Find an EC2 instance by its IP in boto3


I want to find an EC2 instance using its public and private IPs. In CLI it can be done through:

aws ec2 describe-instances --filter Name=ip-address,Values=IP_1,..IP_N

However, I am looking for a way to do this using boto3 in Python:

import boto3
ec2 = boto3.resource("ec2")
for instance in ec2.instances.all():
    # if instance.ip['private'] == '1.2.3.4': # Something like this.

Solution

  • One better option is to use Filters on the ec2 client describe_instances method. Variety of filters available is listed here

    This is the reference for ec2 boto3

    Sample code that I tried

    ec2_client = self.get_ec2_client(aws_credentials)
    ec2_client.describe_instances(Filters=[{
                    'Name': 'private-ip-address',
                    'Values': [
                        '10.273.117.10',
                    ]
                }
                ])
    
     def get_ec2_client(self, aws_credentials):
            client = boto3.client('ec2', aws_access_key_id=aws_credentials["aws_access_key_id"],
                                  aws_secret_access_key=aws_credentials["aws_secret_access_id"])
            return client