Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

python - 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.

question from:https://stackoverflow.com/questions/66057931/how-to-find-ec2-instances-running-under-particular-vpc-using-boto3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...