Mar-06-2019, 10:36 PM
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:
Thanks
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