简体   繁体   中英

How to find ec2 instances running under particular VPC using boto3

I am trying to create a script which does curl on one of my many instances running under a particular VPC ID.

Let say, I have VPC ID. Then how can i get the list of all ec2 instances running under this VPC and eventually how to find the particular ec2 instance named "test-ec2". And then run a command eg. "curl ip_address_of_test-ec2"

I have never used boto3, so do not know much about it.

Any suggestions what can be done to resolve this.

You can use describe-instances and its --filters of vpc-id and tag:key for name.

For example, to get all instances ids in a given vpc:

aws ec2 describe-instances \
  --filters Name=vpc-id,Values=<your-vpc-id> \
  --query 'Reservations[].Instances[].InstanceId' \
  --output text

Also to filter by name:

aws ec2 describe-instances \
  --filters Name=vpc-id,Values=<your-vpc-id> \
            Name=tag:Name,Values=<instance-name> \
  --query 'Reservations[].Instances[].InstanceId' \
  --output text

In boto3, the equivalent function is describe_instances :

ec2 = boto3.client('ec2')

r = ec2.describe_instances(Filters=[
        {
            'Name': 'vpc-id',
            'Values': ['<your-vpc-id>']
        },
        {
            'Name': 'tag:Name',
            'Values': ['<instance-name>']
        }  
    ])

for reservation in r['Reservations']:
  for instance in reservation['Instances']:
    private_ip_addr = instance['PrivateIpAddress']
    print(private_ip_addr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM