Skip to content

Instantly share code, notes, and snippets.

@ErikHarmon
Last active February 5, 2016 15:18
Show Gist options
  • Save ErikHarmon/f4d75db953f553a40dff to your computer and use it in GitHub Desktop.
Save ErikHarmon/f4d75db953f553a40dff to your computer and use it in GitHub Desktop.
Create AWS security group egress rules for AWS API access, using Ansible
#!/usr/bin/python
import json
import sys
# take json from stdin, from source such as https://ip-ranges.amazonaws.com/ip-ranges.json
# and turn it into an AWS security group using Ansible
region = 'us-east-1'
header_str = """---
- hosts: 127.0.0.1
connection: local
gather_facts: no
tasks:"""
task_str =""" - name: Create AWS {} API access security group
ec2_group:
name: "aws-{}-api"
description: "AWS {} API access"
vpc_id: "{{{{vpc_id}}}}"
region: "{{{{region}}}}"
purge_rules_egress: true
rules_egress:"""
rule_str = """ - proto: tcp
from_port: 443
to_port: 443
cidr_ip: "{}" """
obj = json.load(sys.stdin)
print header_str
apilist = [ 'AMAZON', 'EC2' ]
for api in apilist:
print task_str.format(api,api,api)
cnt = 0
for o in obj['prefixes']:
if o['region'] == region and o['service'] == api:
cnt += 1
if cnt < 50:
print rule_str.format(o['ip_prefix'])
else:
sys.stderr.write('exceeded 50 rules for aws-{}-api\n'.format(api))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment