forked from josmo/drone-ecs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.go
349 lines (301 loc) · 10.8 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"errors"
"fmt"
"os"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecs"
)
type Plugin struct {
Key string
Secret string
Region string
Family string
TaskRoleArn string
Service string
ContainerName string
DockerImage string
Tag string
Cluster string
LogDriver string
LogOptions []string
DeploymentConfiguration string
PortMappings []string
Environment []string
SecretEnvironment []string
Labels []string
EntryPoint []string
DesiredCount int64
CPU int64
Memory int64
MemoryReservation int64
NetworkMode string
YamlVerified bool
TaskCPU string
TaskMemory string
TaskExecutionRoleArn string
Compatibilities string
HealthCheckCommand []string
HealthCheckInterval int64
HealthCheckRetries int64
HealthCheckStartPeriod int64
HealthCheckTimeout int64
Ulimits []string
// ServiceNetworkAssignPublicIP - Whether the task's elastic network interface receives a public IP address. The default value is DISABLED.
ServiceNetworkAssignPublicIp string
// ServiceNetworkSecurityGroups represents the VPC security groups to use
// when running awsvpc network mode.
ServiceNetworkSecurityGroups []string
// ServiceNetworkSubnets represents the VPC security groups to use when
// running awsvpc network mode.
ServiceNetworkSubnets []string
}
const (
softLimitBaseParseErr = "error parsing ulimits softLimit: "
hardLimitBaseParseErr = "error parsing ulimits hardLimit: "
hostPortBaseParseErr = "error parsing port_mappings hostPort: "
containerBaseParseErr = "error parsing port_mappings containerPort: "
minimumHealthyPercentBaseParseErr = "error parsing deployment_configuration minimumHealthyPercent: "
maximumPercentBaseParseErr = "error parsing deployment_configuration maximumPercent: "
)
func (p *Plugin) Exec() error {
fmt.Println("Drone AWS ECS Plugin built")
awsConfig := aws.Config{}
if len(p.Key) != 0 && len(p.Secret) != 0 {
awsConfig.Credentials = credentials.NewStaticCredentials(p.Key, p.Secret, "")
}
awsConfig.Region = aws.String(p.Region)
svc := ecs.New(session.New(&awsConfig))
Image := p.DockerImage + ":" + p.Tag
if len(p.ContainerName) == 0 {
p.ContainerName = p.Family + "-container"
}
definition := ecs.ContainerDefinition{
Command: []*string{},
DnsSearchDomains: []*string{},
DnsServers: []*string{},
DockerLabels: map[string]*string{},
DockerSecurityOptions: []*string{},
EntryPoint: []*string{},
Environment: []*ecs.KeyValuePair{},
Essential: aws.Bool(true),
ExtraHosts: []*ecs.HostEntry{},
Image: aws.String(Image),
Links: []*string{},
MountPoints: []*ecs.MountPoint{},
Name: aws.String(p.ContainerName),
PortMappings: []*ecs.PortMapping{},
Ulimits: []*ecs.Ulimit{},
//User: aws.String("String"),
VolumesFrom: []*ecs.VolumeFrom{},
//WorkingDirectory: aws.String("String"),
}
if p.CPU != 0 {
definition.Cpu = aws.Int64(p.CPU)
}
if p.Memory == 0 && p.MemoryReservation == 0 {
definition.MemoryReservation = aws.Int64(128)
} else {
if p.Memory != 0 {
definition.Memory = aws.Int64(p.Memory)
}
if p.MemoryReservation != 0 {
definition.MemoryReservation = aws.Int64(p.MemoryReservation)
}
}
// Port mappings
for _, portMapping := range p.PortMappings {
cleanedPortMapping := strings.Trim(portMapping, " ")
parts := strings.SplitN(cleanedPortMapping, " ", 2)
hostPort, hostPortErr := strconv.ParseInt(parts[0], 10, 64)
if hostPortErr != nil {
hostPortWrappedErr := errors.New(hostPortBaseParseErr + hostPortErr.Error())
fmt.Println(hostPortWrappedErr.Error())
return hostPortWrappedErr
}
containerPort, containerPortErr := strconv.ParseInt(parts[1], 10, 64)
if containerPortErr != nil {
containerPortWrappedErr := errors.New(containerBaseParseErr + containerPortErr.Error())
fmt.Println(containerPortWrappedErr.Error())
return containerPortWrappedErr
}
pair := ecs.PortMapping{
ContainerPort: aws.Int64(containerPort),
HostPort: aws.Int64(hostPort),
Protocol: aws.String("TransportProtocol"),
}
definition.PortMappings = append(definition.PortMappings, &pair)
}
// Environment variables
for _, envVar := range p.Environment {
parts := strings.SplitN(envVar, "=", 2)
pair := ecs.KeyValuePair{
Name: aws.String(strings.Trim(parts[0], " ")),
Value: aws.String(strings.Trim(parts[1], " ")),
}
definition.Environment = append(definition.Environment, &pair)
}
// Secret Environment variables
for _, envVar := range p.SecretEnvironment {
parts := strings.SplitN(envVar, "=", 2)
pair := ecs.KeyValuePair{}
if len(parts) == 2 {
// set to custom named variable
pair.SetName(aws.StringValue(aws.String(strings.Trim(parts[0], " "))))
pair.SetValue(aws.StringValue(aws.String(os.Getenv(strings.Trim(parts[1], " ")))))
} else if len(parts) == 1 {
// default to named var
pair.SetName(aws.StringValue(aws.String(parts[0])))
pair.SetValue(aws.StringValue(aws.String(os.Getenv(parts[0]))))
} else {
fmt.Println("invalid syntax in secret enironment var", envVar)
}
definition.Environment = append(definition.Environment, &pair)
}
// Ulimits
for _, uLimit := range p.Ulimits {
cleanedULimit := strings.Trim(uLimit, " ")
parts := strings.SplitN(cleanedULimit, " ", 3)
name := strings.Trim(parts[0], " ")
softLimit, softLimitErr := strconv.ParseInt(parts[1], 10, 64)
if softLimitErr != nil {
softLimitWrappedErr := errors.New(softLimitBaseParseErr + softLimitErr.Error())
fmt.Println(softLimitWrappedErr.Error())
return softLimitWrappedErr
}
hardLimit, hardLimitErr := strconv.ParseInt(parts[2], 10, 64)
if hardLimitErr != nil {
hardLimitWrappedErr := errors.New(hardLimitBaseParseErr + hardLimitErr.Error())
fmt.Println(hardLimitWrappedErr.Error())
return hardLimitWrappedErr
}
pair := ecs.Ulimit{
Name: aws.String(name),
HardLimit: aws.Int64(hardLimit),
SoftLimit: aws.Int64(softLimit),
}
definition.Ulimits = append(definition.Ulimits, &pair)
}
// DockerLabels
for _, label := range p.Labels {
parts := strings.SplitN(label, "=", 2)
definition.DockerLabels[strings.Trim(parts[0], " ")] = aws.String(strings.Trim(parts[1], " "))
}
// EntryPoint
for _, v := range p.EntryPoint {
definition.EntryPoint = append(definition.EntryPoint, &v)
}
// LogOptions
if len(p.LogDriver) > 0 {
definition.LogConfiguration = new(ecs.LogConfiguration)
definition.LogConfiguration.LogDriver = &p.LogDriver
if len(p.LogOptions) > 0 {
definition.LogConfiguration.Options = make(map[string]*string)
for _, logOption := range p.LogOptions {
parts := strings.SplitN(logOption, "=", 2)
logOptionKey := strings.Trim(parts[0], " ")
logOptionValue := aws.String(strings.Trim(parts[1], " "))
definition.LogConfiguration.Options[logOptionKey] = logOptionValue
}
}
}
if len(p.NetworkMode) == 0 {
p.NetworkMode = "bridge"
}
if len(p.HealthCheckCommand) != 0 {
healthcheck := ecs.HealthCheck{
Command: aws.StringSlice(p.HealthCheckCommand),
Interval: &p.HealthCheckInterval,
Retries: &p.HealthCheckRetries,
Timeout: &p.HealthCheckTimeout,
}
if p.HealthCheckStartPeriod != 0 {
healthcheck.StartPeriod = &p.HealthCheckStartPeriod
}
definition.HealthCheck = &healthcheck
}
params := &ecs.RegisterTaskDefinitionInput{
ContainerDefinitions: []*ecs.ContainerDefinition{
&definition,
},
Family: aws.String(p.Family),
Volumes: []*ecs.Volume{},
TaskRoleArn: aws.String(p.TaskRoleArn),
NetworkMode: aws.String(p.NetworkMode),
}
cleanedCompatibilities := strings.Trim(p.Compatibilities, " ")
compatibilitySlice := strings.Split(cleanedCompatibilities, " ")
if cleanedCompatibilities != "" && len(compatibilitySlice) != 0 {
params.RequiresCompatibilities = aws.StringSlice(compatibilitySlice)
}
if len(p.TaskCPU) != 0 {
params.Cpu = aws.String(p.TaskCPU)
}
if len(p.TaskMemory) != 0 {
params.Memory = aws.String(p.TaskMemory)
}
if len(p.TaskExecutionRoleArn) != 0 {
params.ExecutionRoleArn = aws.String(p.TaskExecutionRoleArn)
}
resp, err := svc.RegisterTaskDefinition(params)
if err != nil {
return err
}
val := *(resp.TaskDefinition.TaskDefinitionArn)
sparams := &ecs.UpdateServiceInput{
Cluster: aws.String(p.Cluster),
Service: aws.String(p.Service),
TaskDefinition: aws.String(val),
NetworkConfiguration: p.setupServiceNetworkConfiguration(),
}
if p.DesiredCount >= 0 {
sparams.DesiredCount = aws.Int64(p.DesiredCount)
}
cleanedDeploymentConfiguration := strings.Trim(p.DeploymentConfiguration, " ")
parts := strings.SplitN(cleanedDeploymentConfiguration, " ", 2)
minimumHealthyPercent, minimumHealthyPercentError := strconv.ParseInt(parts[0], 10, 64)
if minimumHealthyPercentError != nil {
minimumHealthyPercentWrappedErr := errors.New(minimumHealthyPercentBaseParseErr + minimumHealthyPercentError.Error())
fmt.Println(minimumHealthyPercentWrappedErr.Error())
return minimumHealthyPercentWrappedErr
}
maximumPercent, maximumPercentErr := strconv.ParseInt(parts[1], 10, 64)
if maximumPercentErr != nil {
maximumPercentWrappedErr := errors.New(maximumPercentBaseParseErr + maximumPercentErr.Error())
fmt.Println(maximumPercentWrappedErr.Error())
return maximumPercentWrappedErr
}
sparams.DeploymentConfiguration = &ecs.DeploymentConfiguration{
MaximumPercent: aws.Int64(maximumPercent),
MinimumHealthyPercent: aws.Int64(minimumHealthyPercent),
}
sresp, serr := svc.UpdateService(sparams)
if serr != nil {
return serr
}
fmt.Println(sresp)
fmt.Println(resp)
return nil
}
// setupServiceNetworkConfiguration is used to setup the ECS service network
// configuration based on operator input.
func (p *Plugin) setupServiceNetworkConfiguration() *ecs.NetworkConfiguration {
netConfig := ecs.NetworkConfiguration{AwsvpcConfiguration: &ecs.AwsVpcConfiguration{}}
if p.NetworkMode != ecs.NetworkModeAwsvpc {
return &netConfig
}
if len(p.ServiceNetworkAssignPublicIp) != 0 {
netConfig.AwsvpcConfiguration.SetAssignPublicIp(p.ServiceNetworkAssignPublicIp);
}
if len(p.ServiceNetworkSubnets) > 0 {
netConfig.AwsvpcConfiguration.SetSubnets(aws.StringSlice(p.ServiceNetworkSubnets))
}
if len(p.ServiceNetworkSecurityGroups) > 0 {
netConfig.AwsvpcConfiguration.SetSecurityGroups(aws.StringSlice(p.ServiceNetworkSecurityGroups))
}
return &netConfig
}