/
ec2.go
1271 lines (1059 loc) · 35.4 KB
/
ec2.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
copyright 2020 the Goployer authors
licensed under the apache license, version 2.0 (the "license");
you may not use this file except in compliance with the license.
you may obtain a copy of the license at
http://www.apache.org/licenses/license-2.0
unless required by applicable law or agreed to in writing, software
distributed under the license is distributed on an "as is" basis,
without warranties or conditions of any kind, either express or implied.
see the license for the specific language governing permissions and
limitations under the license.
*/
package aws
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/ec2"
Logger "github.com/sirupsen/logrus"
"github.com/DevopsArtFactory/goployer/pkg/constants"
"github.com/DevopsArtFactory/goployer/pkg/schemas"
"github.com/DevopsArtFactory/goployer/pkg/tool"
)
type EC2Client struct {
Client *ec2.EC2
AsClient *autoscaling.AutoScaling
}
func NewEC2Client(session client.ConfigProvider, region string, creds *credentials.Credentials) EC2Client {
return EC2Client{
Client: getEC2ClientFn(session, region, creds),
AsClient: getAsgClientFn(session, region, creds),
}
}
// getEC2ClientFn creates an EC2 client
func getEC2ClientFn(session client.ConfigProvider, region string, creds *credentials.Credentials) *ec2.EC2 {
if creds == nil {
return ec2.New(session, &aws.Config{Region: aws.String(region)})
}
return ec2.New(session, &aws.Config{Region: aws.String(region), Credentials: creds})
}
// getAsgClientFn creates an Autoscaling client
func getAsgClientFn(session client.ConfigProvider, region string, creds *credentials.Credentials) *autoscaling.AutoScaling {
if creds == nil {
return autoscaling.New(session, &aws.Config{Region: aws.String(region)})
}
return autoscaling.New(session, &aws.Config{Region: aws.String(region), Credentials: creds})
}
// GetMatchingAutoscalingGroup returns only one matching autoscaling group information
func (e EC2Client) GetMatchingAutoscalingGroup(name string) (*autoscaling.Group, error) {
asgGroup, err := getSingleAutoScalingGroup(e.AsClient, name)
if err != nil {
return nil, err
}
return asgGroup, nil
}
// GetMatchingLaunchTemplate returns information of launch template with matched ID
func (e EC2Client) GetMatchingLaunchTemplate(ltID string) (*ec2.LaunchTemplateVersion, error) {
input := &ec2.DescribeLaunchTemplateVersionsInput{
LaunchTemplateId: aws.String(ltID),
}
ret, err := e.Client.DescribeLaunchTemplateVersions(input)
if err != nil {
return nil, err
}
return ret.LaunchTemplateVersions[0], nil
}
// GetSecurityGroupDetails returns detailed information for security group
func (e EC2Client) GetSecurityGroupDetails(sgIds []*string) ([]*ec2.SecurityGroup, error) {
input := &ec2.DescribeSecurityGroupsInput{
GroupIds: sgIds,
}
result, err := e.Client.DescribeSecurityGroups(input)
if err != nil {
return nil, err
}
return result.SecurityGroups, nil
}
// DeleteLaunchConfigurations deletes All Launch Configurations belongs to the autoscaling group
func (e EC2Client) DeleteLaunchConfigurations(asgName string) error {
lcs := getAllLaunchConfigurations(e.AsClient, []*autoscaling.LaunchConfiguration{}, nil)
for _, lc := range lcs {
if strings.HasPrefix(*lc.LaunchConfigurationName, asgName) {
err := deleteLaunchConfiguration(e.AsClient, *lc.LaunchConfigurationName)
if err != nil {
return err
}
}
}
return nil
}
// DeleteLaunchTemplates deletes all launch template belongs to the autoscaling group
func (e EC2Client) DeleteLaunchTemplates(asgName string) error {
lts := getAllLaunchTemplates(e.Client, []*ec2.LaunchTemplate{}, nil)
for _, lt := range lts {
if strings.HasPrefix(*lt.LaunchTemplateName, asgName) {
err := deleteLaunchTemplate(e.Client, *lt.LaunchTemplateName)
if err != nil {
return err
}
}
}
return nil
}
// Delete Autoscaling group Set
func (e EC2Client) DeleteAutoscalingSet(asgName string) error {
input := &autoscaling.DeleteAutoScalingGroupInput{
AutoScalingGroupName: aws.String(asgName),
}
_, err := e.AsClient.DeleteAutoScalingGroup(input)
if err != nil {
return err
}
return nil
}
// Get All matching autoscaling groups with aws prefix
// By this function, you could get the latest version of deployment
func (e EC2Client) GetAllMatchingAutoscalingGroupsWithPrefix(prefix string) ([]*autoscaling.Group, error) {
asgGroups, err := getAutoScalingGroups(e.AsClient, []*autoscaling.Group{}, nil)
if err != nil {
return nil, err
}
var ret []*autoscaling.Group
for _, asgGroup := range asgGroups {
if strings.HasPrefix(*asgGroup.AutoScalingGroupName, prefix) {
ret = append(ret, asgGroup)
}
}
return ret, nil
}
// Batch of retrieving list of autoscaling group
// By Token, if needed, you could get all autoscaling groups with paging.
func getAutoScalingGroups(client *autoscaling.AutoScaling, asgGroup []*(autoscaling.Group), nextToken *string) ([]*autoscaling.Group, error) {
input := &autoscaling.DescribeAutoScalingGroupsInput{
NextToken: nextToken,
}
ret, err := client.DescribeAutoScalingGroups(input)
if err != nil {
return nil, err
}
asgGroup = append(asgGroup, ret.AutoScalingGroups...)
if ret.NextToken != nil {
return getAutoScalingGroups(client, asgGroup, ret.NextToken)
}
return asgGroup, nil
}
// Batch of retrieving all launch configurations
func getAllLaunchConfigurations(client *autoscaling.AutoScaling, lcs []*autoscaling.LaunchConfiguration, nextToken *string) []*autoscaling.LaunchConfiguration {
input := &autoscaling.DescribeLaunchConfigurationsInput{
NextToken: nextToken,
}
ret, err := client.DescribeLaunchConfigurations(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case autoscaling.ErrCodeInvalidNextToken:
Logger.Errorln(autoscaling.ErrCodeInvalidNextToken, aerr.Error())
case autoscaling.ErrCodeResourceContentionFault:
Logger.Errorln(autoscaling.ErrCodeResourceContentionFault, aerr.Error())
default:
Logger.Errorln(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
Logger.Errorln(err.Error())
}
return nil
}
lcs = append(lcs, ret.LaunchConfigurations...)
if ret.NextToken != nil {
return getAllLaunchConfigurations(client, lcs, ret.NextToken)
}
return lcs
}
// Batch of retrieving all launch templates
func getAllLaunchTemplates(client *ec2.EC2, lts []*ec2.LaunchTemplate, nextToken *string) []*ec2.LaunchTemplate {
input := &ec2.DescribeLaunchTemplatesInput{
NextToken: nextToken,
}
ret, err := client.DescribeLaunchTemplates(input)
if err != nil {
return nil
}
lts = append(lts, ret.LaunchTemplates...)
if ret.NextToken != nil {
return getAllLaunchTemplates(client, lts, ret.NextToken)
}
return lts
}
// Delete Single Launch Configuration
func deleteLaunchConfiguration(client *autoscaling.AutoScaling, lcName string) error {
input := &autoscaling.DeleteLaunchConfigurationInput{
LaunchConfigurationName: aws.String(lcName),
}
_, err := client.DeleteLaunchConfiguration(input)
if err != nil {
return err
}
return nil
}
// Delete Single Launch Template
func deleteLaunchTemplate(client *ec2.EC2, ltName string) error {
input := &ec2.DeleteLaunchTemplateInput{
LaunchTemplateName: aws.String(ltName),
}
_, err := client.DeleteLaunchTemplate(input)
if err != nil {
return err
}
return nil
}
// Create New Launch Configuration
func (e EC2Client) CreateNewLaunchConfiguration(name, ami, instanceType, keyName, iamProfileName, userdata string, ebsOptimized bool, securityGroups []*string, blockDevices []*autoscaling.BlockDeviceMapping) bool {
input := &autoscaling.CreateLaunchConfigurationInput{
LaunchConfigurationName: aws.String(name),
ImageId: aws.String(ami),
KeyName: aws.String(keyName),
InstanceType: aws.String(instanceType),
UserData: aws.String(userdata),
SecurityGroups: securityGroups,
EbsOptimized: aws.Bool(ebsOptimized),
BlockDeviceMappings: blockDevices,
}
if len(iamProfileName) > 0 {
input.IamInstanceProfile = aws.String(iamProfileName)
}
_, err := e.AsClient.CreateLaunchConfiguration(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case autoscaling.ErrCodeAlreadyExistsFault:
Logger.Errorln(autoscaling.ErrCodeAlreadyExistsFault, aerr.Error())
case autoscaling.ErrCodeLimitExceededFault:
Logger.Errorln(autoscaling.ErrCodeLimitExceededFault, aerr.Error())
case autoscaling.ErrCodeResourceContentionFault:
Logger.Errorln(autoscaling.ErrCodeResourceContentionFault, aerr.Error())
default:
Logger.Errorln(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
Logger.Errorln(err.Error())
}
return false
}
Logger.Info("Successfully create new launch configurations : ", name)
return true
}
// Create New Launch Template
func (e EC2Client) CreateNewLaunchTemplate(name, ami, instanceType, keyName, iamProfileName, userdata string, ebsOptimized, mixedInstancePolicyEnabled bool, securityGroups []*string, blockDevices []*ec2.LaunchTemplateBlockDeviceMappingRequest, instanceMarketOptions *schemas.InstanceMarketOptions, detailedMonitoringEnabled bool) error {
input := &ec2.CreateLaunchTemplateInput{
LaunchTemplateData: &ec2.RequestLaunchTemplateData{
ImageId: aws.String(ami),
InstanceType: aws.String(instanceType),
IamInstanceProfile: &ec2.LaunchTemplateIamInstanceProfileSpecificationRequest{
Name: aws.String(iamProfileName),
},
UserData: aws.String(userdata),
SecurityGroupIds: securityGroups,
EbsOptimized: aws.Bool(ebsOptimized),
Monitoring: &ec2.LaunchTemplatesMonitoringRequest{Enabled: aws.Bool(detailedMonitoringEnabled)},
},
LaunchTemplateName: aws.String(name),
}
if len(blockDevices) > 0 {
input.LaunchTemplateData.SetBlockDeviceMappings(blockDevices)
}
if len(keyName) > 0 {
input.LaunchTemplateData.SetKeyName(keyName)
}
if instanceMarketOptions != nil && !mixedInstancePolicyEnabled {
input.LaunchTemplateData.InstanceMarketOptions = &ec2.LaunchTemplateInstanceMarketOptionsRequest{
MarketType: aws.String(instanceMarketOptions.MarketType),
SpotOptions: &ec2.LaunchTemplateSpotMarketOptionsRequest{},
}
if instanceMarketOptions.SpotOptions.BlockDurationMinutes > 0 {
input.LaunchTemplateData.InstanceMarketOptions.SpotOptions.SetBlockDurationMinutes(instanceMarketOptions.SpotOptions.BlockDurationMinutes)
}
if len(instanceMarketOptions.SpotOptions.InstanceInterruptionBehavior) > 0 {
input.LaunchTemplateData.InstanceMarketOptions.SpotOptions.SetInstanceInterruptionBehavior(instanceMarketOptions.SpotOptions.InstanceInterruptionBehavior)
}
if len(instanceMarketOptions.SpotOptions.SpotInstanceType) > 0 {
input.LaunchTemplateData.InstanceMarketOptions.SpotOptions.SetSpotInstanceType(instanceMarketOptions.SpotOptions.SpotInstanceType)
}
if len(instanceMarketOptions.SpotOptions.MaxPrice) > 0 {
input.LaunchTemplateData.InstanceMarketOptions.SpotOptions.SetMaxPrice(instanceMarketOptions.SpotOptions.MaxPrice)
}
}
_, err := e.Client.CreateLaunchTemplate(input)
if err != nil {
return err
}
Logger.Info("Successfully create new launch template : ", name)
return nil
}
// Get All Security Group Information New Launch Configuration
func (e EC2Client) GetSecurityGroupList(vpc string, sgList []string) ([]*string, error) {
if len(sgList) == 0 {
return nil, errors.New("need to specify at least one security group")
}
vpcID, err := e.GetVPCId(vpc)
if err != nil {
return nil, err
}
var retList []*string
for _, sg := range sgList {
if strings.HasPrefix(sg, "sg-") {
retList = append(retList, aws.String(sg))
continue
}
input := &ec2.DescribeSecurityGroupsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("group-name"),
Values: []*string{
aws.String(sg),
},
},
{
Name: aws.String("vpc-id"),
Values: []*string{
aws.String(vpcID),
},
},
},
}
result, err := e.Client.DescribeSecurityGroups(input)
if err != nil {
return nil, err
}
// if it matches 0 or more than 1, it is wrong
if len(result.SecurityGroups) != 1 {
var matched []string
for _, s := range result.SecurityGroups {
matched = append(matched, *s.GroupName)
}
return nil, fmt.Errorf("expected only one security group on name lookup for \"%s\" got \"%s\"", sg, strings.Join(matched, ","))
}
retList = append(retList, result.SecurityGroups[0].GroupId)
}
return retList, nil
}
// MakeBlockDevices returns list of block device mapping for launch configuration
func (e EC2Client) MakeBlockDevices(blocks []schemas.BlockDevice) []*autoscaling.BlockDeviceMapping {
ret := []*autoscaling.BlockDeviceMapping{}
for _, block := range blocks {
bType := block.VolumeType
if bType == "" {
Logger.Info("Volume type not defined for device mapping: defaulting to \"gp2\"")
bType = "gp2"
}
bSize := block.VolumeSize
if bSize == 0 {
Logger.Info("Volume size not defined for device mapping: defaulting to 16GB")
bSize = 16
}
ret = append(ret, &autoscaling.BlockDeviceMapping{
DeviceName: aws.String(block.DeviceName),
Ebs: &autoscaling.Ebs{
VolumeSize: aws.Int64(bSize),
VolumeType: aws.String(bType),
},
NoDevice: nil,
VirtualName: nil,
})
}
return ret
}
// MakeLaunchTemplateBlockDeviceMappings returns list of block device mappings for launch template
func (e EC2Client) MakeLaunchTemplateBlockDeviceMappings(blocks []schemas.BlockDevice) []*ec2.LaunchTemplateBlockDeviceMappingRequest {
ret := []*ec2.LaunchTemplateBlockDeviceMappingRequest{}
for _, block := range blocks {
bType := block.VolumeType
if bType == "" {
Logger.Info("Default value is applied because volume type not defined : gp2")
bType = "gp2"
}
bSize := block.VolumeSize
if bSize == 0 {
Logger.Info("Volume size not defined for device mapping: defaulting to 16GB")
bSize = 16
}
tmp := ec2.LaunchTemplateBlockDeviceMappingRequest{
DeviceName: aws.String(block.DeviceName),
Ebs: &ec2.LaunchTemplateEbsBlockDeviceRequest{
VolumeSize: aws.Int64(bSize),
VolumeType: aws.String(bType),
},
NoDevice: nil,
VirtualName: nil,
}
if tool.IsStringInArray(bType, constants.IopsRequiredBlockType) {
tmp.Ebs.Iops = aws.Int64(block.Iops)
Logger.Debugf("iops applied: %d", block.Iops)
}
ret = append(ret, &tmp)
}
return ret
}
func (e EC2Client) GetVPCId(vpc string) (string, error) {
ret, err := regexp.MatchString("vpc-[0-9A-Fa-f]{17}", vpc)
if err != nil {
return constants.EmptyString, fmt.Errorf("error occurs when checking regex %v", err.Error())
}
if ret {
return vpc, nil
}
input := &ec2.DescribeVpcsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("tag:Name"),
Values: []*string{
aws.String(vpc),
},
},
},
}
result, err := e.Client.DescribeVpcs(input)
if err != nil {
return constants.EmptyString, err
}
// More than 1 vpc..
if len(result.Vpcs) > 1 {
return constants.EmptyString, fmt.Errorf("expected only one VPC on name lookup for %v", vpc)
}
// No VPC found
if len(result.Vpcs) < 1 {
return constants.EmptyString, fmt.Errorf("unable to find VPC on name lookup for %v", vpc)
}
return *result.Vpcs[0].VpcId, nil
}
// CreateAutoScalingGroup creates new autoscaling group
func (e EC2Client) CreateAutoScalingGroup(name, launchTemplateName, healthcheckType string,
healthcheckGracePeriod int64,
capacity schemas.Capacity,
loadbalancers, availabilityZones []string,
targetGroupArns, terminationPolicies []*string,
tags []*(autoscaling.Tag),
subnets []string,
mixedInstancePolicy schemas.MixedInstancesPolicy,
hooks []*autoscaling.LifecycleHookSpecification) error {
lt := autoscaling.LaunchTemplateSpecification{
LaunchTemplateName: aws.String(launchTemplateName),
}
input := &autoscaling.CreateAutoScalingGroupInput{
AutoScalingGroupName: aws.String(name),
MaxSize: aws.Int64(capacity.Max),
MinSize: aws.Int64(capacity.Min),
DesiredCapacity: aws.Int64(capacity.Desired),
AvailabilityZones: aws.StringSlice(availabilityZones),
HealthCheckType: aws.String(healthcheckType),
HealthCheckGracePeriod: aws.Int64(healthcheckGracePeriod),
TerminationPolicies: terminationPolicies,
Tags: tags,
VPCZoneIdentifier: aws.String(strings.Join(subnets, ",")),
}
if len(loadbalancers) > 0 {
input.LoadBalancerNames = aws.StringSlice(loadbalancers)
}
if len(targetGroupArns) > 0 {
input.TargetGroupARNs = targetGroupArns
}
if mixedInstancePolicy.Enabled {
input.MixedInstancesPolicy = &autoscaling.MixedInstancesPolicy{
InstancesDistribution: &autoscaling.InstancesDistribution{
OnDemandBaseCapacity: aws.Int64(mixedInstancePolicy.OnDemandBaseCapacity),
SpotAllocationStrategy: aws.String(mixedInstancePolicy.SpotAllocationStrategy),
SpotInstancePools: aws.Int64(mixedInstancePolicy.SpotInstancePools),
SpotMaxPrice: aws.String(mixedInstancePolicy.SpotMaxPrice),
},
LaunchTemplate: &autoscaling.LaunchTemplate{
LaunchTemplateSpecification: <,
},
}
if mixedInstancePolicy.OnDemandPercentage >= 0 {
input.MixedInstancesPolicy.InstancesDistribution.OnDemandPercentageAboveBaseCapacity = aws.Int64(mixedInstancePolicy.OnDemandPercentage)
}
if len(mixedInstancePolicy.Override) != 0 {
var overrides []*autoscaling.LaunchTemplateOverrides
for _, o := range mixedInstancePolicy.Override {
overrides = append(overrides, &autoscaling.LaunchTemplateOverrides{
InstanceType: aws.String(o),
})
}
input.MixedInstancesPolicy.LaunchTemplate.Overrides = overrides
}
} else {
input.LaunchTemplate = <
}
if len(hooks) > 0 {
input.LifecycleHookSpecificationList = hooks
}
_, err := e.AsClient.CreateAutoScalingGroup(input)
if err != nil {
return err
}
Logger.Info("Successfully create new autoscaling group : ", name)
return nil
}
// GetAvailabilityZones get all available availability zones
func (e EC2Client) GetAvailabilityZones(vpc string, azs []string) ([]string, error) {
var ret []string
vpcID, err := e.GetVPCId(vpc)
if err != nil {
return nil, err
}
input := &ec2.DescribeSubnetsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("vpc-id"),
Values: []*string{
aws.String(vpcID),
},
},
},
}
result, err := e.Client.DescribeSubnets(input)
if err != nil {
return nil, err
}
for _, subnet := range result.Subnets {
if tool.IsStringInArray(*subnet.AvailabilityZone, ret) || (len(azs) > 0 && !tool.IsStringInArray(*subnet.AvailabilityZone, azs)) {
continue
}
ret = append(ret, *subnet.AvailabilityZone)
}
return ret, nil
}
// GetSubnets retrieves all subnets available
func (e EC2Client) GetSubnets(vpc string, usePublicSubnets bool, azs []string) ([]string, error) {
vpcID, err := e.GetVPCId(vpc)
if err != nil {
return nil, err
}
input := &ec2.DescribeSubnetsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("vpc-id"),
Values: []*string{
aws.String(vpcID),
},
},
},
}
result, err := e.Client.DescribeSubnets(input)
if err != nil {
return nil, err
}
ret := []string{}
subnetType := "private"
if usePublicSubnets {
subnetType = "public"
}
for _, subnet := range result.Subnets {
if !tool.IsStringInArray(*subnet.AvailabilityZone, azs) {
continue
}
for _, tag := range subnet.Tags {
if *tag.Key == "Name" && strings.HasPrefix(*tag.Value, subnetType) {
ret = append(ret, *subnet.SubnetId)
}
}
}
return ret, nil
}
// Update Autoscaling Group size
func (e EC2Client) UpdateAutoScalingGroupSize(asg string, min, max, desired, retry int64) (int64, error) {
input := &autoscaling.UpdateAutoScalingGroupInput{
AutoScalingGroupName: aws.String(asg),
MaxSize: aws.Int64(max),
MinSize: aws.Int64(min),
DesiredCapacity: aws.Int64(desired),
}
_, err := e.AsClient.UpdateAutoScalingGroup(input)
if err != nil {
return retry - 1, err
}
return 0, nil
}
// CreateScalingPolicy creates scaling policy
func (e EC2Client) CreateScalingPolicy(policy schemas.ScalePolicy, asgName string) (*string, error) {
input := &autoscaling.PutScalingPolicyInput{
AdjustmentType: aws.String(policy.AdjustmentType),
AutoScalingGroupName: aws.String(asgName),
PolicyName: aws.String(policy.Name),
ScalingAdjustment: aws.Int64(policy.ScalingAdjustment),
Cooldown: aws.Int64(policy.Cooldown),
}
result, err := e.AsClient.PutScalingPolicy(input)
if err != nil {
return nil, err
}
return result.PolicyARN, nil
}
// EnableMetrics enables metric monitoring of autoscaling group
func (e EC2Client) EnableMetrics(asgName string) error {
input := &autoscaling.EnableMetricsCollectionInput{
AutoScalingGroupName: aws.String(asgName),
Granularity: aws.String("1Minute"),
}
_, err := e.AsClient.EnableMetricsCollection(input)
if err != nil {
return err
}
Logger.Info(fmt.Sprintf("Metrics monitoring of autoscaling group is enabled : %s", asgName))
return nil
}
// GenerateLifecycleHooks generate lifecycle hooks
func (e EC2Client) GenerateLifecycleHooks(hooks schemas.LifecycleHooks) []*autoscaling.LifecycleHookSpecification {
var ret []*autoscaling.LifecycleHookSpecification
if len(hooks.LaunchTransition) > 0 {
for _, l := range hooks.LaunchTransition {
lhs := createSingleLifecycleHookSpecification(l, "autoscaling:EC2_INSTANCE_LAUNCHING")
ret = append(ret, &lhs)
}
}
if len(hooks.TerminateTransition) > 0 {
for _, l := range hooks.TerminateTransition {
lhs := createSingleLifecycleHookSpecification(l, "autoscaling:EC2_INSTANCE_TERMINATING")
ret = append(ret, &lhs)
}
}
return ret
}
// createSingleLifecycleHookSpecification create a lifecycle hook specification
func createSingleLifecycleHookSpecification(l schemas.LifecycleHookSpecification, transition string) autoscaling.LifecycleHookSpecification {
lhs := autoscaling.LifecycleHookSpecification{
LifecycleHookName: aws.String(l.LifecycleHookName),
LifecycleTransition: aws.String(transition),
}
if len(l.DefaultResult) > 0 {
lhs.DefaultResult = aws.String(l.DefaultResult)
}
if l.HeartbeatTimeout > 0 {
lhs.HeartbeatTimeout = aws.Int64(l.HeartbeatTimeout)
}
if len(l.NotificationMetadata) > 0 {
lhs.NotificationMetadata = aws.String(l.NotificationMetadata)
}
if len(l.NotificationTargetARN) > 0 {
lhs.NotificationTargetARN = aws.String(l.NotificationTargetARN)
}
if len(l.RoleARN) > 0 {
lhs.RoleARN = aws.String(l.RoleARN)
}
return lhs
}
// GetTargetGroups returns list of target group ARN of autoscaling group
func (e EC2Client) GetTargetGroups(asgName string) ([]*string, error) {
input := &autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: []*string{
aws.String(asgName),
},
}
result, err := e.AsClient.DescribeAutoScalingGroups(input)
if err != nil {
return nil, err
}
var ret []*string
for _, a := range result.AutoScalingGroups {
ret = a.TargetGroupARNs
}
return ret, nil
}
// getSingleAutoScalingGroup return detailed information of autoscaling group
func getSingleAutoScalingGroup(client *autoscaling.AutoScaling, asgName string) (*autoscaling.Group, error) {
input := &autoscaling.DescribeAutoScalingGroupsInput{
AutoScalingGroupNames: aws.StringSlice([]string{asgName}),
}
ret, err := client.DescribeAutoScalingGroups(input)
if err != nil {
return nil, err
}
if len(ret.AutoScalingGroups) == 0 {
return nil, fmt.Errorf("no autoscaling group exists with name: %s", asgName)
}
return ret.AutoScalingGroups[0], nil
}
// UpdateAutoScalingGroup updates auto scaling group information
func (e EC2Client) UpdateAutoScalingGroup(asg string, capacity schemas.Capacity) error {
input := &autoscaling.UpdateAutoScalingGroupInput{
AutoScalingGroupName: aws.String(asg),
MaxSize: aws.Int64(capacity.Max),
MinSize: aws.Int64(capacity.Min),
DesiredCapacity: aws.Int64(capacity.Desired),
}
_, err := e.AsClient.UpdateAutoScalingGroup(input)
if err != nil {
return err
}
return nil
}
// CreateScheduledActions creates scheduled actions
func (e EC2Client) CreateScheduledActions(asg string, actions []schemas.ScheduledAction) error {
input := &autoscaling.BatchPutScheduledUpdateGroupActionInput{
AutoScalingGroupName: aws.String(asg),
}
var scheduledUpdateGroupActions []*autoscaling.ScheduledUpdateGroupActionRequest
for _, a := range actions {
newSa := autoscaling.ScheduledUpdateGroupActionRequest{
ScheduledActionName: aws.String(a.Name),
Recurrence: aws.String(a.Recurrence),
MinSize: aws.Int64(a.Capacity.Min),
DesiredCapacity: aws.Int64(a.Capacity.Desired),
MaxSize: aws.Int64(a.Capacity.Max),
}
scheduledUpdateGroupActions = append(scheduledUpdateGroupActions, &newSa)
}
input.ScheduledUpdateGroupActions = scheduledUpdateGroupActions
_, err := e.AsClient.BatchPutScheduledUpdateGroupAction(input)
if err != nil {
return err
}
return nil
}
// AttachAsgToTargetGroups attaches autoscaling group to target groups of ELB
func (e EC2Client) AttachAsgToTargetGroups(asg string, targetGroups []*string) error {
input := &autoscaling.AttachLoadBalancerTargetGroupsInput{
AutoScalingGroupName: aws.String(asg),
TargetGroupARNs: targetGroups,
}
_, err := e.AsClient.AttachLoadBalancerTargetGroups(input)
if err != nil {
return err
}
return nil
}
// DetachAsgFromTargetGroups detaches autoscaling group from target groups of ELB
func (e EC2Client) DetachAsgFromTargetGroups(asg string, targetGroups []*string) error {
input := &autoscaling.DetachLoadBalancerTargetGroupsInput{
AutoScalingGroupName: aws.String(asg),
TargetGroupARNs: targetGroups,
}
_, err := e.AsClient.DetachLoadBalancerTargetGroups(input)
if err != nil {
return err
}
return nil
}
// CreateSecurityGroup creates new security group
func (e EC2Client) CreateSecurityGroup(sgName string, vpcID *string) (*string, error) {
input := &ec2.CreateSecurityGroupInput{
Description: aws.String("canary deployment"),
GroupName: aws.String(sgName),
VpcId: vpcID,
}
ret, err := e.Client.CreateSecurityGroup(input)
if err != nil {
return nil, err
}
return ret.GroupId, nil
}
// GetSecurityGroup retrieves group id of existing security group
func (e EC2Client) GetSecurityGroup(sgName string) (*string, error) {
input := &ec2.DescribeSecurityGroupsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("group-name"),
Values: []*string{
aws.String(sgName),
},
},
},
}
result, err := e.Client.DescribeSecurityGroups(input)
if err != nil {
return nil, err
}
if len(result.SecurityGroups) == 0 {
return nil, fmt.Errorf("checked duplicated but cannot find the security group: %s", sgName)
}
return result.SecurityGroups[0].GroupId, nil
}
// UpdateInboundRules updates inbound rules for security group with IP
func (e EC2Client) UpdateInboundRules(sgID, protocol, cidr, description string, fromPort, toPort int64) error {
input := &ec2.AuthorizeSecurityGroupIngressInput{
GroupId: aws.String(sgID),
IpPermissions: []*ec2.IpPermission{
{
FromPort: aws.Int64(fromPort),
ToPort: aws.Int64(toPort),
IpProtocol: aws.String(protocol),
IpRanges: []*ec2.IpRange{
{
CidrIp: aws.String(cidr),
Description: aws.String(description),
},
},
},
},
}
_, err := e.Client.AuthorizeSecurityGroupIngress(input)
if err != nil {
return err
}
return nil
}
// UpdateInboundRulesWithGroup updates inbound rules for security group with other security group
func (e EC2Client) UpdateInboundRulesWithGroup(sgID, protocol, description string, fromSg *string, fromPort, toPort int64) error {
input := &ec2.AuthorizeSecurityGroupIngressInput{
GroupId: aws.String(sgID),
IpPermissions: []*ec2.IpPermission{
{
FromPort: aws.Int64(fromPort),
ToPort: aws.Int64(toPort),
IpProtocol: aws.String(protocol),
UserIdGroupPairs: []*ec2.UserIdGroupPair{
{
Description: aws.String(description),
GroupId: fromSg,
},
},
},
},
}
_, err := e.Client.AuthorizeSecurityGroupIngress(input)
if err != nil {
return err
}