-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_openstack_networking_router_v2.go
475 lines (409 loc) · 13.5 KB
/
resource_openstack_networking_router_v2.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
package openstack
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/attributestags"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/routers"
)
func resourceNetworkingRouterV2() *schema.Resource {
return &schema.Resource{
Create: resourceNetworkingRouterV2Create,
Read: resourceNetworkingRouterV2Read,
Update: resourceNetworkingRouterV2Update,
Delete: resourceNetworkingRouterV2Delete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"region": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
},
"admin_state_up": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: false,
Computed: true,
},
"distributed": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Computed: true,
},
"external_gateway": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
Computed: true,
Deprecated: "use external_network_id instead",
ConflictsWith: []string{"external_network_id"},
},
"external_network_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
Computed: true,
ConflictsWith: []string{"external_gateway"},
},
"enable_snat": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: false,
Computed: true,
},
"external_fixed_ip": &schema.Schema{
Type: schema.TypeList,
Optional: true,
ForceNew: false,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"subnet_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"ip_address": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
},
},
"tenant_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"value_specs": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},
"availability_zone_hints": &schema.Schema{
Type: schema.TypeList,
Computed: true,
ForceNew: true,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vendor_options": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
MinItems: 1,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"set_router_gateway_after_create": &schema.Schema{
Type: schema.TypeBool,
Default: false,
Optional: true,
},
},
},
},
"tags": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func resourceNetworkingRouterV2Create(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
networkingClient, err := config.networkingV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack networking client: %s", err)
}
createOpts := RouterCreateOpts{
routers.CreateOpts{
Name: d.Get("name").(string),
TenantID: d.Get("tenant_id").(string),
AvailabilityZoneHints: resourceNetworkingAvailabilityZoneHintsV2(d),
},
MapValueSpecs(d),
}
if asuRaw, ok := d.GetOk("admin_state_up"); ok {
asu := asuRaw.(bool)
createOpts.AdminStateUp = &asu
}
if dRaw, ok := d.GetOkExists("distributed"); ok {
d := dRaw.(bool)
createOpts.Distributed = &d
}
// Get Vendor_options
vendorOptionsRaw := d.Get("vendor_options").(*schema.Set)
var vendorUpdateGateway bool
if vendorOptionsRaw.Len() > 0 {
vendorOptions := expandVendorOptions(vendorOptionsRaw.List())
vendorUpdateGateway = vendorOptions["set_router_gateway_after_create"].(bool)
}
// Gateway settings
var externalNetworkID string
var gatewayInfo routers.GatewayInfo
if v := d.Get("external_gateway").(string); v != "" {
externalNetworkID = v
gatewayInfo.NetworkID = externalNetworkID
}
if v := d.Get("external_network_id").(string); v != "" {
externalNetworkID = v
gatewayInfo.NetworkID = externalNetworkID
}
if esRaw, ok := d.GetOkExists("enable_snat"); ok {
if externalNetworkID == "" {
return fmt.Errorf("setting enable_snat requires external_network_id to be set")
}
es := esRaw.(bool)
gatewayInfo.EnableSNAT = &es
}
externalFixedIPs := resourceRouterExternalFixedIPsV2(d)
if len(externalFixedIPs) > 0 {
if externalNetworkID == "" {
return fmt.Errorf("setting an external_fixed_ip requires external_network_id to be set")
}
gatewayInfo.ExternalFixedIPs = externalFixedIPs
}
// vendorUpdateGateway is a flag for certain vendor-specific virtual routers
// which do not allow gateway settings to be set during router creation.
// If this flag was not enabled, then we can safely set the gateway
// information during create.
if !vendorUpdateGateway && externalNetworkID != "" {
createOpts.GatewayInfo = &gatewayInfo
}
log.Printf("[DEBUG] Create Options: %#v", createOpts)
n, err := routers.Create(networkingClient, createOpts).Extract()
if err != nil {
return fmt.Errorf("Error creating OpenStack Neutron router: %s", err)
}
log.Printf("[INFO] Router ID: %s", n.ID)
log.Printf("[DEBUG] Waiting for OpenStack Neutron Router (%s) to become available", n.ID)
stateConf := &resource.StateChangeConf{
Pending: []string{"BUILD", "PENDING_CREATE", "PENDING_UPDATE"},
Target: []string{"ACTIVE"},
Refresh: waitForRouterActive(networkingClient, n.ID),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 5 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
d.SetId(n.ID)
// If the vendorUpdateGateway flag was specified and if an external network
// was specified, then set the gateway information after router creation.
if vendorUpdateGateway && externalNetworkID != "" {
log.Printf("[DEBUG] Adding External Network %s to router ID %s", externalNetworkID, d.Id())
var updateOpts routers.UpdateOpts
updateOpts.GatewayInfo = &gatewayInfo
log.Printf("[DEBUG] Assigning external gateway to Router %s with options: %+v", d.Id(), updateOpts)
_, err = routers.Update(networkingClient, d.Id(), updateOpts).Extract()
if err != nil {
return fmt.Errorf("Error updating OpenStack Neutron Router: %s", err)
}
}
tags := networkV2AttributesTags(d)
if len(tags) > 0 {
tagOpts := attributestags.ReplaceAllOpts{Tags: tags}
tags, err := attributestags.ReplaceAll(networkingClient, "routers", n.ID, tagOpts).Extract()
if err != nil {
return fmt.Errorf("Error creating Tags on Router: %s", err)
}
log.Printf("[DEBUG] Set Tags = %+v on Router %+v", tags, n.ID)
}
return resourceNetworkingRouterV2Read(d, meta)
}
func resourceNetworkingRouterV2Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
networkingClient, err := config.networkingV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack networking client: %s", err)
}
n, err := routers.Get(networkingClient, d.Id()).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving OpenStack Neutron Router: %s", err)
}
log.Printf("[DEBUG] Retrieved Router %s: %+v", d.Id(), n)
d.Set("name", n.Name)
d.Set("admin_state_up", n.AdminStateUp)
d.Set("distributed", n.Distributed)
d.Set("tenant_id", n.TenantID)
d.Set("region", GetRegion(d, config))
d.Set("tags", n.Tags)
if err := d.Set("availability_zone_hints", n.AvailabilityZoneHints); err != nil {
log.Printf("[DEBUG] unable to set availability_zone_hints: %s", err)
}
// Gateway settings
d.Set("external_gateway", n.GatewayInfo.NetworkID)
d.Set("external_network_id", n.GatewayInfo.NetworkID)
d.Set("enable_snat", n.GatewayInfo.EnableSNAT)
var externalFixedIPs []map[string]string
for _, v := range n.GatewayInfo.ExternalFixedIPs {
externalFixedIPs = append(externalFixedIPs, map[string]string{
"subnet_id": v.SubnetID,
"ip_address": v.IPAddress,
})
}
if err = d.Set("external_fixed_ip", externalFixedIPs); err != nil {
log.Printf("[DEBUG] unable to set external_fixed_ip: %s", err)
}
return nil
}
func resourceNetworkingRouterV2Update(d *schema.ResourceData, meta interface{}) error {
routerId := d.Id()
osMutexKV.Lock(routerId)
defer osMutexKV.Unlock(routerId)
config := meta.(*Config)
networkingClient, err := config.networkingV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack networking client: %s", err)
}
var updateOpts routers.UpdateOpts
if d.HasChange("name") {
updateOpts.Name = d.Get("name").(string)
}
if d.HasChange("admin_state_up") {
asu := d.Get("admin_state_up").(bool)
updateOpts.AdminStateUp = &asu
}
// Gateway settings
var updateGatewaySettings bool
var externalNetworkID string
gatewayInfo := routers.GatewayInfo{}
if v := d.Get("external_gateway").(string); v != "" {
externalNetworkID = v
}
if v := d.Get("external_network_id").(string); v != "" {
externalNetworkID = v
}
if externalNetworkID != "" {
gatewayInfo.NetworkID = externalNetworkID
}
if d.HasChange("external_gateway") {
updateGatewaySettings = true
}
if d.HasChange("external_network_id") {
updateGatewaySettings = true
}
if d.HasChange("enable_snat") {
updateGatewaySettings = true
if externalNetworkID == "" {
return fmt.Errorf("setting enable_snat requires external_network_id to be set")
}
enableSNAT := d.Get("enable_snat").(bool)
gatewayInfo.EnableSNAT = &enableSNAT
}
if d.HasChange("external_fixed_ip") {
updateGatewaySettings = true
externalFixedIPs := resourceRouterExternalFixedIPsV2(d)
gatewayInfo.ExternalFixedIPs = externalFixedIPs
if len(externalFixedIPs) > 0 {
if externalNetworkID == "" {
return fmt.Errorf("setting an external_fixed_ip requires external_network_id to be set")
}
}
}
if updateGatewaySettings {
updateOpts.GatewayInfo = &gatewayInfo
}
log.Printf("[DEBUG] Updating Router %s with options: %+v", d.Id(), updateOpts)
_, err = routers.Update(networkingClient, d.Id(), updateOpts).Extract()
if err != nil {
return fmt.Errorf("Error updating OpenStack Neutron Router: %s", err)
}
if d.HasChange("tags") {
tags := networkV2AttributesTags(d)
tagOpts := attributestags.ReplaceAllOpts{Tags: tags}
tags, err := attributestags.ReplaceAll(networkingClient, "routers", d.Id(), tagOpts).Extract()
if err != nil {
return fmt.Errorf("Error updating Tags on Router: %s", err)
}
log.Printf("[DEBUG] Updated Tags = %+v on Router %+v", tags, d.Id())
}
return resourceNetworkingRouterV2Read(d, meta)
}
func resourceNetworkingRouterV2Delete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
networkingClient, err := config.networkingV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack networking client: %s", err)
}
stateConf := &resource.StateChangeConf{
Pending: []string{"ACTIVE"},
Target: []string{"DELETED"},
Refresh: waitForRouterDelete(networkingClient, d.Id()),
Timeout: d.Timeout(schema.TimeoutDelete),
Delay: 5 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf("Error deleting OpenStack Neutron Router: %s", err)
}
d.SetId("")
return nil
}
func waitForRouterActive(networkingClient *gophercloud.ServiceClient, routerId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
r, err := routers.Get(networkingClient, routerId).Extract()
if err != nil {
return nil, r.Status, err
}
log.Printf("[DEBUG] OpenStack Neutron Router: %+v", r)
return r, r.Status, nil
}
}
func waitForRouterDelete(networkingClient *gophercloud.ServiceClient, routerId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
log.Printf("[DEBUG] Attempting to delete OpenStack Router %s.\n", routerId)
r, err := routers.Get(networkingClient, routerId).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
log.Printf("[DEBUG] Successfully deleted OpenStack Router %s", routerId)
return r, "DELETED", nil
}
return r, "ACTIVE", err
}
err = routers.Delete(networkingClient, routerId).ExtractErr()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
log.Printf("[DEBUG] Successfully deleted OpenStack Router %s", routerId)
return r, "DELETED", nil
}
return r, "ACTIVE", err
}
log.Printf("[DEBUG] OpenStack Router %s still active.\n", routerId)
return r, "ACTIVE", nil
}
}
func resourceRouterExternalFixedIPsV2(d *schema.ResourceData) []routers.ExternalFixedIP {
var externalFixedIPs []routers.ExternalFixedIP
eFIPs := d.Get("external_fixed_ip").([]interface{})
for _, eFIP := range eFIPs {
v := eFIP.(map[string]interface{})
fip := routers.ExternalFixedIP{
SubnetID: v["subnet_id"].(string),
IPAddress: v["ip_address"].(string),
}
externalFixedIPs = append(externalFixedIPs, fip)
}
return externalFixedIPs
}