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


Messages In This Thread
Try for multiple values - by bluethundr - Mar-06-2019, 10:36 PM
RE: Try for multiple values - by bluethundr - Mar-07-2019, 09:04 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  __init__() got multiple values for argument 'schema' dawid294 4 2,397 Jan-03-2024, 09:42 AM
Last Post: buran
  How to combine multiple column values into 1? cubangt 15 2,868 Aug-11-2022, 08:25 PM
Last Post: cubangt
  Function - Return multiple values tester_V 10 4,466 Jun-02-2021, 05:34 AM
Last Post: tester_V
  Xlsxwriter: Create Multiple Sheets Based on Dataframe's Sorted Values KMV 2 3,506 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,881 Sep-15-2020, 01:42 PM
Last Post: rajesh3383
  Assigning multiple values using tuple sivacg 2 2,285 Aug-06-2020, 10:29 PM
Last Post: perfringo
  How to pass multiple values from one sample to nc variable? Baloch 0 1,871 Jun-01-2020, 09:27 PM
Last Post: Baloch
  Inserting values from multiple lists sqlite azulu 1 2,509 May-24-2020, 08:40 AM
Last Post: ibreeden
  UnUnloading values from multiple widgets in a container UGuntupalli 3 2,759 Apr-20-2020, 08:53 PM
Last Post: UGuntupalli
  Save all values to pandas of multiple classes jenniferruurs 0 1,904 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