0

i have a easy question. I need to show, if ip address exists or if ip address does not exists in simple condition. Little part of my code:

for i in ec2.instances.all():
    if i.public_ip_address == '192.168.1.1':
        print('yes')
    else:
        print('no')

But please look, if i am starting script, i have:

no
no
yes
no
no
no
no
no
no
no

So ... It is going to check all list of ip addresses. But i need only one checking. I want to receive result 'yes' or 'no'. How to do in this situation ? Thanks for help.

Piduna
  • 501
  • 3
  • 10
  • 23

1 Answers1

0

This is easily solved by declaring a flag variable and setting it to a desired value once the IP is found.

ip_found = False
for instance in ec2.instances.all():
    if i.public_ip_address == '192.168.1.1':
        ip_found = True
if ip_found:
    print('yes')
else:
    print('no')

This code sets the ip_found flag only once (after initialisation) - when it actually matches '192.168.1.1'.