|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "flag" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + |
| 8 | + "github.com/aws/aws-sdk-go/aws" |
| 9 | + "github.com/aws/aws-sdk-go/aws/session" |
| 10 | + "github.com/aws/aws-sdk-go/service/iam" |
| 11 | +) |
| 12 | + |
| 13 | +var policyArn = "arn:aws:iam::aws:policy/AdministratorAccess" |
| 14 | +var assumeRoleDocument = `{ |
| 15 | + "Version": "2012-10-17", |
| 16 | + "Statement": [ |
| 17 | + { |
| 18 | + "Effect": "Allow", |
| 19 | + "Principal": { |
| 20 | + "AWS": "arn:aws:iam::%s:root" |
| 21 | + }, |
| 22 | + "Action": "sts:AssumeRole" |
| 23 | + } |
| 24 | + ] |
| 25 | +}` |
| 26 | + |
| 27 | +func main() { |
| 28 | + var account, role string |
| 29 | + |
| 30 | + flag.StringVar(&account, "a", "", "Account to trust") |
| 31 | + flag.StringVar(&role, "r", "", "Role name to create") |
| 32 | + flag.Parse() |
| 33 | + |
| 34 | + if account == "" { |
| 35 | + fmt.Printf("Must specify account option\n") |
| 36 | + os.Exit(0) |
| 37 | + } |
| 38 | + |
| 39 | + if role == "" { |
| 40 | + fmt.Printf("Must specify role name option\n") |
| 41 | + os.Exit(0) |
| 42 | + } |
| 43 | + |
| 44 | + sess := session.Must(session.NewSession()) |
| 45 | + svc := iam.New(sess) |
| 46 | + |
| 47 | + // First see if the role already exists |
| 48 | + params := &iam.GetRoleInput{ |
| 49 | + RoleName: aws.String(role), |
| 50 | + } |
| 51 | + _, err := svc.GetRole(params) |
| 52 | + if err == nil { |
| 53 | + fmt.Printf("Role %s already exists\n", role) |
| 54 | + os.Exit(0) |
| 55 | + } |
| 56 | + |
| 57 | + // Make sure the policy exists before creating the role |
| 58 | + policyParams := &iam.GetPolicyInput{ |
| 59 | + PolicyArn: aws.String(policyArn), |
| 60 | + } |
| 61 | + _, err = svc.GetPolicy(policyParams) |
| 62 | + if err != nil { |
| 63 | + fmt.Printf("Policy %s does not exist: %v\n", policyArn, err) |
| 64 | + os.Exit(0) |
| 65 | + } |
| 66 | + |
| 67 | + // Create the role with a trust policy document |
| 68 | + assumeRoleString := fmt.Sprintf(assumeRoleDocument, account) |
| 69 | + roleParams := &iam.CreateRoleInput{ |
| 70 | + AssumeRolePolicyDocument: aws.String(assumeRoleString), |
| 71 | + RoleName: aws.String(role), |
| 72 | + } |
| 73 | + roleOutput, err := svc.CreateRole(roleParams) |
| 74 | + if err != nil { |
| 75 | + fmt.Printf("Cannot create role %s\n", err) |
| 76 | + os.Exit(0) |
| 77 | + } |
| 78 | + |
| 79 | + // Attach the role policy onto the role |
| 80 | + _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ |
| 81 | + PolicyArn: aws.String(policyArn), |
| 82 | + RoleName: aws.String(role), |
| 83 | + }) |
| 84 | + if err != nil { |
| 85 | + fmt.Printf("AttachRolePolicy failed: %v\n", err) |
| 86 | + os.Exit(0) |
| 87 | + } |
| 88 | + |
| 89 | + fmt.Printf("Role %s created - ARN: %s\n", role, *roleOutput.Role.Arn) |
| 90 | +} |
0 commit comments