-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
resource_evpn.go
520 lines (480 loc) · 16.9 KB
/
resource_evpn.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
package junos
import (
"context"
"fmt"
"regexp"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
type evpnOptions struct {
routingInstanceEvpn bool
defaultGateway string
encapsulation string
multicastMode string
routingInstance string
switchOrRIOptions []map[string]interface{}
}
func resourceEvpn() *schema.Resource {
return &schema.Resource{
CreateContext: resourceEvpnCreate,
ReadContext: resourceEvpnRead,
UpdateContext: resourceEvpnUpdate,
DeleteContext: resourceEvpnDelete,
Importer: &schema.ResourceImporter{
State: resourceEvpnImport,
},
Schema: map[string]*schema.Schema{
"routing_instance": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: defaultWord,
ValidateDiagFunc: validateNameObjectJunos([]string{}, 64, formatDefault),
},
"routing_instance_evpn": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
RequiredWith: []string{"routing_instance", "switch_or_ri_options"},
},
"encapsulation": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"mpls", "vxlan"}, false),
},
"default_gateway": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"advertise", "do-not-advertise", "no-gateway-community"}, false),
},
"multicast_mode": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"ingress-replication"}, false),
},
"switch_or_ri_options": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"route_distinguisher": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(
`^(\d|\.)+L?:\d+$`), "must have valid route distinguisher. Use format 'x:y'"),
},
"vrf_export": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vrf_import": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vrf_target": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(
`^target:(\d|\.)+L?:\d+$`), "must have valid target. Use format 'target:x:y'"),
},
"vrf_target_auto": {
Type: schema.TypeBool,
Optional: true,
},
"vrf_target_export": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(
`^target:(\d|\.)+L?:\d+$`), "must have valid target. Use format 'target:x:y'"),
},
"vrf_target_import": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringMatch(regexp.MustCompile(
`^target:(\d|\.)+L?:\d+$`), "must have valid target. Use format 'target:x:y'"),
},
},
},
},
},
}
}
func resourceEvpnCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
sess := m.(*Session)
if sess.junosFakeCreateSetFile != "" {
if err := setEvpn(d, m, nil); err != nil {
return diag.FromErr(err)
}
d.SetId(d.Get("routing_instance").(string))
return nil
}
jnprSess, err := sess.startNewSession()
if err != nil {
return diag.FromErr(err)
}
defer sess.closeSession(jnprSess)
sess.configLock(jnprSess)
var diagWarns diag.Diagnostics
if d.Get("routing_instance").(string) != defaultWord {
instanceExists, err := checkRoutingInstanceExists(d.Get("routing_instance").(string), m, jnprSess)
if err != nil {
appendDiagWarns(&diagWarns, sess.configClear(jnprSess))
return append(diagWarns, diag.FromErr(err)...)
}
if !instanceExists {
appendDiagWarns(&diagWarns, sess.configClear(jnprSess))
return append(diagWarns,
diag.FromErr(fmt.Errorf("routing instance %v doesn't exist", d.Get("routing_instance").(string)))...)
}
}
if err := setEvpn(d, m, jnprSess); err != nil {
appendDiagWarns(&diagWarns, sess.configClear(jnprSess))
return append(diagWarns, diag.FromErr(err)...)
}
warns, err := sess.commitConf("create resource junos_evpn", jnprSess)
appendDiagWarns(&diagWarns, warns)
if err != nil {
appendDiagWarns(&diagWarns, sess.configClear(jnprSess))
return append(diagWarns, diag.FromErr(err)...)
}
d.SetId(d.Get("routing_instance").(string))
return append(diagWarns, resourceEvpnReadWJnprSess(d, m, jnprSess)...)
}
func resourceEvpnRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
sess := m.(*Session)
jnprSess, err := sess.startNewSession()
if err != nil {
return diag.FromErr(err)
}
defer sess.closeSession(jnprSess)
return resourceEvpnReadWJnprSess(d, m, jnprSess)
}
func resourceEvpnReadWJnprSess(d *schema.ResourceData, m interface{}, jnprSess *NetconfObject) diag.Diagnostics {
mutex.Lock()
if d.Get("routing_instance").(string) != defaultWord {
instanceExists, err := checkRoutingInstanceExists(d.Get("routing_instance").(string), m, jnprSess)
if err != nil {
mutex.Unlock()
return diag.FromErr(err)
}
if !instanceExists {
mutex.Unlock()
d.SetId("")
return nil
}
}
evpnOptions, err := readEvpn(d.Get("routing_instance").(string), m, jnprSess)
mutex.Unlock()
if err != nil {
return diag.FromErr(err)
}
fillEvpnData(d, evpnOptions)
return nil
}
func resourceEvpnUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
d.Partial(true)
sess := m.(*Session)
jnprSess, err := sess.startNewSession()
if err != nil {
return diag.FromErr(err)
}
defer sess.closeSession(jnprSess)
sess.configLock(jnprSess)
var diagWarns diag.Diagnostics
if err := delEvpn(false, d, m, jnprSess); err != nil {
appendDiagWarns(&diagWarns, sess.configClear(jnprSess))
return append(diagWarns, diag.FromErr(err)...)
}
if err := setEvpn(d, m, jnprSess); err != nil {
appendDiagWarns(&diagWarns, sess.configClear(jnprSess))
return append(diagWarns, diag.FromErr(err)...)
}
warns, err := sess.commitConf("update resource junos_evpn", jnprSess)
appendDiagWarns(&diagWarns, warns)
if err != nil {
appendDiagWarns(&diagWarns, sess.configClear(jnprSess))
return append(diagWarns, diag.FromErr(err)...)
}
d.Partial(false)
return append(diagWarns, resourceEvpnReadWJnprSess(d, m, jnprSess)...)
}
func resourceEvpnDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
sess := m.(*Session)
jnprSess, err := sess.startNewSession()
if err != nil {
return diag.FromErr(err)
}
defer sess.closeSession(jnprSess)
sess.configLock(jnprSess)
var diagWarns diag.Diagnostics
if err := delEvpn(true, d, m, jnprSess); err != nil {
appendDiagWarns(&diagWarns, sess.configClear(jnprSess))
return append(diagWarns, diag.FromErr(err)...)
}
warns, err := sess.commitConf("delete resource junos_evpn", jnprSess)
appendDiagWarns(&diagWarns, warns)
if err != nil {
appendDiagWarns(&diagWarns, sess.configClear(jnprSess))
return append(diagWarns, diag.FromErr(err)...)
}
return diagWarns
}
func resourceEvpnImport(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
sess := m.(*Session)
jnprSess, err := sess.startNewSession()
if err != nil {
return nil, err
}
defer sess.closeSession(jnprSess)
result := make([]*schema.ResourceData, 1)
idList := strings.Split(d.Id(), idSeparator)
if idList[0] != defaultWord {
instanceExists, err := checkRoutingInstanceExists(idList[0], m, jnprSess)
if err != nil {
return nil, err
}
if !instanceExists {
return nil, fmt.Errorf("routing instance %v doesn't exist", d.Get("routing_instance").(string))
}
}
evpnOptions, err := readEvpn(idList[0], m, jnprSess)
if err != nil {
return nil, err
}
fillEvpnData(d, evpnOptions)
if len(idList) > 1 || idList[0] == defaultWord {
if tfErr := d.Set("switch_or_ri_options", evpnOptions.switchOrRIOptions); tfErr != nil {
panic(tfErr)
}
}
result[0] = d
return result, nil
}
func setEvpn(d *schema.ResourceData, m interface{}, jnprSess *NetconfObject) error {
sess := m.(*Session)
configSet := make([]string, 0)
setPrefix := setLineStart
setPrefixSwitchRIVRF := setLineStart
if d.Get("routing_instance").(string) == defaultWord {
if len(d.Get("switch_or_ri_options").([]interface{})) == 0 {
return fmt.Errorf("`switch_or_ri_options` required if `routing_instance` = %s", defaultWord)
}
if d.Get("routing_instance_evpn").(bool) {
return fmt.Errorf("`routing_instance_evpn` incompatible if `routing_instance` = %s", defaultWord)
}
if v := d.Get("default_gateway").(string); v != "" {
return fmt.Errorf("`default_gateway` incompatible if `routing_instance` = %s", defaultWord)
}
setPrefix += "protocols evpn "
setPrefixSwitchRIVRF += "switch-options "
} else {
setPrefix += "routing-instances " + d.Get("routing_instance").(string) + " protocols evpn "
setPrefixSwitchRIVRF += "routing-instances " + d.Get("routing_instance").(string) + " "
}
if d.Get("routing_instance_evpn").(bool) {
if len(d.Get("switch_or_ri_options").([]interface{})) == 0 {
return fmt.Errorf("`switch_or_ri_options` required if routing_instance_evpn = true")
}
configSet = append(configSet, setPrefixSwitchRIVRF+"instance-type evpn")
}
if v := d.Get("encapsulation").(string); v != "" {
configSet = append(configSet, setPrefix+"encapsulation "+v)
}
if v := d.Get("default_gateway").(string); v != "" {
configSet = append(configSet, setPrefix+"default-gateway "+v)
}
if v := d.Get("multicast_mode").(string); v != "" {
configSet = append(configSet, setPrefix+"multicast-mode "+v)
}
for _, v := range d.Get("switch_or_ri_options").([]interface{}) {
swOpts := v.(map[string]interface{})
configSet = append(configSet, setPrefixSwitchRIVRF+"route-distinguisher "+swOpts["route_distinguisher"].(string))
for _, v2 := range swOpts["vrf_export"].([]interface{}) {
configSet = append(configSet, setPrefixSwitchRIVRF+"vrf-export \""+v2.(string)+"\"")
}
for _, v2 := range swOpts["vrf_import"].([]interface{}) {
configSet = append(configSet, setPrefixSwitchRIVRF+"vrf-import \""+v2.(string)+"\"")
}
if v2 := swOpts["vrf_target"].(string); v2 != "" {
configSet = append(configSet, setPrefixSwitchRIVRF+"vrf-target "+v2)
}
if swOpts["vrf_target_auto"].(bool) {
configSet = append(configSet, setPrefixSwitchRIVRF+"vrf-target auto")
}
if v2 := swOpts["vrf_target_export"].(string); v2 != "" {
configSet = append(configSet, setPrefixSwitchRIVRF+"vrf-target export "+v2)
}
if v2 := swOpts["vrf_target_import"].(string); v2 != "" {
configSet = append(configSet, setPrefixSwitchRIVRF+"vrf-target import "+v2)
}
}
return sess.configSet(configSet, jnprSess)
}
func readEvpn(routingInstance string,
m interface{}, jnprSess *NetconfObject) (evpnOptions, error) {
sess := m.(*Session)
var confRead evpnOptions
var evpnConfig string
var switchRIConfig string
if routingInstance == defaultWord {
var err error
evpnConfig, err = sess.command("show configuration protocols evpn | display set relative", jnprSess)
if err != nil {
return confRead, err
}
switchRIConfig, err = sess.command("show configuration switch-options | display set relative", jnprSess)
if err != nil {
return confRead, err
}
} else {
var err error
evpnConfig, err = sess.command("show configuration routing-instances "+
routingInstance+" protocols evpn | display set relative", jnprSess)
if err != nil {
return confRead, err
}
switchRIConfig, err = sess.command("show configuration routing-instances "+
routingInstance+" | display set relative", jnprSess)
if err != nil {
return confRead, err
}
}
if evpnConfig != emptyWord {
confRead.routingInstance = routingInstance
for _, item := range strings.Split(evpnConfig, "\n") {
if strings.Contains(item, "<configuration-output>") {
continue
}
if strings.Contains(item, "</configuration-output>") {
break
}
itemTrim := strings.TrimPrefix(item, setLineStart)
switch {
case strings.HasPrefix(itemTrim, "default-gateway "):
confRead.defaultGateway = strings.TrimPrefix(itemTrim, "default-gateway ")
case strings.HasPrefix(itemTrim, "encapsulation "):
confRead.encapsulation = strings.TrimPrefix(itemTrim, "encapsulation ")
case strings.HasPrefix(itemTrim, "multicast-mode "):
confRead.multicastMode = strings.TrimPrefix(itemTrim, "multicast-mode ")
}
}
}
if switchRIConfig != emptyWord {
for _, item := range strings.Split(switchRIConfig, "\n") {
if strings.Contains(item, "<configuration-output>") {
continue
}
if strings.Contains(item, "</configuration-output>") {
break
}
itemTrim := strings.TrimPrefix(item, setLineStart)
switch {
case itemTrim == "instance-type evpn":
confRead.routingInstanceEvpn = true
case strings.HasPrefix(itemTrim, "route-distinguisher ") ||
strings.HasPrefix(itemTrim, "vrf-export") ||
strings.HasPrefix(itemTrim, "vrf-import") ||
strings.HasPrefix(itemTrim, "vrf-target"):
if len(confRead.switchOrRIOptions) == 0 {
confRead.switchOrRIOptions = append(confRead.switchOrRIOptions, map[string]interface{}{
"route_distinguisher": "",
"vrf_export": make([]string, 0),
"vrf_import": make([]string, 0),
"vrf_target": "",
"vrf_target_auto": false,
"vrf_target_export": "",
"vrf_target_import": "",
})
}
switch {
case strings.HasPrefix(itemTrim, "route-distinguisher "):
confRead.switchOrRIOptions[0]["route_distinguisher"] = strings.TrimPrefix(itemTrim, "route-distinguisher ")
case strings.HasPrefix(itemTrim, "vrf-export "):
confRead.switchOrRIOptions[0]["vrf_export"] = append(confRead.switchOrRIOptions[0]["vrf_export"].([]string),
strings.Trim(strings.TrimPrefix(itemTrim, "vrf-export "), "\""))
case strings.HasPrefix(itemTrim, "vrf-import "):
confRead.switchOrRIOptions[0]["vrf_import"] = append(confRead.switchOrRIOptions[0]["vrf_import"].([]string),
strings.Trim(strings.TrimPrefix(itemTrim, "vrf-import "), "\""))
case itemTrim == "vrf-target auto":
confRead.switchOrRIOptions[0]["vrf_target_auto"] = true
case strings.HasPrefix(itemTrim, "vrf-target export "):
confRead.switchOrRIOptions[0]["vrf_target_export"] = strings.TrimPrefix(itemTrim, "vrf-target export ")
case strings.HasPrefix(itemTrim, "vrf-target import "):
confRead.switchOrRIOptions[0]["vrf_target_import"] = strings.TrimPrefix(itemTrim, "vrf-target import ")
case strings.HasPrefix(itemTrim, "vrf-target "):
confRead.switchOrRIOptions[0]["vrf_target"] = strings.TrimPrefix(itemTrim, "vrf-target ")
}
}
}
}
return confRead, nil
}
func delEvpn(destroy bool, d *schema.ResourceData, m interface{}, jnprSess *NetconfObject) error {
sess := m.(*Session)
configSet := make([]string, 0, 1)
delPrefix := deleteWord + " "
delPrefixSwitchRIVRF := deleteWord + " "
if d.Get("routing_instance").(string) == defaultWord {
delPrefix += "protocols evpn "
delPrefixSwitchRIVRF += "switch-options "
} else {
delPrefix += "routing-instances " + d.Get("routing_instance").(string) + " protocols evpn "
delPrefixSwitchRIVRF += "routing-instances " + d.Get("routing_instance").(string) + " "
}
listLinesToDelete := []string{
"default-gateway",
"encapsulation",
"multicast-mode",
}
// to remove line "set protocols evpn" without options when destroy resource
if destroy {
listLinesToDelete = append(listLinesToDelete, "")
}
for _, line := range listLinesToDelete {
configSet = append(configSet, delPrefix+line)
}
listLinesToDelete = listLinesToDelete[:0]
if d.Get("routing_instance_evpn").(bool) {
listLinesToDelete = append(listLinesToDelete, "instance-type")
}
if len(d.Get("switch_or_ri_options").([]interface{})) != 0 {
listLinesToDelete = append(listLinesToDelete,
"route-distinguisher",
"vrf-export",
"vrf-import",
"vrf-target",
)
}
for _, line := range listLinesToDelete {
configSet = append(configSet, delPrefixSwitchRIVRF+line)
}
return sess.configSet(configSet, jnprSess)
}
func fillEvpnData(d *schema.ResourceData, evpnOptions evpnOptions) {
if tfErr := d.Set("routing_instance", evpnOptions.routingInstance); tfErr != nil {
panic(tfErr)
}
if tfErr := d.Set("routing_instance_evpn", evpnOptions.routingInstanceEvpn); tfErr != nil {
panic(tfErr)
}
if tfErr := d.Set("encapsulation", evpnOptions.encapsulation); tfErr != nil {
panic(tfErr)
}
if tfErr := d.Set("default_gateway", evpnOptions.defaultGateway); tfErr != nil {
panic(tfErr)
}
if tfErr := d.Set("multicast_mode", evpnOptions.multicastMode); tfErr != nil {
panic(tfErr)
}
if _, s := d.GetOk("switch_or_ri_options"); s {
if tfErr := d.Set("switch_or_ri_options", evpnOptions.switchOrRIOptions); tfErr != nil {
panic(tfErr)
}
}
}