This repository has been archived by the owner on Jul 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
resource_tc_eni.go
677 lines (568 loc) · 16.4 KB
/
resource_tc_eni.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
/*
Provides a resource to create an ENI.
Example Usage
```hcl
resource "tencentcloud_vpc" "foo" {
name = "ci-test-eni-vpc"
cidr_block = "10.0.0.0/16"
}
resource "tencentcloud_subnet" "foo" {
availability_zone = "ap-guangzhou-3"
name = "ci-test-eni-subnet"
vpc_id = tencentcloud_vpc.foo.id
cidr_block = "10.0.0.0/16"
is_multicast = false
}
resource "tencentcloud_eni" "foo" {
name = "ci-test-eni"
vpc_id = tencentcloud_vpc.foo.id
subnet_id = tencentcloud_subnet.foo.id
description = "eni desc"
ipv4_count = 1
}
```
Import
ENI can be imported using the id, e.g.
```
$ terraform import tencentcloud_eni.foo eni-qka182br
```
*/
package tencentcloud
import (
"context"
"errors"
"fmt"
"net"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/terraform-providers/terraform-provider-tencentcloud/tencentcloud/internal/helper"
)
func eniIpOutputResource() *schema.Resource {
return &schema.Resource{
Schema: map[string]*schema.Schema{
"ip": {
Type: schema.TypeString,
Computed: true,
Description: "Intranet IP.",
},
"primary": {
Type: schema.TypeBool,
Computed: true,
Description: "Indicates whether the IP is primary.",
},
"description": {
Type: schema.TypeString,
Computed: true,
Description: "Description of the IP.",
},
},
}
}
func resourceTencentCloudEni() *schema.Resource {
return &schema.Resource{
Create: resourceTencentCloudEniCreate,
Read: resourceTencentCloudEniRead,
Update: resourceTencentCloudEniUpdate,
Delete: resourceTencentCloudEniDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateStringLengthInRange(0, 60),
Description: "Name of the ENI, maximum length 60.",
},
"vpc_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "ID of the vpc.",
},
"subnet_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "ID of the subnet within this vpc.",
},
"description": {
Type: schema.TypeString,
Optional: true,
Default: "",
ValidateFunc: validateStringLengthInRange(0, 60),
Description: "Description of the ENI, maximum length 60.",
},
"security_groups": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Description: "A set of security group IDs.",
},
"ipv4s": {
Type: schema.TypeSet,
Optional: true,
ConflictsWith: []string{"ipv4_count"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip": {
Type: schema.TypeString,
Required: true,
Description: "Intranet IP.",
},
"primary": {
Type: schema.TypeBool,
Required: true,
Description: "Indicates whether the IP is primary.",
},
"description": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Description of the IP, maximum length 25.",
ValidateFunc: validateStringLengthInRange(0, 25),
},
},
},
MaxItems: 30,
Description: "Applying for intranet IPv4s collection, conflict with `ipv4_count`. When there are multiple ipv4s, can only be one primary IP, and the maximum length of the array is 30. Each element contains the following attributes:",
},
"ipv4_count": {
Type: schema.TypeInt,
Optional: true,
ConflictsWith: []string{"ipv4s"},
ValidateFunc: validateIntegerInRange(1, 30),
Description: "The number of intranet IPv4s. When it is greater than 1, there is only one primary intranet IP. The others are auxiliary intranet IPs, which conflict with `ipv4s`.",
},
"tags": {
Type: schema.TypeMap,
Optional: true,
Description: "Tags of the ENI.",
},
// computed
"mac": {
Type: schema.TypeString,
Computed: true,
Description: "MAC address.",
},
"state": {
Type: schema.TypeString,
Computed: true,
Description: "State of the ENI.",
},
"primary": {
Type: schema.TypeBool,
Computed: true,
Description: "Indicates whether the IP is primary.",
},
"create_time": {
Type: schema.TypeString,
Computed: true,
Description: "Creation time of the ENI.",
},
"ipv4_info": {
Type: schema.TypeList,
Elem: eniIpOutputResource(),
Computed: true,
Description: "An information list of IPv4s. Each element contains the following attributes:",
},
},
}
}
func resourceTencentCloudEniCreate(d *schema.ResourceData, m interface{}) error {
defer logElapsed("resource.tencentcloud_eni.create")()
logId := getLogId(contextNil)
ctx := context.WithValue(context.TODO(), logIdKey, logId)
name := d.Get("name").(string)
vpcId := d.Get("vpc_id").(string)
subnetId := d.Get("subnet_id").(string)
desc := d.Get("description").(string)
var (
securityGroups []string
ipv4s []VpcEniIP
ipv4Count *int
)
if raw, ok := d.GetOk("security_groups"); ok {
securityGroups = helper.InterfacesStrings(raw.(*schema.Set).List())
}
if raw, ok := d.GetOk("ipv4s"); ok {
set := raw.(*schema.Set)
ipv4s = make([]VpcEniIP, 0, set.Len())
var hasPrimary bool
for _, v := range set.List() {
m := v.(map[string]interface{})
ipStr := m["ip"].(string)
ip := net.ParseIP(ipStr)
if ip == nil {
return fmt.Errorf("ip %s is invalid", ipStr)
}
primary := m["primary"].(bool)
switch {
case !hasPrimary && primary:
hasPrimary = true
case hasPrimary && primary:
return errors.New("only can have a primary ipv4")
}
ipv4 := VpcEniIP{
ip: ip,
primary: primary,
}
ipv4.desc = helper.String(m["description"].(string))
ipv4s = append(ipv4s, ipv4)
}
if !hasPrimary {
return errors.New("need a primary ipv4")
}
}
if raw, ok := d.GetOk("ipv4_count"); ok {
ipv4Count = common.IntPtr(raw.(int))
}
if len(ipv4s) == 0 && ipv4Count == nil {
return errors.New("ipv4s or ipv4_count must be set")
}
tags := helper.GetTags(d, "tags")
client := m.(*TencentCloudClient).apiV3Conn
vpcService := VpcService{client: client}
tagService := TagService{client: client}
region := client.Region
var (
id string
err error
)
switch {
case len(ipv4s) > 0 && len(ipv4s) <= 10:
id, err = vpcService.CreateEni(ctx, name, vpcId, subnetId, desc, securityGroups, nil, ipv4s)
if err != nil {
return err
}
d.SetId(id)
case len(ipv4s) > 0:
// eni should create with primary ipv4
for i := 0; i < len(ipv4s); i++ {
if ipv4s[i].primary {
if i < 10 {
break
}
// move primary ip to the first
ipv4s[0], ipv4s[i] = ipv4s[i], ipv4s[0]
break
}
}
ipv4ss := chunkEniIP(ipv4s)
withPrimaryIpv4s := ipv4ss[0]
id, err = vpcService.CreateEni(ctx, name, vpcId, subnetId, desc, securityGroups, nil, withPrimaryIpv4s)
if err != nil {
return err
}
d.SetId(id)
for _, ipv4s := range ipv4ss[1:] {
if err = vpcService.AssignIpv4ToEni(ctx, id, ipv4s, nil); err != nil {
return err
}
}
case ipv4Count != nil && *ipv4Count <= 10:
id, err = vpcService.CreateEni(ctx, name, vpcId, subnetId, desc, securityGroups, ipv4Count, nil)
if err != nil {
return err
}
d.SetId(id)
case ipv4Count != nil:
count := *ipv4Count
id, err = vpcService.CreateEni(ctx, name, vpcId, subnetId, desc, securityGroups, common.IntPtr(10), nil)
if err != nil {
return err
}
d.SetId(id)
count -= 10
for count > 10 {
if err = vpcService.AssignIpv4ToEni(ctx, id, nil, common.IntPtr(10)); err != nil {
return err
}
count -= 10
}
// assign last ip
if count > 0 {
if err = vpcService.AssignIpv4ToEni(ctx, id, nil, &count); err != nil {
return err
}
}
}
if len(tags) > 0 {
resourceName := BuildTagResourceName("vpc", "eni", region, id)
if err := tagService.ModifyTags(ctx, resourceName, tags, nil); err != nil {
return err
}
}
return resourceTencentCloudEniRead(d, m)
}
func resourceTencentCloudEniRead(d *schema.ResourceData, m interface{}) error {
defer logElapsed("resource.tencentcloud_eni.read")()
defer inconsistentCheck(d, m)()
logId := getLogId(contextNil)
ctx := context.WithValue(context.TODO(), logIdKey, logId)
id := d.Id()
service := VpcService{client: m.(*TencentCloudClient).apiV3Conn}
enis, err := service.DescribeEniById(ctx, []string{id})
if err != nil {
return err
}
if len(enis) < 1 {
d.SetId("")
return nil
}
eni := enis[0]
_ = d.Set("name", eni.NetworkInterfaceName)
_ = d.Set("vpc_id", eni.VpcId)
_ = d.Set("subnet_id", eni.SubnetId)
_ = d.Set("description", eni.NetworkInterfaceDescription)
_ = d.Set("mac", eni.MacAddress)
_ = d.Set("state", eni.State)
_ = d.Set("primary", eni.Primary)
_ = d.Set("create_time", eni.CreatedTime)
sgs := make([]string, 0, len(eni.GroupSet))
for _, sg := range eni.GroupSet {
sgs = append(sgs, *sg)
}
_ = d.Set("security_groups", sgs)
ipv4s := make([]map[string]interface{}, 0, len(eni.PrivateIpAddressSet))
for _, ipv4 := range eni.PrivateIpAddressSet {
ipv4s = append(ipv4s, map[string]interface{}{
"ip": ipv4.PrivateIpAddress,
"primary": ipv4.Primary,
"description": ipv4.Description,
})
}
_ = d.Set("ipv4_info", ipv4s)
_, manually := d.GetOk("ipv4s")
_, count := d.GetOk("ipv4_count")
if !manually && !count {
// import mode
_ = d.Set("ipv4_count", len(ipv4s))
}
tags := make(map[string]string, len(eni.TagSet))
for _, tag := range eni.TagSet {
tags[*tag.Key] = *tag.Value
}
_ = d.Set("tags", tags)
return nil
}
func resourceTencentCloudEniUpdate(d *schema.ResourceData, m interface{}) error {
defer logElapsed("resource.tencentcloud_eni.update")()
logId := getLogId(contextNil)
ctx := context.WithValue(context.TODO(), logIdKey, logId)
id := d.Id()
d.Partial(true)
client := m.(*TencentCloudClient).apiV3Conn
vpcService := VpcService{client: client}
tagService := TagService{client: client}
region := client.Region
var (
name *string
desc *string
sgs []string
updateAttrs []string
)
if d.HasChange("name") {
updateAttrs = append(updateAttrs, "name")
name = helper.String(d.Get("name").(string))
}
if d.HasChange("description") {
updateAttrs = append(updateAttrs, "description")
desc = helper.String(d.Get("description").(string))
}
if d.HasChange("security_groups") {
updateAttrs = append(updateAttrs, "security_groups")
}
sgs = helper.InterfacesStrings(d.Get("security_groups").(*schema.Set).List())
if len(updateAttrs) > 0 {
if err := vpcService.ModifyEniAttribute(ctx, id, name, desc, sgs); err != nil {
return err
}
for _, attr := range updateAttrs {
d.SetPartial(attr)
}
}
// if ipv4 set manually
if _, ok := d.GetOk("ipv4s"); ok && d.HasChange("ipv4s") {
oldRaw, newRaw := d.GetChange("ipv4s")
oldSet := oldRaw.(*schema.Set)
newSet := newRaw.(*schema.Set)
if newSet.Len() == 0 {
return errors.New("can't remove all ipv4s")
}
removeSet := oldSet.Difference(newSet).List()
addSet := newSet.Difference(oldSet).List()
var modifyPrimaryIpv4 *VpcEniIP
removeIpv4 := make([]string, 0, len(removeSet))
for _, v := range removeSet {
m := v.(map[string]interface{})
if m["primary"].(bool) {
// check if only modify primary description
modifyPrimaryIpv4 = &VpcEniIP{
ip: net.ParseIP(m["ip"].(string)),
}
continue
}
removeIpv4 = append(removeIpv4, m["ip"].(string))
}
addIpv4 := make([]VpcEniIP, 0, len(addSet))
newPrimaryCount := 0
for _, v := range addSet {
m := v.(map[string]interface{})
ipStr := m["ip"].(string)
ip := net.ParseIP(ipStr)
if ip == nil {
return fmt.Errorf("ip %s is invalid", ipStr)
}
if m["primary"].(bool) {
if modifyPrimaryIpv4 == nil {
return errors.New("can't set more than one primary ipv4")
}
// if newPrimaryCount > 1, means new ipv4s have more than one primary ipv4,
// if only one, maybe just update primary ipv4 description
newPrimaryCount++
if newPrimaryCount > 1 {
return errors.New("can't set more than one primary ipv4")
}
// only can update primary ipv4 description
if modifyPrimaryIpv4.ip.String() != ipStr {
return errors.New("can't change primary ipv4")
}
modifyPrimaryIpv4.desc = helper.String(m["description"].(string))
continue
}
ipv4 := VpcEniIP{
ip: ip,
primary: m["primary"].(bool),
desc: helper.String(m["description"].(string)),
}
addIpv4 = append(addIpv4, ipv4)
}
if modifyPrimaryIpv4 != nil {
// if desc is nil, means remove primary ipv4 but not add same primary ipv4,
// that means not just update primary ipv4 description, user remove primary ipv4
if modifyPrimaryIpv4.desc == nil {
return errors.New("can't remove primary ipv4")
}
if err := vpcService.ModifyEniPrimaryIpv4Desc(ctx, id, modifyPrimaryIpv4.ip.String(), modifyPrimaryIpv4.desc); err != nil {
return err
}
}
if len(removeIpv4) > 0 {
if len(removeIpv4) <= 10 {
if err := vpcService.UnAssignIpv4FromEni(ctx, id, removeIpv4); err != nil {
return err
}
} else {
for _, remove := range chunkRemoveIpv4(removeIpv4) {
if err := vpcService.UnAssignIpv4FromEni(ctx, id, remove); err != nil {
return err
}
}
}
}
if len(addIpv4) > 0 {
if len(addIpv4) <= 10 {
if err := vpcService.AssignIpv4ToEni(ctx, id, addIpv4, nil); err != nil {
return err
}
} else {
for _, add := range chunkEniIP(addIpv4) {
if err := vpcService.AssignIpv4ToEni(ctx, id, add, nil); err != nil {
return err
}
}
}
}
d.SetPartial("ipv4s")
}
if _, ok := d.GetOk("ipv4_count"); ok {
if d.HasChange("ipv4_count") {
oldRaw, newRaw := d.GetChange("ipv4_count")
oldCount := oldRaw.(int)
newCount := newRaw.(int)
if newCount > oldCount {
count := newCount - oldCount
if count <= 10 {
if err := vpcService.AssignIpv4ToEni(ctx, id, nil, &count); err != nil {
return err
}
} else {
for count > 10 {
if err := vpcService.AssignIpv4ToEni(ctx, id, nil, common.IntPtr(10)); err != nil {
return err
}
count -= 10
}
// assign last ip
if count > 0 {
if err := vpcService.AssignIpv4ToEni(ctx, id, nil, &count); err != nil {
return err
}
}
}
} else {
removeCount := oldCount - newCount
list := d.Get("ipv4_info").([]interface{})
removeIpv4 := make([]string, 0, removeCount)
for _, v := range list {
if removeCount == 0 {
break
}
m := v.(map[string]interface{})
if m["primary"].(bool) {
continue
}
removeIpv4 = append(removeIpv4, m["ip"].(string))
removeCount--
}
if len(removeIpv4) <= 10 {
if err := vpcService.UnAssignIpv4FromEni(ctx, id, removeIpv4); err != nil {
return err
}
} else {
for _, remove := range chunkRemoveIpv4(removeIpv4) {
if err := vpcService.UnAssignIpv4FromEni(ctx, id, remove); err != nil {
return err
}
}
}
d.SetPartial("ipv4_count")
}
}
}
if d.HasChange("tags") {
oldTags, newTags := d.GetChange("tags")
replaceTags, deleteTags := diffTags(oldTags.(map[string]interface{}), newTags.(map[string]interface{}))
resourceName := BuildTagResourceName("vpc", "eni", region, id)
if err := tagService.ModifyTags(ctx, resourceName, replaceTags, deleteTags); err != nil {
return err
}
d.SetPartial("tags")
}
d.Partial(false)
return resourceTencentCloudEniRead(d, m)
}
func resourceTencentCloudEniDelete(d *schema.ResourceData, m interface{}) error {
defer logElapsed("resource.tencentcloud_eni.delete")()
logId := getLogId(contextNil)
ctx := context.WithValue(context.TODO(), logIdKey, logId)
id := d.Id()
service := VpcService{client: m.(*TencentCloudClient).apiV3Conn}
return service.DeleteEni(ctx, id)
}
func chunkEniIP(ipv4s []VpcEniIP) [][]VpcEniIP {
if len(ipv4s) <= 10 {
return [][]VpcEniIP{ipv4s}
}
first := ipv4s[:10]
return append([][]VpcEniIP{first}, chunkEniIP(ipv4s[10:])...)
}
func chunkRemoveIpv4(ss []string) [][]string {
if len(ss) <= 10 {
return [][]string{ss}
}
s := ss[:10]
return append([][]string{s}, chunkRemoveIpv4(ss[10:])...)
}