-
Notifications
You must be signed in to change notification settings - Fork 584
/
Copy pathaws.go
2360 lines (2048 loc) · 67.8 KB
/
aws.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
//go:build e2e
// +build e2e
/*
Copyright 2020 The Kubernetes 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 shared
import (
"bytes"
"context"
b64 "encoding/base64"
"errors"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
awscreds "github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
cfn "github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/cloudtrail"
"github.com/aws/aws-sdk-go/service/configservice"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ecrpublic"
"github.com/aws/aws-sdk-go/service/efs"
"github.com/aws/aws-sdk-go/service/eks"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/servicequotas"
"github.com/aws/aws-sdk-go/service/sts"
cfn_iam "github.com/awslabs/goformation/v4/cloudformation/iam"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"k8s.io/utils/ptr"
"sigs.k8s.io/yaml"
cfn_bootstrap "sigs.k8s.io/cluster-api-provider-aws/v2/cmd/clusterawsadm/cloudformation/bootstrap"
cloudformation "sigs.k8s.io/cluster-api-provider-aws/v2/cmd/clusterawsadm/cloudformation/service"
"sigs.k8s.io/cluster-api-provider-aws/v2/cmd/clusterawsadm/credentials"
"sigs.k8s.io/cluster-api-provider-aws/v2/pkg/cloud/awserrors"
"sigs.k8s.io/cluster-api-provider-aws/v2/pkg/cloud/filter"
"sigs.k8s.io/cluster-api-provider-aws/v2/pkg/cloud/services/wait"
)
type AWSInfrastructureSpec struct {
ClusterName string `json:"clustername"`
VpcCidr string `json:"vpcCidr"`
PublicSubnetCidr string `json:"publicSubnetCidr"`
PrivateSubnetCidr string `json:"privateSubnetCidr"`
AvailabilityZone string `json:"availabilityZone"`
ExternalSecurityGroups bool `json:"externalSecurityGroups"`
}
type AWSInfrastructureState struct {
PrivateSubnetID *string `json:"privateSubnetID"`
PrivateSubnetState *string `json:"privateSubnetState"`
PublicSubnetID *string `json:"publicSubnetID"`
PublicSubnetState *string `json:"publicSubnetState"`
VpcState *string `json:"vpcState"`
NatGatewayState *string `json:"natGatewayState"`
PublicRouteTableID *string `json:"publicRouteTableID"`
PrivateRouteTableID *string `json:"privateRouteTableID"`
}
type AWSInfrastructure struct {
Spec AWSInfrastructureSpec `json:"spec"`
Context *E2EContext
VPC *ec2.Vpc
Subnets []*ec2.Subnet
RouteTables []*ec2.RouteTable
InternetGateway *ec2.InternetGateway
ElasticIP *ec2.Address
NatGateway *ec2.NatGateway
State AWSInfrastructureState `json:"state"`
Peering *ec2.VpcPeeringConnection
}
func (i *AWSInfrastructure) New(ais AWSInfrastructureSpec, e2eCtx *E2EContext) AWSInfrastructure {
i.Spec = ais
i.Context = e2eCtx
return *i
}
func (i *AWSInfrastructure) CreateVPC() AWSInfrastructure {
cv, err := CreateVPC(i.Context, i.Spec.ClusterName+"-vpc", i.Spec.VpcCidr)
if err != nil {
i.State.VpcState = ptr.To[string](fmt.Sprintf("failed: %v", err))
return *i
}
i.VPC = cv
i.State.VpcState = cv.State
return *i
}
func (i *AWSInfrastructure) RefreshVPCState() AWSInfrastructure {
if i.VPC == nil {
return *i
}
vpc, err := GetVPC(i.Context, *i.VPC.VpcId)
if err != nil {
return *i
}
if vpc != nil {
i.VPC = vpc
i.State.VpcState = vpc.State
}
return *i
}
func (i *AWSInfrastructure) CreatePublicSubnet() AWSInfrastructure {
subnet, err := CreateSubnet(i.Context, i.Spec.ClusterName, i.Spec.PublicSubnetCidr, i.Spec.AvailabilityZone, *i.VPC.VpcId, "public")
if err != nil {
i.State.PublicSubnetState = ptr.To[string]("failed")
return *i
}
i.State.PublicSubnetID = subnet.SubnetId
i.State.PublicSubnetState = subnet.State
i.Subnets = append(i.Subnets, subnet)
return *i
}
func (i *AWSInfrastructure) CreatePrivateSubnet() AWSInfrastructure {
subnet, err := CreateSubnet(i.Context, i.Spec.ClusterName, i.Spec.PrivateSubnetCidr, i.Spec.AvailabilityZone, *i.VPC.VpcId, "private")
if err != nil {
i.State.PrivateSubnetState = ptr.To[string]("failed")
return *i
}
i.State.PrivateSubnetID = subnet.SubnetId
i.State.PrivateSubnetState = subnet.State
i.Subnets = append(i.Subnets, subnet)
return *i
}
func (i *AWSInfrastructure) CreateInternetGateway() AWSInfrastructure {
igwC, err := CreateInternetGateway(i.Context, i.Spec.ClusterName+"-igw")
if err != nil {
return *i
}
_, aerr := AttachInternetGateway(i.Context, *igwC.InternetGatewayId, *i.VPC.VpcId)
if aerr != nil {
i.InternetGateway = igwC
return *i
}
i.InternetGateway = igwC
return *i
}
func (i *AWSInfrastructure) AllocateAddress() AWSInfrastructure {
aa, err := AllocateAddress(i.Context, i.Spec.ClusterName+"-eip")
if err != nil {
return *i
}
var addr *ec2.Address
Eventually(func(gomega Gomega) {
addr, _ = GetAddress(i.Context, *aa.AllocationId)
}, 2*time.Minute, 5*time.Second).Should(Succeed())
i.ElasticIP = addr
return *i
}
func (i *AWSInfrastructure) CreateNatGateway(ct string) AWSInfrastructure {
var s *ec2.Subnet
Eventually(func(gomega Gomega) {
s, _ = GetSubnetByName(i.Context, i.Spec.ClusterName+"-subnet-"+ct)
}, 2*time.Minute, 5*time.Second).Should(Succeed())
if s == nil {
return *i
}
ngwC, ngwce := CreateNatGateway(i.Context, i.Spec.ClusterName+"-nat", ct, *i.ElasticIP.AllocationId, *s.SubnetId)
if ngwce != nil {
return *i
}
if WaitForNatGatewayState(i.Context, *ngwC.NatGatewayId, "available") {
ngw, _ := GetNatGateway(i.Context, *ngwC.NatGatewayId)
i.NatGateway = ngw
i.State.NatGatewayState = ngw.State
return *i
}
i.NatGateway = ngwC
return *i
}
func (i *AWSInfrastructure) CreateRouteTable(subnetType string) AWSInfrastructure {
rt, err := CreateRouteTable(i.Context, i.Spec.ClusterName+"-rt-"+subnetType, *i.VPC.VpcId)
if err != nil {
return *i
}
switch subnetType {
case "public":
if a, _ := AssociateRouteTable(i.Context, *rt.RouteTableId, *i.State.PublicSubnetID); a != nil {
i.State.PublicRouteTableID = rt.RouteTableId
}
case "private":
if a, _ := AssociateRouteTable(i.Context, *rt.RouteTableId, *i.State.PrivateSubnetID); a != nil {
i.State.PrivateRouteTableID = rt.RouteTableId
}
}
return *i
}
func (i *AWSInfrastructure) GetRouteTable(rtID string) AWSInfrastructure {
rt, err := GetRouteTable(i.Context, rtID)
if err != nil {
return *i
}
if rt != nil {
i.RouteTables = append(i.RouteTables, rt)
}
return *i
}
// CreateInfrastructure creates a VPC, two subnets with appropriate tags based on type(private/public)
// an internet gateway, an elastic IP address, a NAT gateway, a route table for each subnet and
// routes to their respective gateway.
func (i *AWSInfrastructure) CreateInfrastructure() AWSInfrastructure {
i.CreateVPC()
Eventually(func() string {
return *i.RefreshVPCState().State.VpcState
}, 2*time.Minute, 5*time.Second).Should(Equal("available"), "Expected VPC state to eventually become 'available'")
By(fmt.Sprintf("Created VPC - %s", *i.VPC.VpcId))
if i.VPC != nil {
i.CreatePublicSubnet()
if i.State.PublicSubnetID != nil {
By(fmt.Sprintf("Created Public Subnet - %s", *i.State.PublicSubnetID))
}
i.CreatePrivateSubnet()
if i.State.PrivateSubnetID != nil {
By(fmt.Sprintf("Created Private Subnet - %s", *i.State.PrivateSubnetID))
}
i.CreateInternetGateway()
if i.InternetGateway != nil {
By(fmt.Sprintf("Created Internet Gateway - %s", *i.InternetGateway.InternetGatewayId))
}
}
i.AllocateAddress()
if i.ElasticIP != nil && i.ElasticIP.AllocationId != nil {
By(fmt.Sprintf("Created Elastic IP - %s", *i.ElasticIP.AllocationId))
i.CreateNatGateway("public")
if i.NatGateway != nil && i.NatGateway.NatGatewayId != nil {
WaitForNatGatewayState(i.Context, *i.NatGateway.NatGatewayId, "available")
By(fmt.Sprintf("Created NAT Gateway - %s", *i.NatGateway.NatGatewayId))
}
}
if len(i.Subnets) == 2 {
i.CreateRouteTable("public")
if i.State.PublicRouteTableID != nil {
By(fmt.Sprintf("Created public route table - %s", *i.State.PublicRouteTableID))
}
i.CreateRouteTable("private")
if i.State.PrivateRouteTableID != nil {
By(fmt.Sprintf("Created private route table - %s", *i.State.PrivateRouteTableID))
}
if i.InternetGateway != nil && i.InternetGateway.InternetGatewayId != nil {
CreateRoute(i.Context, *i.State.PublicRouteTableID, "0.0.0.0/0", nil, i.InternetGateway.InternetGatewayId, nil)
}
if i.NatGateway != nil && i.NatGateway.NatGatewayId != nil {
CreateRoute(i.Context, *i.State.PrivateRouteTableID, "0.0.0.0/0", i.NatGateway.NatGatewayId, nil, nil)
}
if i.State.PublicRouteTableID != nil {
i.GetRouteTable(*i.State.PublicRouteTableID)
}
if i.State.PrivateRouteTableID != nil {
i.GetRouteTable(*i.State.PrivateRouteTableID)
}
}
return *i
}
// DeleteInfrastructure has calls added to discover and delete potential orphaned resources created
// by CAPA. In an attempt to avoid dependency violations it works in the following order
// Instances, Load Balancers, Route Tables, NAT gateway, Elastic IP, Internet Gateway,
// Security Group Rules, Security Groups, Subnets, VPC.
func (i *AWSInfrastructure) DeleteInfrastructure() {
instances, _ := ListClusterEC2Instances(i.Context, i.Spec.ClusterName)
for _, instance := range instances {
if instance.State.Code != aws.Int64(48) {
By(fmt.Sprintf("Deleting orphaned instance: %s - %v", *instance.InstanceId, TerminateInstance(i.Context, *instance.InstanceId)))
}
}
WaitForInstanceState(i.Context, i.Spec.ClusterName, "terminated")
loadbalancers, _ := ListLoadBalancers(i.Context, i.Spec.ClusterName)
for _, lb := range loadbalancers {
By(fmt.Sprintf("Deleting orphaned load balancer: %s - %v", *lb.LoadBalancerName, DeleteLoadBalancer(i.Context, *lb.LoadBalancerName)))
}
for _, rt := range i.RouteTables {
for _, a := range rt.Associations {
By(fmt.Sprintf("Disassociating route table - %s - %v", *a.RouteTableAssociationId, DisassociateRouteTable(i.Context, *a.RouteTableAssociationId)))
}
By(fmt.Sprintf("Deleting route table - %s - %v", *rt.RouteTableId, DeleteRouteTable(i.Context, *rt.RouteTableId)))
}
if i.NatGateway != nil {
By(fmt.Sprintf("Deleting NAT Gateway - %s - %v", *i.NatGateway.NatGatewayId, DeleteNatGateway(i.Context, *i.NatGateway.NatGatewayId)))
WaitForNatGatewayState(i.Context, *i.NatGateway.NatGatewayId, "deleted")
}
if i.ElasticIP != nil {
By(fmt.Sprintf("Deleting Elastic IP - %s - %v", *i.ElasticIP.AllocationId, ReleaseAddress(i.Context, *i.ElasticIP.AllocationId)))
}
if i.InternetGateway != nil {
By(fmt.Sprintf("Detaching Internet Gateway - %s - %v", *i.InternetGateway.InternetGatewayId, DetachInternetGateway(i.Context, *i.InternetGateway.InternetGatewayId, *i.VPC.VpcId)))
By(fmt.Sprintf("Deleting Internet Gateway - %s - %v", *i.InternetGateway.InternetGatewayId, DeleteInternetGateway(i.Context, *i.InternetGateway.InternetGatewayId)))
}
sgGroups, _ := GetSecurityGroupsByVPC(i.Context, *i.VPC.VpcId)
for _, sg := range sgGroups {
if *sg.GroupName != "default" {
sgRules, _ := ListSecurityGroupRules(i.Context, *sg.GroupId)
for _, sgr := range sgRules {
var d bool
if *sgr.IsEgress {
for d = DeleteSecurityGroupRule(i.Context, *sgr.GroupId, *sgr.SecurityGroupRuleId, "egress"); !d; {
d = DeleteSecurityGroupRule(i.Context, *sgr.GroupId, *sgr.SecurityGroupRuleId, "egress")
}
By(fmt.Sprintf("Deleting Egress Security Group Rule - %s - %v", *sgr.SecurityGroupRuleId, d))
} else {
for d = DeleteSecurityGroupRule(i.Context, *sgr.GroupId, *sgr.SecurityGroupRuleId, "ingress"); !d; {
d = DeleteSecurityGroupRule(i.Context, *sgr.GroupId, *sgr.SecurityGroupRuleId, "ingress")
}
By(fmt.Sprintf("Deleting Ingress Security Group Rule - %s - %v", *sgr.SecurityGroupRuleId, d))
}
}
}
}
sgGroups, _ = GetSecurityGroupsByVPC(i.Context, *i.VPC.VpcId)
for _, sg := range sgGroups {
if *sg.GroupName != "default" {
By(fmt.Sprintf("Deleting Security Group - %s - %v", *sg.GroupId, DeleteSecurityGroup(i.Context, *sg.GroupId)))
}
}
for _, subnet := range i.Subnets {
By(fmt.Sprintf("Deleting Subnet - %s - %v", *subnet.SubnetId, DeleteSubnet(i.Context, *subnet.SubnetId)))
}
if i.VPC != nil {
By(fmt.Sprintf("Deleting VPC - %s - %v", *i.VPC.VpcId, DeleteVPC(i.Context, *i.VPC.VpcId)))
}
}
func NewAWSSession() client.ConfigProvider {
By("Getting an AWS IAM session - from environment")
region, err := credentials.ResolveRegion("")
Expect(err).NotTo(HaveOccurred())
config := aws.NewConfig().WithCredentialsChainVerboseErrors(true).WithRegion(region)
sess, err := session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: *config,
})
Expect(err).NotTo(HaveOccurred())
_, err = sess.Config.Credentials.Get()
Expect(err).NotTo(HaveOccurred())
return sess
}
func NewAWSSessionRepoWithKey(accessKey *iam.AccessKey) client.ConfigProvider {
By("Getting an AWS IAM session - from access key")
config := aws.NewConfig().WithCredentialsChainVerboseErrors(true).WithRegion("us-east-1")
config.Credentials = awscreds.NewStaticCredentials(*accessKey.AccessKeyId, *accessKey.SecretAccessKey, "")
sess, err := session.NewSessionWithOptions(session.Options{
Config: *config,
})
Expect(err).NotTo(HaveOccurred())
_, err = sess.Config.Credentials.Get()
Expect(err).NotTo(HaveOccurred())
return sess
}
func NewAWSSessionWithKey(accessKey *iam.AccessKey) client.ConfigProvider {
By("Getting an AWS IAM session - from access key")
region, err := credentials.ResolveRegion("")
Expect(err).NotTo(HaveOccurred())
config := aws.NewConfig().WithCredentialsChainVerboseErrors(true).WithRegion(region)
config.Credentials = awscreds.NewStaticCredentials(*accessKey.AccessKeyId, *accessKey.SecretAccessKey, "")
sess, err := session.NewSessionWithOptions(session.Options{
Config: *config,
})
Expect(err).NotTo(HaveOccurred())
_, err = sess.Config.Credentials.Get()
Expect(err).NotTo(HaveOccurred())
return sess
}
// createCloudFormationStack ensures the cloudformation stack is up to date.
func createCloudFormationStack(prov client.ConfigProvider, t *cfn_bootstrap.Template, tags map[string]string) error {
By(fmt.Sprintf("Creating AWS CloudFormation stack for AWS IAM resources: stack-name=%s", t.Spec.StackName))
cfnClient := cfn.New(prov)
// CloudFormation stack will clean up on a failure, we don't need an Eventually here.
// The `create` already does a WaitUntilStackCreateComplete.
cfnSvc := cloudformation.NewService(cfnClient)
if err := cfnSvc.ReconcileBootstrapNoUpdate(t.Spec.StackName, *renderCustomCloudFormation(t), tags); err != nil {
By(fmt.Sprintf("Error reconciling Cloud formation stack %v", err))
spewCloudFormationResources(cfnClient, t)
// always clean up on a failure because we could leak these resources and the next cloud formation create would
// fail with the same problem.
deleteMultitenancyRoles(prov)
deleteResourcesInCloudFormation(prov, t)
return err
}
spewCloudFormationResources(cfnClient, t)
return nil
}
func spewCloudFormationResources(cfnClient *cfn.CloudFormation, t *cfn_bootstrap.Template) {
output, err := cfnClient.DescribeStackEvents(&cfn.DescribeStackEventsInput{StackName: aws.String(t.Spec.StackName), NextToken: aws.String("1")})
if err != nil {
By(fmt.Sprintf("Error describin Cloud formation stack events %v, skipping", err))
} else {
By("========= Stack Event Output Begin =========")
for _, event := range output.StackEvents {
By(fmt.Sprintf("Event details for %s : Resource: %s, Status: %s, Reason: %s", aws.StringValue(event.LogicalResourceId), aws.StringValue(event.ResourceType), aws.StringValue(event.ResourceStatus), aws.StringValue(event.ResourceStatusReason)))
}
By("========= Stack Event Output End =========")
}
out, err := cfnClient.DescribeStackResources(&cfn.DescribeStackResourcesInput{
StackName: aws.String(t.Spec.StackName),
})
if err != nil {
By(fmt.Sprintf("Error describing Stack Resources %v, skipping", err))
} else {
By("========= Stack Resources Output Begin =========")
By("Resource\tType\tStatus")
for _, r := range out.StackResources {
By(fmt.Sprintf("%s\t%s\t%s\t%s",
aws.StringValue(r.ResourceType),
aws.StringValue(r.PhysicalResourceId),
aws.StringValue(r.ResourceStatus),
aws.StringValue(r.ResourceStatusReason)))
}
By("========= Stack Resources Output End =========")
}
}
func SetMultitenancyEnvVars(prov client.ConfigProvider) error {
for _, roles := range MultiTenancyRoles {
if err := roles.SetEnvVars(prov); err != nil {
return err
}
}
return nil
}
// Delete resources that already exists.
func deleteResourcesInCloudFormation(prov client.ConfigProvider, t *cfn_bootstrap.Template) {
iamSvc := iam.New(prov)
temp := *renderCustomCloudFormation(t)
var (
iamUsers []*cfn_iam.User
iamRoles []*cfn_iam.Role
instanceProfiles []*cfn_iam.InstanceProfile
policies []*cfn_iam.ManagedPolicy
groups []*cfn_iam.Group
)
// the deletion order of these resources is important. Policies need to be last,
// so they don't have any attached resources which prevents their deletion.
// temp.Resources is a map. Traversing that directly results in undetermined order.
for _, val := range temp.Resources {
switch val.AWSCloudFormationType() {
case configservice.ResourceTypeAwsIamUser:
user := val.(*cfn_iam.User)
iamUsers = append(iamUsers, user)
case configservice.ResourceTypeAwsIamRole:
role := val.(*cfn_iam.Role)
iamRoles = append(iamRoles, role)
case "AWS::IAM::InstanceProfile":
profile := val.(*cfn_iam.InstanceProfile)
instanceProfiles = append(instanceProfiles, profile)
case "AWS::IAM::ManagedPolicy":
policy := val.(*cfn_iam.ManagedPolicy)
policies = append(policies, policy)
case configservice.ResourceTypeAwsIamGroup:
group := val.(*cfn_iam.Group)
groups = append(groups, group)
}
}
for _, user := range iamUsers {
By(fmt.Sprintf("deleting the following user: %q", user.UserName))
repeat := false
Eventually(func(gomega Gomega) bool {
err := DeleteUser(prov, user.UserName)
if err != nil && !repeat {
By(fmt.Sprintf("failed to delete user '%q'; reason: %+v", user.UserName, err))
repeat = true
}
code, ok := awserrors.Code(err)
return err == nil || (ok && code == iam.ErrCodeNoSuchEntityException)
}, 5*time.Minute, 5*time.Second).Should(BeTrue(), fmt.Sprintf("Eventually failed deleting the user: %q", user.UserName))
}
for _, role := range iamRoles {
By(fmt.Sprintf("deleting the following role: %s", role.RoleName))
repeat := false
Eventually(func(gomega Gomega) bool {
err := DeleteRole(prov, role.RoleName)
if err != nil && !repeat {
By(fmt.Sprintf("failed to delete role '%s'; reason: %+v", role.RoleName, err))
repeat = true
}
code, ok := awserrors.Code(err)
return err == nil || (ok && code == iam.ErrCodeNoSuchEntityException)
}, 5*time.Minute, 5*time.Second).Should(BeTrue(), fmt.Sprintf("Eventually failed deleting the following role: %q", role.RoleName))
}
for _, profile := range instanceProfiles {
By(fmt.Sprintf("cleanup for profile with name '%s'", profile.InstanceProfileName))
repeat := false
Eventually(func(gomega Gomega) bool {
_, err := iamSvc.DeleteInstanceProfile(&iam.DeleteInstanceProfileInput{InstanceProfileName: aws.String(profile.InstanceProfileName)})
if err != nil && !repeat {
By(fmt.Sprintf("failed to delete role '%s'; reason: %+v", profile.InstanceProfileName, err))
repeat = true
}
code, ok := awserrors.Code(err)
return err == nil || (ok && code == iam.ErrCodeNoSuchEntityException)
}, 5*time.Minute, 5*time.Second).Should(BeTrue(), fmt.Sprintf("Eventually failed cleaning up profile with name %q", profile.InstanceProfileName))
}
for _, group := range groups {
repeat := false
Eventually(func(gomega Gomega) bool {
_, err := iamSvc.DeleteGroup(&iam.DeleteGroupInput{GroupName: aws.String(group.GroupName)})
if err != nil && !repeat {
By(fmt.Sprintf("failed to delete group '%s'; reason: %+v", group.GroupName, err))
repeat = true
}
code, ok := awserrors.Code(err)
return err == nil || (ok && code == iam.ErrCodeNoSuchEntityException)
}, 5*time.Minute, 5*time.Second).Should(BeTrue(), fmt.Sprintf("Eventually failed deleting group %q", group.GroupName))
}
for _, policy := range policies {
policies, err := iamSvc.ListPolicies(&iam.ListPoliciesInput{})
Expect(err).NotTo(HaveOccurred())
if len(policies.Policies) > 0 {
for _, p := range policies.Policies {
if aws.StringValue(p.PolicyName) == policy.ManagedPolicyName {
By(fmt.Sprintf("cleanup for policy '%s'", p.String()))
repeat := false
Eventually(func(gomega Gomega) bool {
response, err := iamSvc.DeletePolicy(&iam.DeletePolicyInput{
PolicyArn: p.Arn,
})
if err != nil && !repeat {
By(fmt.Sprintf("failed to delete policy '%s'; reason: %+v, response: %s", policy.Description, err, response.String()))
repeat = true
}
code, ok := awserrors.Code(err)
return err == nil || (ok && code == iam.ErrCodeNoSuchEntityException)
}, 5*time.Minute, 5*time.Second).Should(BeTrue(), fmt.Sprintf("Eventually failed to delete policy %q", p.String()))
// TODO: why is there a break here? Don't we want to clean up everything?
break
}
}
}
}
}
// TODO: remove once test infra accounts are fixed.
func deleteMultitenancyRoles(prov client.ConfigProvider) {
if err := DeleteRole(prov, "multi-tenancy-role"); err != nil {
By(fmt.Sprintf("failed to delete role multi-tenancy-role %s", err))
}
if err := DeleteRole(prov, "multi-tenancy-nested-role"); err != nil {
By(fmt.Sprintf("failed to delete role multi-tenancy-nested-role %s", err))
}
}
// detachAllPoliciesForRole detaches all policies for role.
func detachAllPoliciesForRole(prov client.ConfigProvider, name string) error {
iamSvc := iam.New(prov)
input := &iam.ListAttachedRolePoliciesInput{
RoleName: &name,
}
policies, err := iamSvc.ListAttachedRolePolicies(input)
if err != nil {
return errors.New("error fetching policies for role")
}
for _, p := range policies.AttachedPolicies {
input := &iam.DetachRolePolicyInput{
RoleName: aws.String(name),
PolicyArn: p.PolicyArn,
}
_, err := iamSvc.DetachRolePolicy(input)
if err != nil {
return errors.New("failed detaching policy from a role")
}
}
return nil
}
// DeleteUser deletes an IAM user in a best effort manner.
func DeleteUser(prov client.ConfigProvider, name string) error {
iamSvc := iam.New(prov)
// if role does not exist, return.
_, err := iamSvc.GetUser(&iam.GetUserInput{UserName: aws.String(name)})
if err != nil {
return err
}
_, err = iamSvc.DeleteUser(&iam.DeleteUserInput{UserName: aws.String(name)})
if err != nil {
return err
}
return nil
}
// DeleteRole deletes roles in a best effort manner.
func DeleteRole(prov client.ConfigProvider, name string) error {
iamSvc := iam.New(prov)
// if role does not exist, return.
_, err := iamSvc.GetRole(&iam.GetRoleInput{RoleName: aws.String(name)})
if err != nil {
return err
}
if err := detachAllPoliciesForRole(prov, name); err != nil {
return err
}
_, err = iamSvc.DeleteRole(&iam.DeleteRoleInput{RoleName: aws.String(name)})
if err != nil {
return err
}
return nil
}
func GetPolicyArn(prov client.ConfigProvider, name string) string {
iamSvc := iam.New(prov)
policyList, err := iamSvc.ListPolicies(&iam.ListPoliciesInput{
Scope: aws.String(iam.PolicyScopeTypeLocal),
})
Expect(err).NotTo(HaveOccurred())
for _, policy := range policyList.Policies {
if aws.StringValue(policy.PolicyName) == name {
return aws.StringValue(policy.Arn)
}
}
return ""
}
func logAccountDetails(prov client.ConfigProvider) {
By("Getting AWS account details")
stsSvc := sts.New(prov)
output, err := stsSvc.GetCallerIdentity(&sts.GetCallerIdentityInput{})
if err != nil {
fmt.Fprintf(GinkgoWriter, "couldn't get sts caller identity: err=%s", err)
return
}
fmt.Fprintf(GinkgoWriter, "Using AWS account: %s", *output.Account)
}
// deleteCloudFormationStack removes the provisioned clusterawsadm stack.
func deleteCloudFormationStack(prov client.ConfigProvider, t *cfn_bootstrap.Template) {
By(fmt.Sprintf("Deleting %s CloudFormation stack", t.Spec.StackName))
CFN := cfn.New(prov)
cfnSvc := cloudformation.NewService(CFN)
err := cfnSvc.DeleteStack(t.Spec.StackName, nil)
if err != nil {
var retainResources []*string
out, err := CFN.DescribeStackResources(&cfn.DescribeStackResourcesInput{StackName: aws.String(t.Spec.StackName)})
Expect(err).NotTo(HaveOccurred())
for _, v := range out.StackResources {
if aws.StringValue(v.ResourceStatus) == cfn.ResourceStatusDeleteFailed {
retainResources = append(retainResources, v.LogicalResourceId)
}
}
err = cfnSvc.DeleteStack(t.Spec.StackName, retainResources)
Expect(err).NotTo(HaveOccurred())
}
err = CFN.WaitUntilStackDeleteComplete(&cfn.DescribeStacksInput{
StackName: aws.String(t.Spec.StackName),
})
Expect(err).NotTo(HaveOccurred())
}
func ensureTestImageUploaded(e2eCtx *E2EContext) error {
sessionForRepo := NewAWSSessionRepoWithKey(e2eCtx.Environment.BootstrapAccessKey)
ecrSvc := ecrpublic.New(sessionForRepo)
repoName := ""
if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) {
output, err := ecrSvc.CreateRepository(&ecrpublic.CreateRepositoryInput{
RepositoryName: aws.String("capa/update"),
CatalogData: &ecrpublic.RepositoryCatalogDataInput{
AboutText: aws.String("Created by cluster-api-provider-aws/test/e2e/shared/aws.go for E2E tests"),
},
})
if err != nil {
if !awserrors.IsRepositoryExists(err) {
return false, err
}
out, err := ecrSvc.DescribeRepositories(&ecrpublic.DescribeRepositoriesInput{RepositoryNames: []*string{aws.String("capa/update")}})
if err != nil || len(out.Repositories) == 0 {
return false, err
}
repoName = aws.StringValue(out.Repositories[0].RepositoryUri)
} else {
repoName = aws.StringValue(output.Repository.RepositoryUri)
}
return true, nil
}, awserrors.UnrecognizedClientException); err != nil {
return err
}
cmd := exec.Command("docker", "inspect", "--format='{{index .Id}}'", "gcr.io/k8s-staging-cluster-api/capa-manager:e2e")
var stdOut bytes.Buffer
cmd.Stdout = &stdOut
err := cmd.Run()
if err != nil {
return err
}
imageSha := strings.ReplaceAll(strings.TrimSuffix(stdOut.String(), "\n"), "'", "")
ecrImageName := repoName + ":e2e"
cmd = exec.Command("docker", "tag", imageSha, ecrImageName) //nolint:gosec
err = cmd.Run()
if err != nil {
return err
}
outToken, err := ecrSvc.GetAuthorizationToken(&ecrpublic.GetAuthorizationTokenInput{})
if err != nil {
return err
}
// Auth token is in username:password format. To login using it, we need to decode first and separate password and username
decodedUsernamePassword, _ := b64.StdEncoding.DecodeString(aws.StringValue(outToken.AuthorizationData.AuthorizationToken))
strList := strings.Split(string(decodedUsernamePassword), ":")
if len(strList) != 2 {
return errors.New("failed to decode ECR authentication token")
}
cmd = exec.Command("docker", "login", "--username", strList[0], "--password", strList[1], "public.ecr.aws") //nolint:gosec
err = cmd.Run()
if err != nil {
return err
}
cmd = exec.Command("docker", "push", ecrImageName)
err = cmd.Run()
if err != nil {
return err
}
e2eCtx.E2EConfig.Variables["CAPI_IMAGES_REGISTRY"] = repoName
e2eCtx.E2EConfig.Variables["E2E_IMAGE_TAG"] = "e2e"
return nil
}
// ensureNoServiceLinkedRoles removes an auto-created IAM role, and tests
// the controller's IAM permissions to use ELB and Spot instances successfully.
func ensureNoServiceLinkedRoles(prov client.ConfigProvider) {
By("Deleting AWS IAM Service Linked Role: role-name=AWSServiceRoleForElasticLoadBalancing")
iamSvc := iam.New(prov)
_, err := iamSvc.DeleteServiceLinkedRole(&iam.DeleteServiceLinkedRoleInput{
RoleName: aws.String("AWSServiceRoleForElasticLoadBalancing"),
})
if code, _ := awserrors.Code(err); code != iam.ErrCodeNoSuchEntityException {
Expect(err).NotTo(HaveOccurred())
}
By("Deleting AWS IAM Service Linked Role: role-name=AWSServiceRoleForEC2Spot")
_, err = iamSvc.DeleteServiceLinkedRole(&iam.DeleteServiceLinkedRoleInput{
RoleName: aws.String("AWSServiceRoleForEC2Spot"),
})
if code, _ := awserrors.Code(err); code != iam.ErrCodeNoSuchEntityException {
Expect(err).NotTo(HaveOccurred())
}
}
// ensureSSHKeyPair ensures A SSH key is present under the name.
func ensureSSHKeyPair(prov client.ConfigProvider, keyPairName string) {
By(fmt.Sprintf("Ensuring presence of SSH key in EC2: key-name=%s", keyPairName))
ec2c := ec2.New(prov)
_, err := ec2c.CreateKeyPair(&ec2.CreateKeyPairInput{KeyName: aws.String(keyPairName)})
if code, _ := awserrors.Code(err); code != "InvalidKeyPair.Duplicate" {
Expect(err).NotTo(HaveOccurred())
}
}
func ensureStackTags(prov client.ConfigProvider, stackName string, expectedTags map[string]string) {
By(fmt.Sprintf("Ensuring AWS CloudFormation stack is created or updated with the specified tags: stack-name=%s", stackName))
CFN := cfn.New(prov)
r, err := CFN.DescribeStacks(&cfn.DescribeStacksInput{StackName: &stackName})
Expect(err).NotTo(HaveOccurred())
stacks := r.Stacks
Expect(len(stacks)).To(BeNumerically("==", 1))
stackTags := stacks[0].Tags
Expect(len(stackTags)).To(BeNumerically("==", len(expectedTags)))
for _, tag := range stackTags {
Expect(*tag.Value).To(BeIdenticalTo(expectedTags[*tag.Key]))
}
}
// encodeCredentials leverages clusterawsadm to encode AWS credentials.
func encodeCredentials(accessKey *iam.AccessKey, region string) string {
creds := credentials.AWSCredentials{
Region: region,
AccessKeyID: *accessKey.AccessKeyId,
SecretAccessKey: *accessKey.SecretAccessKey,
}
encCreds, err := creds.RenderBase64EncodedAWSDefaultProfile()
Expect(err).NotTo(HaveOccurred())
return encCreds
}
// newUserAccessKey generates a new AWS Access Key pair based off of the
// bootstrap user. This tests that the CloudFormation policy is correct.
func newUserAccessKey(prov client.ConfigProvider, userName string) *iam.AccessKey {
iamSvc := iam.New(prov)
keyOuts, _ := iamSvc.ListAccessKeys(&iam.ListAccessKeysInput{
UserName: aws.String(userName),
})
for i := range keyOuts.AccessKeyMetadata {
By(fmt.Sprintf("Deleting an existing access key: user-name=%s", userName))
_, err := iamSvc.DeleteAccessKey(&iam.DeleteAccessKeyInput{
UserName: aws.String(userName),
AccessKeyId: keyOuts.AccessKeyMetadata[i].AccessKeyId,
})
Expect(err).NotTo(HaveOccurred())
}
By(fmt.Sprintf("Creating an access key: user-name=%s", userName))
out, err := iamSvc.CreateAccessKey(&iam.CreateAccessKeyInput{UserName: aws.String(userName)})
Expect(err).NotTo(HaveOccurred())
Expect(out.AccessKey).ToNot(BeNil())
return &iam.AccessKey{
AccessKeyId: out.AccessKey.AccessKeyId,
SecretAccessKey: out.AccessKey.SecretAccessKey,
}
}
func DumpCloudTrailEvents(e2eCtx *E2EContext) {
client := cloudtrail.New(e2eCtx.BootstrapUserAWSSession)
events := []*cloudtrail.Event{}
err := client.LookupEventsPages(
&cloudtrail.LookupEventsInput{
StartTime: aws.Time(e2eCtx.StartOfSuite),
EndTime: aws.Time(time.Now()),
},
func(page *cloudtrail.LookupEventsOutput, lastPage bool) bool {
events = append(events, page.Events...)
return !lastPage
},
)
if err != nil {
fmt.Fprintf(GinkgoWriter, "couldn't get AWS CloudTrail events: err=%v", err)
}
logPath := filepath.Join(e2eCtx.Settings.ArtifactFolder, "cloudtrail-events.yaml")
dat, err := yaml.Marshal(events)
if err != nil {
fmt.Fprintf(GinkgoWriter, "Failed to marshal AWS CloudTrail events: err=%v", err)
}
if err := os.WriteFile(logPath, dat, 0o600); err != nil {
fmt.Fprintf(GinkgoWriter, "couldn't write cloudtrail events to file: file=%s err=%s", logPath, err)
return
}
}
// conformanceImageID looks up a specific image for a given
// Kubernetes version in the e2econfig.
func conformanceImageID(e2eCtx *E2EContext) string {
ver := e2eCtx.E2EConfig.GetVariable("CONFORMANCE_CI_ARTIFACTS_KUBERNETES_VERSION")
amiName := AMIPrefix + ver + "*"
By(fmt.Sprintf("Searching for AMI: name=%s", amiName))
ec2Svc := ec2.New(e2eCtx.AWSSession)
filters := []*ec2.Filter{
{
Name: aws.String("name"),
Values: []*string{aws.String(amiName)},
},
}
filters = append(filters, &ec2.Filter{
Name: aws.String("owner-id"),
Values: []*string{aws.String(DefaultImageLookupOrg)},
})
resp, err := ec2Svc.DescribeImages(&ec2.DescribeImagesInput{
Filters: filters,
})
Expect(err).NotTo(HaveOccurred())
Expect(len(resp.Images)).To(Not(BeZero()))
imageID := aws.StringValue(resp.Images[0].ImageId)
By(fmt.Sprintf("Using AMI: image-id=%s", imageID))
return imageID
}
func GetAvailabilityZones(sess client.ConfigProvider) []*ec2.AvailabilityZone {
ec2Client := ec2.New(sess)
azs, err := ec2Client.DescribeAvailabilityZonesWithContext(context.TODO(), nil)
Expect(err).NotTo(HaveOccurred())
return azs.AvailabilityZones
}
type ServiceQuota struct {
ServiceCode string
QuotaName string
QuotaCode string
Value int
DesiredMinimumValue int
RequestStatus string
}
func EnsureServiceQuotas(sess client.ConfigProvider) (map[string]*ServiceQuota, map[string]*servicequotas.ServiceQuota) {
limitedResources := getLimitedResources()
serviceQuotasClient := servicequotas.New(sess)
originalQuotas := map[string]*servicequotas.ServiceQuota{}
for k, v := range limitedResources {
out, err := serviceQuotasClient.GetServiceQuota(&servicequotas.GetServiceQuotaInput{
QuotaCode: aws.String(v.QuotaCode),
ServiceCode: aws.String(v.ServiceCode),
})
Expect(err).NotTo(HaveOccurred())
originalQuotas[k] = out.Quota
v.Value = int(aws.Float64Value(out.Quota.Value))
limitedResources[k] = v
if v.Value < v.DesiredMinimumValue {
v.attemptRaiseServiceQuotaRequest(serviceQuotasClient)
}
}
return limitedResources, originalQuotas
}
func (s *ServiceQuota) attemptRaiseServiceQuotaRequest(serviceQuotasClient *servicequotas.ServiceQuotas) {
s.updateServiceQuotaRequestStatus(serviceQuotasClient)
if s.RequestStatus == "" {
s.raiseServiceRequest(serviceQuotasClient)
}
}
func (s *ServiceQuota) raiseServiceRequest(serviceQuotasClient *servicequotas.ServiceQuotas) {
fmt.Printf("Requesting service quota increase for %s/%s to %d\n", s.ServiceCode, s.QuotaName, s.DesiredMinimumValue)
out, err := serviceQuotasClient.RequestServiceQuotaIncrease(
&servicequotas.RequestServiceQuotaIncreaseInput{
DesiredValue: aws.Float64(float64(s.DesiredMinimumValue)),
ServiceCode: aws.String(s.ServiceCode),
QuotaCode: aws.String(s.QuotaCode),
},
)
if err != nil {
fmt.Printf("Unable to raise quota for %s/%s: %s\n", s.ServiceCode, s.QuotaName, err)
} else {
s.RequestStatus = aws.StringValue(out.RequestedQuota.Status)
}
}
func (s *ServiceQuota) updateServiceQuotaRequestStatus(serviceQuotasClient *servicequotas.ServiceQuotas) {
params := &servicequotas.ListRequestedServiceQuotaChangeHistoryInput{
ServiceCode: aws.String(s.ServiceCode),
}
latestRequest := &servicequotas.RequestedServiceQuotaChange{}
_ = serviceQuotasClient.ListRequestedServiceQuotaChangeHistoryPages(params,
func(page *servicequotas.ListRequestedServiceQuotaChangeHistoryOutput, lastPage bool) bool {
for _, v := range page.RequestedQuotas {
if int(aws.Float64Value(v.DesiredValue)) >= s.DesiredMinimumValue && aws.StringValue(v.QuotaCode) == s.QuotaCode && aws.TimeValue(v.Created).After(aws.TimeValue(latestRequest.Created)) {
latestRequest = v
}
}
return !lastPage