-
-
Notifications
You must be signed in to change notification settings - Fork 360
/
Copy pathexamples_complete_test.go
215 lines (179 loc) · 7.29 KB
/
examples_complete_test.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
package test
import (
"encoding/base64"
"fmt"
testStructure "github.com/gruntwork-io/terratest/modules/test-structure"
"k8s.io/apimachinery/pkg/util/runtime"
"regexp"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/gruntwork-io/terratest/modules/random"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"sigs.k8s.io/aws-iam-authenticator/pkg/token"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/eks"
)
func newClientset(cluster *eks.Cluster) (*kubernetes.Clientset, error) {
gen, err := token.NewGenerator(true, false)
if err != nil {
return nil, err
}
opts := &token.GetTokenOptions{
ClusterID: aws.StringValue(cluster.Name),
}
tok, err := gen.GetWithOptions(opts)
if err != nil {
return nil, err
}
ca, err := base64.StdEncoding.DecodeString(aws.StringValue(cluster.CertificateAuthority.Data))
if err != nil {
return nil, err
}
clientset, err := kubernetes.NewForConfig(
&rest.Config{
Host: aws.StringValue(cluster.Endpoint),
BearerToken: tok.Token,
TLSClientConfig: rest.TLSClientConfig{
CAData: ca,
},
},
)
if err != nil {
return nil, err
}
return clientset, nil
}
// Test the Terraform module in examples/complete using Terratest.
func TestExamplesComplete(t *testing.T) {
randId := strings.ToLower(random.UniqueId())
attributes := []string{randId}
terraformOptions := &terraform.Options{
// The path to where our Terraform code is located
TerraformDir: "../../examples/complete",
Upgrade: true,
// Variables to pass to our Terraform code using -var-file options
VarFiles: []string{"fixtures.us-east-2.tfvars"},
Vars: map[string]interface{}{
"attributes": attributes,
},
}
// At the end of the test, run `terraform destroy` to clean up any resources that were created
defer terraform.Destroy(t, terraformOptions)
// If Go runtime crushes, run `terraform destroy` to clean up any resources that were created
defer runtime.HandleCrash(func(i interface{}) {
terraform.Destroy(t, terraformOptions)
})
// This will run `terraform init` and `terraform apply` and fail the test if there are any errors
terraform.InitAndApply(t, terraformOptions)
// Run `terraform output` to get the value of an output variable
vpcCidr := terraform.Output(t, terraformOptions, "vpc_cidr")
// Verify we're getting back the outputs we expect
assert.Equal(t, "172.16.0.0/16", vpcCidr)
// Run `terraform output` to get the value of an output variable
privateSubnetCidrs := terraform.OutputList(t, terraformOptions, "private_subnet_cidrs")
// Verify we're getting back the outputs we expect
assert.Equal(t, []string{"172.16.0.0/19", "172.16.32.0/19"}, privateSubnetCidrs)
// Run `terraform output` to get the value of an output variable
publicSubnetCidrs := terraform.OutputList(t, terraformOptions, "public_subnet_cidrs")
// Verify we're getting back the outputs we expect
assert.Equal(t, []string{"172.16.96.0/19", "172.16.128.0/19"}, publicSubnetCidrs)
// Run `terraform output` to get the value of an output variable
eksClusterId := terraform.Output(t, terraformOptions, "eks_cluster_id")
// Verify we're getting back the outputs we expect
assert.Equal(t, "eg-test-eks-"+randId+"-cluster", eksClusterId)
// Run `terraform output` to get the value of an output variable
eksNodeGroupId := terraform.Output(t, terraformOptions, "eks_node_group_id")
// Verify we're getting back the outputs we expect
// The node group ID will have a random pet name appended to it
assert.Contains(t, eksNodeGroupId, "eg-test-eks-"+randId+"-cluster:eg-test-eks-"+randId+"-workers-")
// Run `terraform output` to get the value of an output variable
eksNodeGroupRoleName := terraform.Output(t, terraformOptions, "eks_node_group_role_name")
// Verify we're getting back the outputs we expect
assert.Equal(t, "eg-test-eks-"+randId+"-workers", eksNodeGroupRoleName)
// Run `terraform output` to get the value of an output variable
eksNodeGroupStatus := terraform.Output(t, terraformOptions, "eks_node_group_status")
// Verify we're getting back the outputs we expect
assert.Equal(t, "ACTIVE", eksNodeGroupStatus)
// Wait for the worker nodes to join the cluster
// https://github.com/kubernetes/client-go
// https://www.rushtehrani.com/post/using-kubernetes-api
// https://rancher.com/using-kubernetes-api-go-kubecon-2017-session-recap
// https://gianarb.it/blog/kubernetes-shared-informer
// https://stackoverflow.com/questions/60547409/unable-to-obtain-kubeconfig-of-an-aws-eks-cluster-in-go-code/60573982#60573982
fmt.Println("Waiting for worker nodes to join the EKS cluster")
clusterName := "eg-test-eks-" + randId + "-cluster"
region := "us-east-2"
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String(region),
}))
eksSvc := eks.New(sess)
input := &eks.DescribeClusterInput{
Name: aws.String(clusterName),
}
result, err := eksSvc.DescribeCluster(input)
assert.NoError(t, err)
clientset, err := newClientset(result.Cluster)
assert.NoError(t, err)
factory := informers.NewSharedInformerFactory(clientset, 0)
informer := factory.Core().V1().Nodes().Informer()
stopChannel := make(chan struct{})
var countOfWorkerNodes uint64 = 0
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
node := obj.(*corev1.Node)
fmt.Printf("Worker Node %s has joined the EKS cluster at %s\n", node.Name, node.CreationTimestamp)
atomic.AddUint64(&countOfWorkerNodes, 1)
if countOfWorkerNodes > 1 {
close(stopChannel)
}
},
})
go informer.Run(stopChannel)
select {
case <-stopChannel:
msg := "All worker nodes have joined the EKS cluster"
fmt.Println(msg)
case <-time.After(5 * time.Minute):
msg := "Not all worker nodes have joined the EKS cluster"
fmt.Println(msg)
assert.Fail(t, msg)
}
}
func TestExamplesCompleteDisabled(t *testing.T) {
t.Parallel()
randID := strings.ToLower(random.UniqueId())
attributes := []string{randID}
rootFolder := "../../"
terraformFolderRelativeToRoot := "examples/complete"
varFiles := []string{"fixtures.us-east-2.tfvars"}
tempTestFolder := testStructure.CopyTerraformFolderToTemp(t, rootFolder, terraformFolderRelativeToRoot)
terraformOptions := &terraform.Options{
// The path to where our Terraform code is located
TerraformDir: tempTestFolder,
Upgrade: true,
// Variables to pass to our Terraform code using -var-file options
VarFiles: varFiles,
Vars: map[string]interface{}{
"attributes": attributes,
"enabled": false,
},
}
// At the end of the test, run `terraform destroy` to clean up any resources that were created
defer terraform.Destroy(t, terraformOptions)
// This will run `terraform init` and `terraform apply` and fail the test if there are any errors
results := terraform.InitAndApply(t, terraformOptions)
// Should complete successfully without creating or changing any resources.
// Extract the "Resources:" section of the output to make the error message more readable.
re := regexp.MustCompile(`Resources: [^.]+\.`)
match := re.FindString(results)
assert.Equal(t, "Resources: 0 added, 0 changed, 0 destroyed.", match, "Applying with enabled=false should not create any resources")
}