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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…