Created
May 24, 2019 16:37
-
-
Save phwelo/762a1927a1e5cdc1197cea04497193c7 to your computer and use it in GitHub Desktop.
Python script to describe a Security Group from AWS and convert it into HCL markup. Not the entire file, but the rules only
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# Purpose of script: | |
# Convert a security group to HCL | |
import boto3 | |
client = boto3.client('ec2') | |
def describe_sg(security_group): | |
response = client.describe_security_groups( | |
GroupIds=[ | |
security_group, | |
] | |
) | |
# Since we only give it one ID, we know only one result | |
return response['SecurityGroups'][0] | |
def output_fromport(fromport): | |
return ' from_port = ' + str(fromport) | |
def output_toport(toport): | |
return ' to_port = ' + str(toport) | |
def output_protocol(ip_protocol): | |
return ' protocol = \'' + str(ip_protocol) + '\'' | |
def output_iprange(ip_range): | |
return ' cidr_block = [' + ip_range + ']' | |
def output_ip_description(ip_range_obj): | |
return ' description = \'' + ip_range_obj['Description'] + '\'' | |
def output_cidr_block(ip_ranges): | |
return ' cidr_blocks = ' + str(ip_ranges) | |
def output_sg_rules(sg_rules): | |
return ' security_groups = ' + str(sg_rules) | |
def main(): | |
for rule in describe_sg('sg-73186d08')['IpPermissions']: | |
described = False | |
print(' ingress {') | |
if 'FromPort' in rule: | |
print(output_fromport(rule['FromPort'])) | |
if 'ToPort' in rule: | |
print(output_toport(rule['ToPort'])) | |
print(output_protocol(rule['IpProtocol'])) | |
if len(rule['IpRanges']) > 0: | |
ip_ranges = [] | |
for range in rule['IpRanges']: | |
ip_ranges.append(range['CidrIp']) | |
if not described: | |
print(output_ip_description(range)) | |
described = True | |
print(output_cidr_block(ip_ranges)) | |
if len(rule['UserIdGroupPairs']) > 0: | |
sg_rules = [] | |
for pair in rule['UserIdGroupPairs']: | |
sg_rules.append(pair['GroupId']) | |
print(output_sg_rules(sg_rules)) | |
if 'Description' in pair: | |
print(' description = \'' + pair['Description'] + '\'') | |
# print(' description = \'' + pair['Description']) + '\'' | |
print('},') | |
print(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment