Reputation: 43
I'm having a hard time trying to figure out how to make the code below to take InstanceID as parameter and display info only about this instance:
import boto3
ec2_client = boto3.client('ec2')
instance_data = []
instanceid = 'i-123456'
def get_instace_data(instanceid):
reservations = ec2_client.describe_instances()
for reservation in reservations['Reservations']:
for instance in reservation['Instances']:
instance_data.append(
{
'instanceId': instance['InstanceId'],
'instanceType': instance['InstanceType'],
'launchDate': instance['LaunchTime'].strftime('%Y-%m-%dT%H:%M:%S.%f')
}
)
print(instance_data)
get_instace_data(instanceid)
My understanding is that get_instance_data() should be taking the instance ID and display only info for that instance, even though it iterates to the whole 'Reservations' dict that returned.
Am i missing something here?
Thanks in advance!
Upvotes: 0
Views: 1921
Reputation: 13176
describe_instance() let you specify filters, however, the syntax can be quite confusing. Because you can specify instance ID inside the Filters parameter or inside InsanceIds parameter.
e.g.
# method 1
response = client.describe_instances(
InstanceIds=[
'i-123456',
],
)
# method 2
response = client.describe_instances(
Filters=[
{
'Name': 'instance-id',
'Values': ['i-123456']
},
],
)
The documentation showing Filters (list) is utterly confusing, because the only way to pass in the correct filtering name into the list, you must embrace the "Name" and "Value" explicitly inside a dict.
# This will not works
response = client.describe_instances(
Filters=[
'instance-id:i-123456'
])
# Neither will this!
response = client.describe_instances(
Filters=[
{'instance-id': ['i-123456']}
])
Upvotes: 1
Reputation: 1895
Your code will append all instances to the instance_data
.
In order to receive only required instance you need change
reservations = ec2_client.describe_instances()
To the following:
reservations = ec2_client.describe_instances(
Filters=
InstanceIds=['i-123456'])
Upvotes: 2