Skip to main content
deleted 19 characters in body; edited tags
Source Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

I was hoping to get a quick review of a script I wrote for retrieving AWS VPC Subnet information. Any and all ideas welcome. I am looking specifically for logic enhancements, and optimizations to make the code more pythonic. Also, I was initially constructing a dictionary, however I had to adjust since many of the aws values have "-" hyphens. :-( Thank you in advance! 

One note - I am using two spaces vs. four due to internal standards.

I was hoping to get a quick review of a script I wrote for retrieving AWS VPC Subnet information. Any and all ideas welcome. I am looking specifically for logic enhancements, and optimizations to make the code more pythonic. Also, I was initially constructing a dictionary, however I had to adjust since many of the aws values have "-" hyphens. :-( Thank you in advance! One note - I am using two spaces vs. four due to internal standards.

I was hoping to get a quick review of a script I wrote for retrieving AWS VPC Subnet information. Any and all ideas welcome. I am looking specifically for logic enhancements, and optimizations to make the code more pythonic. Also, I was initially constructing a dictionary, however I had to adjust since many of the aws values have "-" hyphens. :-( 

One note - I am using two spaces vs. four due to internal standards.

added 790 characters in body
Source Link
fr00z1
  • 514
  • 4
  • 14

I was hoping to get a quick review of a script I wrote for retrieving AWS VPC Subnet information. Any and all ideas welcome. I am looking specifically for logic enhancements, and optimizations to make the code more pythonic. Also, I was initially constructing a dictionary, however I had to adjust since many of the aws values have "-" hyphens. :-( Thank you in advance! One note - I am using two spaces vs. four due to internal standards.

#!/usr/bin/env python
# encoding: utf-8

import argparse
import logging
import string
import sys

from boto import vpc, exception
from boto.exception import EC2ResponseError

from lib.aws_utilaws_location import check_configLocationData
from lib.aws_locationaws_util import LocationDatacheck_config


def get_subnets(connection, vpc_id):
  """Function that returns all subnets within a given AWS VPC.
  :connection: AWS Connection.
  :vpc_id: VPC Identifier.

  """
  return connection.get_all_subnets(filters={'vpc_id': vpc_id}) 


def mainformat_data(region, vpc_id, vpc_subnet, subnets):
  parser"""Function =that argparseoutputs region data based on template.ArgumentParser( 

  :region: EC2 Region.
  :vpc_id: VPC Identifier.
  description='Script:vpc_subnet: forSubnet obtainingallocated to VPC.
 Subnet information:subnets: Subnets defined within VPC.'
  
  todo:: Serialization. (yaml/json)
  """
  with open('vpc_subnets.tmpl') as f:
  parser  templ = string.add_argumentTemplate("-d",f.read())

 "--debug", help="Enableregion_dict debug= messages",{}
  region_dict['region'] = region
  region_dict['vpc_id'] = vpc_id
  region_dict['vpc_subnet'] = vpc_subnet
  region_dict['subnets'] = ', '.join(subnets)

  print templ.safe_substitute(region_dict)


def parse_args():
  parser = argparse.ArgumentParser(
     action="store_true" description='Script for obtaining VPC Subnet information.') 

  group = parser.add_mutually_exclusive_group()

  group.add_argument("-v"d", "--verbose"debug",
      help="Enable verbosedebug messages",
         action="store_true")

  group.add_argument("-v", "--verbose",
      help="Enable verbose messages",
      action="store_true")

  args = parser.parse_args()

  if args.debug:
    logging.basicConfig(level=logging.DEBUG)
  elif args.verbose:
    logging.basicConfig(level=logging.INFO)
  else:
    logging.basicConfig(level=logging.CRITICAL)

def main():
  parse_args()

  try:
    check_config()
  except EnvironmentError as e:
    print("Error: Could not open config file: {}".format(e))
    sys.exit(1)

  loc = LocationData()

  for region in loc.get_regions():
    try:
      print "Region:", region
      connection = vpc.connect_to_region(region)
      for vpc_blockvpc_raw in loc.get_vpcs_raw(connection):
        vpc_id = str(vpc_blockvpc_raw).split(':')[1]
        print "\tVPC:", vpc_id
        print "\tVPC Subnet:"
        printsubnets "\t-",= vpc_block.cidr_block[]
        print "\t\tSubnets:"
       for subnetssubnet_id =in get_subnets(connection, vpc_id):
        for subnet in subnets:
 .append(subnet_id.cidr_block)    
      printformat_data(region, "\t\t-"vpc_id, subnetvpc_raw.cidr_block, subnets)
    except exception.EC2ResponseError as e:
      logging.error("EC2Error: {}".format(e))
      nextcontinue

if __name__ == '__main__':
  main()

I was hoping to get a quick review of a script I wrote for retrieving AWS VPC Subnet information. Any and all ideas welcome. I am looking specifically for logic enhancements, and optimizations to make the code more pythonic. Also, I was initially constructing a dictionary, however I had to adjust since many of the aws values have "-" hyphens. :-( Thank you in advance!

#!/usr/bin/env python
# encoding: utf-8

import argparse
import logging
import sys

from boto import vpc, exception
from boto.exception import EC2ResponseError

from lib.aws_util import check_config
from lib.aws_location import LocationData


def get_subnets(connection, vpc_id):
  """Function that returns all subnets within a given AWS VPC."""
  return connection.get_all_subnets(filters={'vpc_id': vpc_id})

def main():
  parser = argparse.ArgumentParser(
          description='Script for obtaining VPC Subnet information.'
          )
  parser.add_argument("-d", "--debug", help="Enable debug messages",
                          action="store_true")
  parser.add_argument("-v", "--verbose", help="Enable verbose messages",
                          action="store_true")

  args = parser.parse_args()

  if args.debug:
    logging.basicConfig(level=logging.DEBUG)
  elif args.verbose:
    logging.basicConfig(level=logging.INFO)
  else:
    logging.basicConfig(level=logging.CRITICAL)


  try:
    check_config()
  except EnvironmentError as e:
    print("Error: Could not open config file: {}".format(e))
    sys.exit(1)

  loc = LocationData()

  for region in loc.get_regions():
    try:
      print "Region:", region
      connection = vpc.connect_to_region(region)
      for vpc_block in loc.get_vpcs_raw(connection):
        vpc_id = str(vpc_block).split(':')[1]
        print "\tVPC:", vpc_id
        print "\tVPC Subnet:"
        print "\t-", vpc_block.cidr_block
        print "\t\tSubnets:"
        subnets = get_subnets(connection, vpc_id)
        for subnet in subnets:
          print "\t\t-", subnet.cidr_block
    except EC2ResponseError as e:
      logging.error("EC2Error: {}".format(e))
      next

if __name__ == '__main__':
  main()

I was hoping to get a quick review of a script I wrote for retrieving AWS VPC Subnet information. Any and all ideas welcome. I am looking specifically for logic enhancements, and optimizations to make the code more pythonic. Also, I was initially constructing a dictionary, however I had to adjust since many of the aws values have "-" hyphens. :-( Thank you in advance! One note - I am using two spaces vs. four due to internal standards.

#!/usr/bin/env python
# encoding: utf-8

import argparse
import logging
import string
import sys

from boto import vpc, exception

from lib.aws_location import LocationData
from lib.aws_util import check_config


def get_subnets(connection, vpc_id):
  """Function that returns all subnets within a given AWS VPC.
  :connection: AWS Connection.
  :vpc_id: VPC Identifier.

  """
  return connection.get_all_subnets(filters={'vpc_id': vpc_id}) 


def format_data(region, vpc_id, vpc_subnet, subnets):
  """Function that outputs region data based on template. 

  :region: EC2 Region.
  :vpc_id: VPC Identifier.
  :vpc_subnet: Subnet allocated to VPC.
  :subnets: Subnets defined within VPC.
 
  todo:: Serialization. (yaml/json)
  """
  with open('vpc_subnets.tmpl') as f:
    templ = string.Template(f.read())

  region_dict = {}
  region_dict['region'] = region
  region_dict['vpc_id'] = vpc_id
  region_dict['vpc_subnet'] = vpc_subnet
  region_dict['subnets'] = ', '.join(subnets)

  print templ.safe_substitute(region_dict)


def parse_args():
  parser = argparse.ArgumentParser(
      description='Script for obtaining VPC Subnet information.') 

  group = parser.add_mutually_exclusive_group()

  group.add_argument("-d", "--debug",
      help="Enable debug messages",
      action="store_true")

  group.add_argument("-v", "--verbose",
      help="Enable verbose messages",
      action="store_true")

  args = parser.parse_args()

  if args.debug:
    logging.basicConfig(level=logging.DEBUG)
  elif args.verbose:
    logging.basicConfig(level=logging.INFO)
  else:
    logging.basicConfig(level=logging.CRITICAL)

def main():
  parse_args()

  try:
    check_config()
  except EnvironmentError as e:
    print("Error: Could not open config file: {}".format(e))
    sys.exit(1)

  loc = LocationData()

  for region in loc.get_regions():
    try:
      connection = vpc.connect_to_region(region)
      for vpc_raw in loc.get_vpcs_raw(connection):
        vpc_id = str(vpc_raw).split(':')[1]
        subnets = []
        for subnet_id in get_subnets(connection, vpc_id):
          subnets.append(subnet_id.cidr_block)    
      format_data(region, vpc_id, vpc_raw.cidr_block, subnets)
    except exception.EC2ResponseError as e:
      logging.error("EC2Error: {}".format(e))
      continue

if __name__ == '__main__':
  main()
Source Link
fr00z1
  • 514
  • 4
  • 14

Gets AWS VPC subnet info

I was hoping to get a quick review of a script I wrote for retrieving AWS VPC Subnet information. Any and all ideas welcome. I am looking specifically for logic enhancements, and optimizations to make the code more pythonic. Also, I was initially constructing a dictionary, however I had to adjust since many of the aws values have "-" hyphens. :-( Thank you in advance!

#!/usr/bin/env python
# encoding: utf-8

import argparse
import logging
import sys

from boto import vpc, exception
from boto.exception import EC2ResponseError

from lib.aws_util import check_config
from lib.aws_location import LocationData


def get_subnets(connection, vpc_id):
  """Function that returns all subnets within a given AWS VPC."""
  return connection.get_all_subnets(filters={'vpc_id': vpc_id})

def main():
  parser = argparse.ArgumentParser(
          description='Script for obtaining VPC Subnet information.'
          )
  parser.add_argument("-d", "--debug", help="Enable debug messages",
                          action="store_true")
  parser.add_argument("-v", "--verbose", help="Enable verbose messages",
                          action="store_true")

  args = parser.parse_args()

  if args.debug:
    logging.basicConfig(level=logging.DEBUG)
  elif args.verbose:
    logging.basicConfig(level=logging.INFO)
  else:
    logging.basicConfig(level=logging.CRITICAL)


  try:
    check_config()
  except EnvironmentError as e:
    print("Error: Could not open config file: {}".format(e))
    sys.exit(1)

  loc = LocationData()

  for region in loc.get_regions():
    try:
      print "Region:", region
      connection = vpc.connect_to_region(region)
      for vpc_block in loc.get_vpcs_raw(connection):
        vpc_id = str(vpc_block).split(':')[1]
        print "\tVPC:", vpc_id
        print "\tVPC Subnet:"
        print "\t-", vpc_block.cidr_block
        print "\t\tSubnets:"
        subnets = get_subnets(connection, vpc_id)
        for subnet in subnets:
          print "\t\t-", subnet.cidr_block
    except EC2ResponseError as e:
      logging.error("EC2Error: {}".format(e))
      next

if __name__ == '__main__':
  main()