forked from awsdocs/aws-doc-sdk-examples
/
GetPublicKeys.go
95 lines (80 loc) · 2.74 KB
/
GetPublicKeys.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
91
92
93
94
95
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
// snippet-start:[iam.go.get_public_keys]
package main
// snippet-start:[iam.go.get_public_keys.imports]
import (
"flag"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/iam/iamiface"
)
// snippet-end:[iam.go.get_public_keys.imports]
// GetPublicKeyBodies retrieves the bodies of the user's public SSH keys
// Inputs:
// svc is an IAM service client
// userName is the name of an IAM user
// Output:
// If success, the list of public SSH key bodies and nil
// Otherwise, nil and an error from the call to ListSSHPublicKeys
func GetPublicKeyBodies(svc iamiface.IAMAPI, userName *string) ([]*string, error) {
// snippet-start:[iam.go.get_public_keys.call]
var bodies []*string
result, err := svc.ListSSHPublicKeys(&iam.ListSSHPublicKeysInput{
UserName: userName,
})
// snippet-end:[iam.go.get_public_keys.call]
if err != nil {
return bodies, err
}
// snippet-start:[iam.go.get_public_keys.bodies]
for _, key := range result.SSHPublicKeys {
// Get an SSH public key.
keyResult, err := svc.GetSSHPublicKey(&iam.GetSSHPublicKeyInput{
UserName: userName,
SSHPublicKeyId: key.SSHPublicKeyId,
Encoding: aws.String("SSH"),
})
if err != nil {
continue
}
// append to list
bodies = append(bodies, keyResult.SSHPublicKey.SSHPublicKeyBody)
// snippet-end:[iam.go.get_public_keys.bodies]
}
return bodies, nil
}
func main() {
// snippet-start:[iam.go.get_public_keys.args]
userName := flag.String("u", "", "The name of the user")
flag.Parse()
if *userName == "" {
fmt.Println("You must supply the name of a user (-u USER-NAME)")
return
}
// snippet-end:[iam.go.get_public_keys.args]
// snippet-start:[iam.go.get_public_keys.session]
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := iam.New(sess)
// snippet-end:[iam.go.get_public_keys.session]
bodies, err := GetPublicKeyBodies(svc, userName)
if err != nil {
fmt.Println("Got an error retrieving the public keys:")
fmt.Println(err)
return
}
if len(bodies) < 1 {
fmt.Println("User " + *userName + " had no public SSH keys")
return
}
fmt.Println("Public SSH key bodies for " + *userName)
for _, body := range bodies {
fmt.Printf(*body)
fmt.Println("")
}
}
// snippet-end:[iam.go.get_public_keys]