Python Forum
Try for multiple values - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Try for multiple values (/thread-16611.html)



Try for multiple values - bluethundr - Mar-06-2019

Guys,

I need to build a list of AWS instances in all the accounts.

Some of the instance that are stopped have no private IP address. And some have public ip adresses, but not others. My code depends on whether or not those values are set.

So far I am accounting for what happens if there is no private ip address with a try statement. How can I alter this so that I add a try if the Public IP is set?

Here is my code so far:

#!usr/bin/env python

import boto3
import collections
from collections import defaultdict
import time
from datetime import datetime
from colorama import init, deinit, Fore, Back, Style
from termcolor import colored
init()

print(Fore.CYAN)
print('******************************************************')
print('             List AWS Instances')
print('******************************************************\n')

print(Fore.YELLOW)
aws_account = input("Enter the name of the AWS account you'll be working in: ")
# Connect to EC2
session = boto3.Session(profile_name=aws_account)
ec2 = session.client('ec2')
ec2info = defaultdict()
response = ec2.describe_instances()
for reservation in response["Reservations"]:
    for instance in reservation["Instances"]:
        try:
            private_ip = instance['PrivateIpAddress']
        except:
            ## Print instances with no private IP
            ec2info[instance['InstanceId']] = {
            'Instance ID': instance['InstanceId'],
            'Type': instance['InstanceType'],
            'State': instance['State']['Name']
        }
            attributes = ['Instance ID', 'Type', 'State' ]
            for instance_id, instance in ec2info.items():
                print(Fore.RESET + "-------------------------------------")
                for key in attributes:
                    print(Fore.CYAN + "{0}: {1}".format(key, instance[key]))
                print(Fore.RESET + "-------------------------------------")
        else:
                ec2info[instance['InstanceId']] = {
                'Instance ID': instance['InstanceId'],
                'Type': instance['InstanceType'],
                'State': instance['State']['Name'],
                'Private IP': instance['PrivateIpAddress'],
            }
                attributes = ['Instance ID', 'Type', 'State', 'Private IP']
                for instance_id, instance in ec2info.items():
                    print(Fore.RESET + "-------------------------------------")
                    for key in attributes:
                        print(Fore.CYAN + "{0}: {1}".format(key, instance[key]))
                    print(Fore.RESET + "-------------------------------------")
As mentioned it tests for the presense of a private IP. And I want to also test if a public ip exists for the instance.

Thanks


RE: Try for multiple values - bluethundr - Mar-07-2019

Apparently this is better handled as an if statement. However I am having trouble dealing with dictionary keys that are missing.

I get the following error when the code runs into a stopped AWS instance that does not have a Public IP address:

Error:
------------------------------------- Instance ID: i-86533615 Type: m4.xlarge State: stopped Private IP: 10.1.233.18 Traceback (most recent call last): File ".\aws_ec2_list_instances.py", line 43, in <module> print(Fore.CYAN + "{0}: {1}".format(key, instance[key])) KeyError: 'Public IP'
Here is my code:
#!usr/bin/env python

import boto3
import collections
from collections import defaultdict
import time
from datetime import datetime
from colorama import init, deinit, Fore, Back, Style
init()

print(Fore.CYAN)
print('******************************************************')
print('             Terminate AWS Instances', 'blue')
print('******************************************************\n')

print(Fore.YELLOW)
aws_account = input("Enter the name of the AWS account you'll be working in: ")

session = boto3.Session(profile_name=aws_account)
ec2 = session.client('ec2')
response = ec2.describe_instances()
ec2info = defaultdict()
for reservation in response["Reservations"]:
    for instance in reservation["Instances"]:
        instance_state = instance['State']['Name']
        if 'PrivateIpAddress' in instance and 'PublicIpAddress' in instance:
            launch_time = instance['LaunchTime']
            launch_time_friendly = launch_time.strftime("%B %d %Y")
            ec2info[instance['InstanceId']] = {
                'Instance ID': instance['InstanceId'],
                'Type': instance['InstanceType'],
                'State': instance_state,
                'Private IP': instance['PrivateIpAddress'],
                'Public IP': instance['PublicIpAddress'],
                'Launch Time' : launch_time_friendly
            }
            attributes = ['Instance ID', 'Type',
                            'State', 'Private IP', 'Public IP', 'Launch Time' ]
            for instance_id, instance in ec2info.items():
                print(Fore.RESET + "-------------------------------------")
                for key in attributes:
                    print(Fore.CYAN + "{0}: {1}".format(key, instance[key]))
                print(Fore.RESET + "-------------------------------------")
        elif 'PrivateIpAddress' in instance:
            launch_time = instance['LaunchTime']
            launch_time_friendly = launch_time.strftime("%B %d %Y")
            ec2info[instance['InstanceId']] = {
                'Instance ID': instance['InstanceId'],
                'Type': instance['InstanceType'],
                'State': instance_state,
                'Private IP': instance['PrivateIpAddress'],
                'Launch Time' : launch_time_friendly
            }
            attributes = ['Instance ID', 'Type',
                            'State', 'Private IP', 'Launch Time' ]
            for instance_id, instance in ec2info.items():
                print(Fore.RESET + "-------------------------------------")
                for key in attributes:
                    print(Fore.CYAN + "{0}: {1}".format(key, instance[key]))
                print(Fore.RESET + "-------------------------------------")
        else:
            launch_time = instance['LaunchTime']
            launch_time_friendly = launch_time.strftime("%B %d %Y")
            ec2info[instance['InstanceId']] = {
                'Instance ID': instance['InstanceId'],
                'Type': instance['InstanceType'],
                'State': instance_state,
                'Launch Time' : launch_time_friendly
            }
            attributes = ['Instance ID', 'Type',
                            'State', 'Launch Time' ]
            for instance_id, instance in ec2info.items():
                print(Fore.RESET + "-------------------------------------")
                for key in attributes:
                    print(Fore.CYAN + "{0}: {1}".format(key, instance[key]))
                print(Fore.RESET + "-------------------------------------")
How can I control the output in the case of stopped instances that don't have either a public IP or a private IP address?