forked from rancher/terraform-provider-rke
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_rke_cluster_test.go
351 lines (317 loc) · 10.1 KB
/
resource_rke_cluster_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
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
package rke
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
"testing"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
"github.com/rancher/rke/cluster"
"github.com/rancher/rke/pki"
v3 "github.com/rancher/rke/types"
"gopkg.in/yaml.v2"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var (
testAccRKEClusterNodes = []string{"tf-testacc1", "tf-testacc2"}
)
func TestAccResourceRKECluster(t *testing.T) {
resource.Test(t, resource.TestCase{
Providers: testAccProviders,
CheckDestroy: testAccCheckRKEClusterDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckRKEConfigBasic(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("rke_cluster.cluster", "nodes.#", "1"),
resource.TestCheckResourceAttr("rke_cluster.cluster", "nodes.0.address", testAccRKEClusterNodes[0]),
resource.TestMatchResourceAttr("rke_cluster.cluster", "kube_config_yaml", regexp.MustCompile(".+")), // should be not empty
testAccCheckTempFilesExists(),
),
},
{
Config: testAccCheckRKEConfigUpdate(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("rke_cluster.cluster", "nodes.#", "1"),
resource.TestCheckResourceAttr("rke_cluster.cluster", "nodes.0.address", testAccRKEClusterNodes[0]),
resource.TestMatchResourceAttr("rke_cluster.cluster", "kube_config_yaml", regexp.MustCompile(".+")), // should be not empty
resource.TestMatchResourceAttr("rke_cluster.cluster", "rke_cluster_yaml", regexp.MustCompile(".+")), // should be not empty
resource.TestCheckResourceAttr("rke_cluster.cluster", "nodes.0.labels.%", "2"),
resource.TestCheckResourceAttr("rke_cluster.cluster", "nodes.0.labels.foo", "foo"),
resource.TestCheckResourceAttr("rke_cluster.cluster", "nodes.0.labels.bar", "bar"),
testAccCheckTempFilesExists(),
),
},
{
Config: testAccCheckRKEConfigBasic(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("rke_cluster.cluster", "nodes.#", "1"),
testAccCheckRKENodeExists("rke_cluster.cluster", testAccRKEClusterNodes[0]),
testAccCheckRKEClusterYAML("rke_cluster.cluster", 1),
),
},
{
Config: testAccCheckRKEConfigBasic2Nodes(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("rke_cluster.cluster", "nodes.#", "2"),
testAccCheckRKENodeExists("rke_cluster.cluster", testAccRKEClusterNodes[0], testAccRKEClusterNodes[1]),
testAccCheckRKEClusterYAML("rke_cluster.cluster", 2),
),
},
{
Config: testAccCheckRKEConfigBasic(),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("rke_cluster.cluster", "nodes.#", "1"),
testAccCheckRKENodeExists("rke_cluster.cluster", testAccRKEClusterNodes[0]),
testAccCheckRKEClusterYAML("rke_cluster.cluster", 1),
),
},
},
})
}
func testAccCheckTempFilesExists() resource.TestCheckFunc {
return func(s *terraform.State) error {
if _, err := os.Stat(pki.ClusterConfig); err == nil {
return fmt.Errorf("temporary file %q is still exists", pki.ClusterConfig)
}
kubeClusterYAML := fmt.Sprintf("%s%s", pki.KubeAdminConfigPrefix, pki.ClusterConfig)
if _, err := os.Stat(kubeClusterYAML); err == nil {
return fmt.Errorf("temporary file %q is still exists", kubeClusterYAML)
}
rkeStatePath := cluster.GetStateFilePath(pki.ClusterConfig, "")
if _, err := os.Stat(rkeStatePath); err == nil {
return fmt.Errorf("temporary file %q is still exists", rkeStatePath)
}
return nil
}
}
func testAccCheckRKENodeExists(n string, nodeIPs ...string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("not found: %s", n)
}
if rs.Primary.ID == "" {
return errors.New("no ID of rke_cluster is set")
}
masterURL := rs.Primary.Attributes["api_server_url"]
strKubeConfig := rs.Primary.Attributes["kube_config_yaml"]
if strKubeConfig == "" {
return errors.New("kube_config_yaml is empty")
}
// save kube_config_yaml to tmpfile
tmpFile, err := ioutil.TempFile("", "test_acc_rke_cluster_kube_config_")
if err != nil {
return errors.New("failed to create temp file")
}
defer os.Remove(tmpFile.Name()) // nolint
if err := ioutil.WriteFile(tmpFile.Name(), []byte(strKubeConfig), 0644); err != nil {
return errors.New("failed to create temp file")
}
// create kubernetes client
kubeConfig, err := clientcmd.BuildConfigFromFlags(masterURL, tmpFile.Name())
if err != nil {
return err
}
client, err := kubernetes.NewForConfig(kubeConfig)
if err != nil {
return err
}
// getNodes
nodes, err := client.CoreV1().Nodes().List(context.Background(), meta_v1.ListOptions{})
if err != nil {
return err
}
for _, ip := range nodeIPs {
found := false
for _, node := range nodes.Items {
for _, addr := range node.Status.Addresses {
if ip == addr.Address {
found = true
break
}
}
}
if !found {
return fmt.Errorf("node %q not found", ip)
}
}
return nil
}
}
func testAccCheckRKEClusterYAML(n string, expectNodeLen int) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("not found: %s", n)
}
if rs.Primary.ID == "" {
return errors.New("no ID of rke_cluster is set")
}
v := rs.Primary.Attributes["rke_cluster_yaml"]
var rkeConfig v3.RancherKubernetesEngineConfig
if err := yaml.Unmarshal([]byte(v), &rkeConfig); err != nil {
return err
}
if len(rkeConfig.Nodes) != expectNodeLen {
return fmt.Errorf("rke_cluster_yaml has unexpected nodes. expect: %d, actual: %d", expectNodeLen, len(rkeConfig.Nodes))
}
return nil
}
}
func testAccCheckRKEClusterDestroy(s *terraform.State) error {
for _, rs := range s.RootModule().Resources {
if rs.Type != "rke_cluster" {
continue
}
masterURL := rs.Primary.Attributes["api_server_url"]
req, err := http.NewRequest("GET", masterURL, nil)
if err != nil {
continue
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
hc := &http.Client{Timeout: 2 * time.Second, Transport: tr}
resp, err := hc.Do(req)
if resp != nil {
resp.Body.Close() // nolint
}
if err != nil {
continue
}
return errors.New("RKE cluster still exists")
}
// check tmp files
return testAccCheckTempFilesExists()(s)
}
func testAccCheckRKEConfigBasic() string {
return fmt.Sprintf(`
resource rke_cluster "cluster" {
ignore_docker_version = true
addon_job_timeout = 60
dind = true
dind_dns_server = "8.8.8.8"
nodes {
address = "%s"
user = "docker"
role = ["controlplane", "worker", "etcd"]
}
upgrade_strategy {
drain = true
max_unavailable_worker = "20%%"
}
}
`, testAccRKEClusterNodes[0])
}
func testAccCheckRKEConfigUpdate() string {
return fmt.Sprintf(`
resource rke_cluster "cluster" {
ignore_docker_version = true
addon_job_timeout = 60
dind = true
dind_dns_server = "8.8.8.8"
nodes {
address = "%s"
user = "docker"
role = ["controlplane", "worker", "etcd"]
labels = {
foo = "foo"
bar = "bar"
}
}
services {
kube_api {
audit_log {
enabled = true
configuration {
max_age = 5
max_backup = 5
max_size = 100
path = "-"
format = "json"
policy = "{\"apiVersion\":\"audit.k8s.io/v1\",\"kind\":\"Policy\",\"metadata\":{\"creationTimestamp\":null},\"rules\":[{\"level\":\"RequestResponse\",\"resources\":[{\"group\":\"\",\"resources\":[\"pods\"]}]}]}"
}
}
event_rate_limit {
configuration = "apiVersion: eventratelimit.admission.k8s.io/v1alpha1\nkind: Configuration\nlimits:\n- type: Server\n burst: 35000\n qps: 6000\n"
enabled = true
}
secrets_encryption_config {
custom_config = "apiVersion: apiserver.config.k8s.io/v1\nkind: EncryptionConfiguration\nresources:\n- providers:\n - aescbc:\n keys:\n - name: k-gt6hv\n secret: RTczRjFDODMwQzAyMDVBREU4NDJBMUZFNDhCNzM5N0I=\n - identity: {}\n resources:\n - secrets\n"
enabled = true
}
}
}
upgrade_strategy {
drain = true
max_unavailable_worker = "20%%"
drain_input {
ignore_daemon_sets = true
timeout = 120
delete_local_data = true
}
}
}
`, testAccRKEClusterNodes[0])
}
func testAccCheckRKEConfigBasic2Nodes() string {
return fmt.Sprintf(`
resource rke_cluster "cluster" {
ignore_docker_version = true
addon_job_timeout = 60
dind = true
dind_dns_server = "8.8.8.8"
nodes {
address = "%s"
user = "docker"
role = ["controlplane", "worker", "etcd"]
}
nodes {
address = "%s"
user = "docker"
role = ["worker"]
}
services {
kube_api {
audit_log {
enabled = true
configuration {
max_age = 5
max_backup = 5
max_size = 100
path = "-"
format = "json"
policy = "{\"apiVersion\":\"audit.k8s.io/v1\",\"kind\":\"Policy\",\"metadata\":{\"creationTimestamp\":null},\"rules\":[{\"level\":\"RequestResponse\",\"resources\":[{\"group\":\"\",\"resources\":[\"pods\"]}]}]}"
}
}
event_rate_limit {
configuration = "apiVersion: eventratelimit.admission.k8s.io/v1alpha1\nkind: Configuration\nlimits:\n- type: Server\n burst: 35000\n qps: 6000\n"
enabled = true
}
secrets_encryption_config {
custom_config = "apiVersion: apiserver.config.k8s.io/v1\nkind: EncryptionConfiguration\nresources:\n- providers:\n - aescbc:\n keys:\n - name: k-gt6hv\n secret: RTczRjFDODMwQzAyMDVBREU4NDJBMUZFNDhCNzM5N0I=\n - identity: {}\n resources:\n - secrets\n"
enabled = true
}
}
}
upgrade_strategy {
drain = true
max_unavailable_worker = "20%%"
drain_input {
ignore_daemon_sets = true
timeout = 120
delete_local_data = true
}
}
}
`, testAccRKEClusterNodes[0], testAccRKEClusterNodes[1])
}