Created
October 5, 2018 14:48
-
-
Save VannaDii/f9e7cc3e16929425597a40028b560a90 to your computer and use it in GitHub Desktop.
Transforms AWS CLI JSON output from Describe Security Groups into variable driven Terraform definition.
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
const fs = require('fs'); | |
/* | |
File contains the output of: | |
"aws ec2 describe-security-groups --filters Name=vpc-id,Values=<vpc_id> --output json" | |
This could also be an AWS SDK invocation | |
*/ | |
const data = fs.readFileSync('./data.json'); | |
const json = JSON.parse(data); | |
function groupToRef(groupId) { | |
let match = json.SecurityGroups.find(sg => sg.GroupId === groupId); | |
if (match) match = `$\{aws_security_group.${match.GroupName.replace(/[^a-zA-Z]/g, '').toLowerCase()}.id}`; | |
return match || groupId | |
} | |
const seenCidrs = [] | |
function translateCidr(cidr) { | |
if (cidr === '0.0.0.0/0') { | |
return cidr; | |
} | |
let index = seenCidrs.indexOf(cidr); | |
if (index < 0) { | |
index = seenCidrs.push(cidr); | |
} | |
return `$\{var.known_cidr_${index + 1}}`; | |
} | |
function gressBlock(ipp) { | |
return ` ingress { | |
from_port = "${ipp.FromPort || '0'}" | |
to_port = "${ipp.ToPort || '0'}" | |
protocol = "${ipp.IpProtocol}"${ipp.IpRanges.length > 0 ? `\n cidr_blocks = [${ipp.IpRanges.map(ipr => `"${translateCidr(ipr.CidrIp)}"`).join(", ")}]` : ''}${ipp.UserIdGroupPairs.length > 0 ? `\n security_groups = [${ipp.UserIdGroupPairs.map(ugp => `"${groupToRef(ugp.GroupId)}"`).join(", ")}]` : ''} | |
self = true | |
}`; | |
} | |
let terraSgs = json.SecurityGroups.sort((a, b) => a.GroupName.localeCompare(b.GroupName)).map(sg => { | |
let name = sg.GroupName.replace(/[^a-zA-Z]/g, '').toLowerCase(); | |
return `resource "aws_security_group" "${name}" { | |
name = "provata-$\{var.environment}-${name}-sg" | |
description = "${sg.Description}" | |
vpc_id = "$\{aws_vpc.vpc.id}" | |
depends_on = ["aws_vpc.vpc"] | |
${sg.IpPermissions.map(gressBlock).join('\n')} | |
${sg.IpPermissionsEgress.map(gressBlock).join('\n')} | |
tags { | |
Name = "$\{var.environment}-${name}" | |
Environment = "$\{var.environment}" | |
} | |
}`; | |
}).join('\n'); | |
let cidrVars = seenCidrs.sort().map((cidr, index) => `variable "known_cidr_${index + 1}" { | |
type = "string" | |
default = "${cidr}" | |
description = "A known CIDR used in one or more security groups." | |
}`).join('\n'); | |
console.log(cidrVars); | |
console.log(terraSgs); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment