-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaws-mfa-auth.go
68 lines (54 loc) · 1.88 KB
/
aws-mfa-auth.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
package main
import (
"flag"
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
)
func getTempCredentials(profileName string, tokenCode string, mfaSerial string) (*sts.Credentials, error) {
// Create a session with the specified profile
sess, err := session.NewSessionWithOptions(session.Options{
Profile: profileName,
})
if err != nil {
return nil, err
}
// Get an STS client using the session
svc := sts.New(sess)
// Get temporary credentials using the STS client and MFA token code
params := &sts.GetSessionTokenInput{
DurationSeconds: aws.Int64(3600),
SerialNumber: aws.String(mfaSerial),
TokenCode: aws.String(tokenCode),
}
resp, err := svc.GetSessionToken(params)
if err != nil {
return nil, err
}
// Return the temporary credentials
return resp.Credentials, nil
}
func main() {
// Parse command line arguments
profileName := flag.String("profile", "", "Name of the AWS CLI profile to use")
tokenCode := flag.String("token", "", "MFA token code")
mfaSerial := flag.String("mfa-serial", "", "ARN of the MFA device")
flag.Parse()
// Get temporary credentials
tempCreds, err := getTempCredentials(*profileName, *tokenCode, *mfaSerial)
if err != nil {
fmt.Println(err)
return
}
// Set environment variables with the temporary credentials
os.Setenv("AWS_ACCESS_KEY_ID", *tempCreds.AccessKeyId)
os.Setenv("AWS_SECRET_ACCESS_KEY", *tempCreds.SecretAccessKey)
os.Setenv("AWS_SESSION_TOKEN", *tempCreds.SessionToken)
// Print a message indicating that the environment variables have been set
fmt.Println("Temporary credentials obtained with MFA. Environment variables have been set.")
// Print the temporary credentials
fmt.Printf("AWS_ACCESS_KEY_ID=%s\n", *tempCreds.AccessKeyId)
fmt.Printf("AWS_SECRET_ACCESS_KEY=%s\n", *tempCreds.SecretAccessKey)
fmt.Printf("AWS_SESSION_TOKEN=%s\n", *tempCreds.SessionToken)
}