Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Try for multiple values
#1
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
Reply
#2
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?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  __init__() got multiple values for argument 'schema' dawid294 4 1,893 Jan-03-2024, 09:42 AM
Last Post: buran
  How to combine multiple column values into 1? cubangt 15 2,633 Aug-11-2022, 08:25 PM
Last Post: cubangt
  Function - Return multiple values tester_V 10 4,320 Jun-02-2021, 05:34 AM
Last Post: tester_V
  Xlsxwriter: Create Multiple Sheets Based on Dataframe's Sorted Values KMV 2 3,442 Mar-09-2021, 12:24 PM
Last Post: KMV
  Looking for help in Parse multiple XMLs and update key node values and generate Out.. rajesh3383 0 1,847 Sep-15-2020, 01:42 PM
Last Post: rajesh3383
  Assigning multiple values using tuple sivacg 2 2,225 Aug-06-2020, 10:29 PM
Last Post: perfringo
  How to pass multiple values from one sample to nc variable? Baloch 0 1,838 Jun-01-2020, 09:27 PM
Last Post: Baloch
  Inserting values from multiple lists sqlite azulu 1 2,452 May-24-2020, 08:40 AM
Last Post: ibreeden
  UnUnloading values from multiple widgets in a container UGuntupalli 3 2,698 Apr-20-2020, 08:53 PM
Last Post: UGuntupalli
  Save all values to pandas of multiple classes jenniferruurs 0 1,875 Sep-13-2019, 12:10 PM
Last Post: jenniferruurs

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020