Skip to content

Instantly share code, notes, and snippets.

@tadeck
Forked from fengler/LICENSE.txt
Last active October 28, 2016 14:52
Show Gist options
  • Save tadeck/c0832db8c212177b6f3a to your computer and use it in GitHub Desktop.
Save tadeck/c0832db8c212177b6f3a to your computer and use it in GitHub Desktop.
sg-creator
sg-creator.py generates JSON to describe Security Group rules using a Security Group csv file.
This method simplifies collaboration in creating and documentation of Security Groups. It speeds up the tedious process of creating rules and decreases the potential for typographical errors since the data only has to be entered once.
To generate the .csv file, import the security-group-template.csv to a Google Docs spreadsheet and compile ingress and egress rules.
To fill in the template correctly, follow these rules:
- in the ingress or egress column, enter either ingress or egress
- in the CidrIp column, enter the source or destination Cidr block or enter "sg" if the rule references a Security Group
- enter an 'x' and no other characters to choose which protocol(s) the rule applies to
- leave blank if the rule does not apply to the protocol
From Google Docs, download as csv.
Run the sg-creator inputting (-i) the .csv file and outputting (-o) a filename of your choice. The resulting file will be the Ingress and Egress Properties of your Security Group resource. For example:
sg-creator.py -i sample.csv -o sample.template -g Nazwa
Limitations:
sg-creator cannot check for dependencies between Security Groups so if they reference each other, you may be required to create a separate ingress or egress resource that modifies the base group.
sg-creator will create a rule that references itself since the version in this branch is unaware of the name of the resource to which it will be added.
The MIT License (MIT)
Copyright (c) [2013] [Fanya Engler]
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
ingress or egress CidrIp FromPort ToPort TCP UDP ICMP SecurityGroup
ingress 10.0.0.0/24 22 22 x
ingress 10.0.10.0/24 137 138 x
egress 10.0.20.0/24 25 25 x
egress 10.0.30.0/24 389 389 x x
ingress 10.0.40.0/24 -1 -1 x
egress 10.0.40.0/24 -1 -1 x
ingress sg 443 443 x SampleSecGr1
egress sg 443 443 x x SampleSecGr2
#!/usr/bin/env python
#import modules
import argparse
import csv
import json
#parse the arguments
parser = argparse.ArgumentParser(description="generates JSON to describe Security Group rules from a Security Group csv")
parser.add_argument("-i", "--input", help="the csv file created from spreadsheet")
parser.add_argument("-o", "--output", help="name the template file for JSON output")
parser.add_argument("-g", "--groupcolumn", help="name of the column containing group name")
args = parser.parse_args()
sg_csvfile = args.input
outfile = open(args.output, 'w')
#create Ingress and Egress lists
lists = {}
#open csv file and read each row as dictionary
sg_file = open(sg_csvfile, 'rb')
sg_reader = csv.DictReader(sg_file)
#write a new rule with a Cidr block reference
def new_rule(listname):
listname.append({'CidrIp':sg_dict['CidrIp'],
'FromPort':sg_dict['FromPort'],
"IpProtocol": proto,
'ToPort':sg_dict['ToPort']})
#write a new rule with Security Group reference
def new_sg_rule(listname, sg_ref):
if sg_dict['SecurityGroup']=='self':
print "**Additional resources necessary** You must use a base Security Group and add a resource for Ingress or Egress for a Security Group to reference itself."
else:
listname.append({sg_ref:sg_dict['SecurityGroup'],
'FromPort':sg_dict['FromPort'],
"IpProtocol": proto,
'ToPort':sg_dict['ToPort']})
def iter_properties(lists):
"""Iterate over nested dictionary with properties"""
for group_name, group_props in lists.items():
yield group_props['Properties']
def clean_ingress_egress(lists):
props_to_clean = ['SecurityGroupEgress', 'SecurityGroupIngress']
for properties in iter_properties(lists):
for prop in props_to_clean:
if not properties.get(prop) and prop in properties:
del properties[prop]
return lists
#iterate through rows checking for protocols
for sg_dict in sg_reader:
group_def = lists.setdefault(sg_dict[args.groupcolumn], {
'Type': 'AWS::EC2::SecurityGroup',
'Properties': {
'GroupDescription': sg_dict[args.groupcolumn],
},
})
vpc_id = sg_dict['VpcId']
if vpc_id:
group_def['Properties']['VpcId'] = vpc_id
direction = sg_dict['ingress or egress']
list_to_append = {
'ingress': group_def['Properties'].setdefault('SecurityGroupIngress', []),
'egress': group_def['Properties'].setdefault('SecurityGroupEgress', []),
}[direction]
params = {'listname': list_to_append}
if sg_dict['CidrIp'] == 'sg':
rule_func = new_sg_rule
params['sg_ref'] = 'SourceSecurityGroupId' if direction == 'ingress' else 'DestinationSecurityGroupId'
else:
rule_func = new_rule
protocols_map = {
'ICMP': '-1',
'TCP': 'tcp',
'UDP': 'udp',
}
for protocol in protocols_map:
# check each protocol and issue proper rule function if marked
if sg_dict[protocol] == 'x':
proto = protocols_map[protocol]
rule_func(**params)
#create a text file and write the Security Group rules to it
outfile.write(json.dumps({'AWSTemplateFormatVersion': '2010-09-09', 'Resources': clean_ingress_egress(lists)}, sort_keys=True, indent=4))
outfile.close()
print "done writing " + args.output
ingress or egress CidrIp FromPort ToPort TCP UDP ICMP VpcId SecurityGroup Nazwa
ingress 0.0.0.0/0 80 80 x vpc-45ftg testhttp
ingress 1.2.3.4/32 111 112 x vpc-45ftg testgroup
ingress sg 0 65535 x x x vpc-45ftg id-38921 testgroup
ingress 4.3.2.1/32 2000 2010 x x x vpc-89ytr test2group
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment