Skip to content

Instantly share code, notes, and snippets.

@aerostitch
Created September 16, 2017 01:08
Show Gist options
  • Save aerostitch/77c8a47e35f8724d682c6f91403a2943 to your computer and use it in GitHub Desktop.
Save aerostitch/77c8a47e35f8724d682c6f91403a2943 to your computer and use it in GitHub Desktop.
This script export all the security groups (not the stale ones) and corresponding rules to the stdout in a csv format
package main
// This script export all the security groups (not the stale ones) and corresponding rules to the stdout in a csv format
// Quickn dirty version
import (
"fmt"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"log"
)
func computeTags(tagsInput []*ec2.Tag) *string {
res := ""
for _, tag := range tagsInput {
res += *tag.Key + " " + *tag.Value + ";"
}
return &res
}
func main() {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := ec2.New(sess)
result, err := svc.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{})
if err != nil {
log.Fatalf("Unable to get descriptions for security groups, %v\n", err)
}
fmt.Printf("Account,Vpc,Group,Protocol,FromPort,ToPort,IPv4,IPv6,TargetSecurityGroups,Description,Tags\n")
for _, group := range result.SecurityGroups {
groupTags := computeTags(group.Tags)
vpc := ""
if group.VpcId != nil {
vpc = *group.VpcId
}
for _, perm := range group.IpPermissions {
fromPort := ""
if perm.FromPort != nil {
fromPort = fmt.Sprintf("%d", *perm.FromPort)
}
toPort := ""
if perm.ToPort != nil {
toPort = fmt.Sprintf("%d", *perm.ToPort)
}
ipProtocol := ""
if perm.IpProtocol != nil {
ipProtocol = *perm.IpProtocol
}
ipRanges := ""
for _, ip := range perm.IpRanges {
ipRanges += *ip.CidrIp + " "
}
ip6Ranges := ""
for _, ip := range perm.Ipv6Ranges {
ip6Ranges += *ip.CidrIpv6 + " "
}
targetSg := ""
for _, sg := range perm.PrefixListIds {
targetSg += *sg.PrefixListId + " "
}
fmt.Printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,\"%s\",\"%s\"\n", *group.OwnerId, vpc, *group.GroupId, ipProtocol, fromPort, toPort, ipRanges, ip6Ranges, targetSg, *group.Description, *groupTags)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment