Bottom Page

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
Quote
#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?
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Save all values to pandas of multiple classes jenniferruurs 0 81 Sep-13-2019, 12:10 PM
Last Post: jenniferruurs
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 302 Mar-20-2019, 08:01 PM
Last Post: stillsen
  Get multiple values from function and total it. nirlep 5 538 Feb-05-2019, 06:54 AM
Last Post: nirlep
  multiple values as parameters to POST command.. onenessboy 17 2,292 Feb-25-2018, 09:57 AM
Last Post: onenessboy
  comparing multiple values Skaperen 5 4,999 Dec-06-2017, 03:25 AM
Last Post: wavic
  'soup.findAll()' help - Want to retrieve multiple attribute values MattRHope 1 8,403 Jul-29-2017, 11:35 PM
Last Post: metulburr
  How to return multiple values from function in python pikkip 2 1,935 Jan-23-2017, 06:00 AM
Last Post: pikkip
  Check if multiple values exist in a list glidecode 6 15,525 Oct-06-2016, 10:21 PM
Last Post: glidecode
  Class method returning multiple values,dont know which is returned when.. ujjwalrathod007 4 1,926 Oct-03-2016, 08:29 PM
Last Post: ujjwalrathod007

Forum Jump:


Users browsing this thread: 1 Guest(s)