-
Notifications
You must be signed in to change notification settings - Fork 1
/
plugin.go
executable file
·113 lines (94 loc) · 2.22 KB
/
plugin.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/sirupsen/logrus"
)
type (
// Config holds input parameters for the plugin
Config struct {
Sensitive bool
RoleARN string
Shell bool
}
AWSCli struct {
Version string
Commands []string
}
// Plugin represents the plugin instance to be executed
Plugin struct {
Config Config
AWSCli AWSCli
}
)
// Exec executes the plugin
func (p Plugin) Exec() error {
// Install specified version of awscli
if p.AWSCli.Version == "" {
err := installAWSCli()
if err != nil {
return err
}
}
if p.Config.RoleARN != "" {
assumeRole(p.Config.RoleARN)
}
// Initialize commands
var commands []*exec.Cmd
// Print AWSCli version
commands = append(commands, exec.Command(awsCliExe, "--version"))
// Set user defined command
for _, command := range p.AWSCli.Commands {
if p.Config.Shell {
commands = append(commands, exec.Command(
"bash", "-c", command))
} else {
commands = append(commands, exec.Command(command))
}
}
// Run commands
for _, c := range commands {
c.Stdout = os.Stdout
c.Stderr = os.Stderr
if !p.Config.Sensitive {
trace(c)
}
err := c.Run()
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
}).Fatal("Failed to execute a command")
}
logrus.Debug("Command completed successfully")
}
return nil
}
func assumeRole(roleArn string) {
client := sts.New(session.New())
duration := time.Hour * 1
stsProvider := &stscreds.AssumeRoleProvider{
Client: client,
Duration: duration,
RoleARN: roleArn,
RoleSessionName: "drone",
}
value, err := credentials.NewCredentials(stsProvider).Get()
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
}).Fatal("Error assuming role!")
}
os.Setenv("AWS_ACCESS_KEY_ID", value.AccessKeyID)
os.Setenv("AWS_SECRET_ACCESS_KEY", value.SecretAccessKey)
os.Setenv("AWS_SESSION_TOKEN", value.SessionToken)
}
func trace(cmd *exec.Cmd) {
fmt.Println("$", strings.Join(cmd.Args, " "))
}