const fs = require('fs'); /* File contains the output of: "aws ec2 describe-security-groups --filters Name=vpc-id,Values= --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);