Reputation: 105
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.
Upvotes: 0
Views: 3308
Reputation: 238847
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)
Upvotes: 1