Deepali Mittal
Deepali Mittal

Reputation: 1032

Unable to print "Unknown" if a AWS instance is not having a name tag associated using Python

Below is a little code snippet of a program i wrote which gets all instance ip and instance tags associated with it. I can easily do this using boto , my problem is if i find a AWS instance which is not having any tag name associated with it i want to display/write in file "ip UNKNOWN".

for reservation in reservations: 
  for instances in reservation.instances: 
    if instances.state == "running": 
     print instances.private_ip_address,instances.tags['Name'] 
     fileCSV.write("%s %s\n"%(instances.private_ip_address,instances.tags['Name'])) 
    if instances.state == "running" and 'Name' in instances.tags==' ': 
     print "%s %s" % (instances.private_ip_address,"UNKNOWN") 
     fileCSV.write("%s %s\n"%(instances.private_ip_address,"UNKNOWN")

This code prints something like this

192.124.121.17
192.124.121.11 squid-server
192.124.121.13 apache

I am expecting :

192.124.121.17 UNKNOWN
192.124.121.11 squid-server
192.124.121.13 apache

Upvotes: 2

Views: 58

Answers (2)

helloV
helloV

Reputation: 52433

I didn't test this, but this should work.

for reservation in reservations: 
  for instances in reservation.instances: 
    if instances.state == "running": 
     print instances.private_ip_address, instances.tags['Name'] if instances.tags['Name'] else 'UNKNOWN'

Upvotes: 1

Avihoo Mamka
Avihoo Mamka

Reputation: 4786

It seems that your code always catches the first if block.

You can try use the default value dictionary option in the get method.

Try this:

for reservation in reservations: 
  for instances in reservation.instances: 
    if instances.state == "running": 
        name = instances.tags["Name"] if instances.tags["Name"] != "" else "UNKNOWN"
        print instances.private_ip_address,name
        fileCSV.write("%s %s\n" % (instances.private_ip_address,name))

Upvotes: 1

Related Questions