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()