I have 1 list instance ID from s3 and i want to check each instance ID from s3 with instance ID from EC2 services for check ec2 exist. Could you help advise to me some solution ? Thanks
def lambda_handler(event, context):
#Get all ec2 information - The current list in AWS
ins_inf = ec2_client.describe_instances()
for reservation in ins_inf['Reservations']:
for ins_cur in reservation['Instances']:
#Get all instance ID from ec2
ins_cur_id = ins_cur["InstanceId"]
#Get instance ID list from s3
for ins_f_s3 in line_stream(s3_objload.get()['Body']):
#Remove /n
ins_f_s3_re=ins_f_s3.strip()
#Compare instance ID from s3 with current instance ID in aws
if ins_cur_id == ins_f_s3_re:
print (ins_f_s3_re ' found')
else:
print(ins_f_s3_re ' not found in aws ')
And This is result
i-0a959c122fd51581e not found in aws
i-0a959c122fd51581f not found in aws
i-0a959c122fd51581e found
i-0a959c122fd51581f not found in aws
Maybe you can see "i-0a959c122fd51581e" show 2 message when compare. It not correct. Can someone help me this case ? Thnk so much
CodePudding user response:
Pre-read your list of EC2 instances of interest from S3 and store them in a list. Then simply test each instance ID returned from the DescribeInstances call to see if it's in the S3 list (much as @jordanm suggests in the above comment).
s3_list = [x.strip() for x in line_stream(s3_objload.get()['Body'])]
ins_inf = ec2_client.describe_instances()
for reservation in ins_inf['Reservations']:
for ins_cur in reservation['Instances']:
# Get instance ID from ec2
ins_cur_id = ins_cur["InstanceId"]
if ins_cur_id in s3_list:
print(ins_cur_id ' found')
else:
print(ins_cur_id ' not found')