forked from cyberark/summon-aws-secrets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
91 lines (77 loc) · 2.55 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
91
package main
import (
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/secretsmanager"
)
func RetrieveSecret(variableName string) {
// All clients require a Session. The Session provides the client with
// shared configuration such as region, endpoint, and credentials. A
// Session should be shared where possible to take advantage of
// configuration and credential caching. See the session package for
// more information.
sess, err := session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
})
if err != nil {
printAndExit(err)
}
// AWS Go SDK does not currently support automatic fetching of region from ec2metadata.
// If the region could not be found in an environment variable or a shared config file,
// create metaSession to fetch the ec2 instance region and pass to the regular Session.
if *sess.Config.Region == "" {
metaSession, err := session.NewSession()
if err != nil {
printAndExit(err)
}
metaClient := ec2metadata.New(metaSession)
// If running on an EC2 instance, the metaClient will be available and we can set the region to match the instance
// If not on an EC2 instance, the region will remain blank and AWS returns a "MissingRegion: ..." error
if metaClient.Available() {
if region, err := metaClient.Region(); err == nil {
sess.Config.Region = aws.String(region)
} else {
printAndExit(err)
}
}
}
// Create a new instance of the service's client with a Session.
// Optional aws.Config values can also be provided as variadic arguments
// to the New function. This option allows you to provide service
// specific configuration.
svc := secretsmanager.New(sess)
// Get secret value
req, resp := svc.GetSecretValueRequest(&secretsmanager.GetSecretValueInput{
SecretId: aws.String(variableName),
})
err = req.Send()
if err != nil { // resp is now filled
printAndExit(err)
}
var secretBytes []byte
if resp.SecretString != nil {
secretBytes = []byte(*resp.SecretString)
} else {
secretBytes = resp.SecretBinary
}
os.Stdout.Write(secretBytes)
}
func main() {
if len(os.Args) != 2 {
os.Stderr.Write([]byte("A variable name or version flag must be given as the first and only argument!"))
os.Exit(-1)
}
singleArgument := os.Args[1]
switch singleArgument {
case "-v","--version":
os.Stdout.Write([]byte(VERSION))
default:
RetrieveSecret(singleArgument)
}
}
func printAndExit(err error) {
os.Stderr.Write([]byte(err.Error()))
os.Exit(1)
}