/
main.go
90 lines (74 loc) · 1.82 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"bufio"
"fmt"
"net/url"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func WriteFile(path string, text string) error {
f, err := os.Create(path)
if err != nil {
return err
}
w := bufio.NewWriter(f)
w.WriteString(text)
w.Flush()
f.Close()
return nil
}
func WritePolicyToFile(policy *iam.Policy) {
document := DecodePolicy(GetPolicyDocument(policy))
fmt.Print(document)
path := "policy/" + *policy.PolicyName + ".json"
WriteFile(path, document)
}
func DecodePolicy(text string) string {
text, _ = url.QueryUnescape(text)
return text
}
func ListPolicies() []*iam.Policy {
sess := session.Must(session.NewSession())
svc := iam.New(sess)
params := &iam.ListPoliciesInput{
MaxItems: aws.Int64(1000),
OnlyAttached: aws.Bool(false),
Scope: aws.String("All"),
}
resp, err := svc.ListPolicies(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return nil
}
// Pretty-print the response data.
fmt.Println(resp)
return resp.Policies
}
func GetPolicyDocument(policy *iam.Policy) string {
sess := session.Must(session.NewSession())
svc := iam.New(sess)
params := &iam.GetPolicyVersionInput{
PolicyArn: aws.String(*policy.Arn), // Required
VersionId: aws.String(*policy.DefaultVersionId), // Required
}
resp, err := svc.GetPolicyVersion(params)
if err != nil {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
return ""
}
// Pretty-print the response data.
//fmt.Println(resp)
return *resp.PolicyVersion.Document
}
func main() {
policies := ListPolicies()
for _, policy := range policies {
WritePolicyToFile(policy)
}
}