forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_openstack_networking_port_v2.go
409 lines (352 loc) · 10.8 KB
/
resource_openstack_networking_port_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
package openstack
import (
"bytes"
"fmt"
"log"
"time"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack/networking/v2/ports"
)
func resourceNetworkingPortV2() *schema.Resource {
return &schema.Resource{
Create: resourceNetworkingPortV2Create,
Read: resourceNetworkingPortV2Read,
Update: resourceNetworkingPortV2Update,
Delete: resourceNetworkingPortV2Delete,
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,
Required: true,
ForceNew: true,
DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""),
},
"name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
},
"network_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"admin_state_up": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
ForceNew: false,
Computed: true,
},
"mac_address": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"tenant_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"device_owner": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"security_group_ids": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: false,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"device_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"fixed_ip": &schema.Schema{
Type: schema.TypeList,
Optional: true,
ForceNew: false,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"subnet_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"ip_address": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
},
},
"allowed_address_pairs": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
ForceNew: false,
Computed: true,
Set: allowedAddressPairsHash,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip_address": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"mac_address": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
},
"value_specs": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},
"all_fixed_ips": &schema.Schema{
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func resourceNetworkingPortV2Create(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
networkingClient, err := config.networkingV2Client(GetRegion(d))
if err != nil {
return fmt.Errorf("Error creating OpenStack networking client: %s", err)
}
createOpts := PortCreateOpts{
ports.CreateOpts{
Name: d.Get("name").(string),
AdminStateUp: resourcePortAdminStateUpV2(d),
NetworkID: d.Get("network_id").(string),
MACAddress: d.Get("mac_address").(string),
TenantID: d.Get("tenant_id").(string),
DeviceOwner: d.Get("device_owner").(string),
SecurityGroups: resourcePortSecurityGroupsV2(d),
DeviceID: d.Get("device_id").(string),
FixedIPs: resourcePortFixedIpsV2(d),
AllowedAddressPairs: resourceAllowedAddressPairsV2(d),
},
MapValueSpecs(d),
}
log.Printf("[DEBUG] Create Options: %#v", createOpts)
p, err := ports.Create(networkingClient, createOpts).Extract()
if err != nil {
return fmt.Errorf("Error creating OpenStack Neutron network: %s", err)
}
log.Printf("[INFO] Network ID: %s", p.ID)
log.Printf("[DEBUG] Waiting for OpenStack Neutron Port (%s) to become available.", p.ID)
stateConf := &resource.StateChangeConf{
Target: []string{"ACTIVE"},
Refresh: waitForNetworkPortActive(networkingClient, p.ID),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 5 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
d.SetId(p.ID)
return resourceNetworkingPortV2Read(d, meta)
}
func resourceNetworkingPortV2Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
networkingClient, err := config.networkingV2Client(GetRegion(d))
if err != nil {
return fmt.Errorf("Error creating OpenStack networking client: %s", err)
}
p, err := ports.Get(networkingClient, d.Id()).Extract()
if err != nil {
return CheckDeleted(d, err, "port")
}
log.Printf("[DEBUG] Retrieved Port %s: %+v", d.Id(), p)
d.Set("name", p.Name)
d.Set("admin_state_up", p.AdminStateUp)
d.Set("network_id", p.NetworkID)
d.Set("mac_address", p.MACAddress)
d.Set("tenant_id", p.TenantID)
d.Set("device_owner", p.DeviceOwner)
d.Set("security_group_ids", p.SecurityGroups)
d.Set("device_id", p.DeviceID)
// Create a slice of all returned Fixed IPs.
// This will be in the order returned by the API,
// which is usually alpha-numeric.
var ips []string
for _, ipObject := range p.FixedIPs {
ips = append(ips, ipObject.IPAddress)
}
d.Set("all_fixed_ips", ips)
// Convert AllowedAddressPairs to list of map
var pairs []map[string]interface{}
for _, pairObject := range p.AllowedAddressPairs {
pair := make(map[string]interface{})
pair["ip_address"] = pairObject.IPAddress
pair["mac_address"] = pairObject.MACAddress
pairs = append(pairs, pair)
}
d.Set("allowed_address_pairs", pairs)
d.Set("region", GetRegion(d))
return nil
}
func resourceNetworkingPortV2Update(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
networkingClient, err := config.networkingV2Client(GetRegion(d))
if err != nil {
return fmt.Errorf("Error creating OpenStack networking client: %s", err)
}
var updateOpts ports.UpdateOpts
if d.HasChange("name") {
updateOpts.Name = d.Get("name").(string)
}
if d.HasChange("admin_state_up") {
updateOpts.AdminStateUp = resourcePortAdminStateUpV2(d)
}
if d.HasChange("device_owner") {
updateOpts.DeviceOwner = d.Get("device_owner").(string)
}
if d.HasChange("security_group_ids") {
updateOpts.SecurityGroups = resourcePortSecurityGroupsV2(d)
}
if d.HasChange("device_id") {
updateOpts.DeviceID = d.Get("device_id").(string)
}
if d.HasChange("fixed_ip") {
updateOpts.FixedIPs = resourcePortFixedIpsV2(d)
}
if d.HasChange("allowed_address_pairs") {
updateOpts.AllowedAddressPairs = resourceAllowedAddressPairsV2(d)
}
log.Printf("[DEBUG] Updating Port %s with options: %+v", d.Id(), updateOpts)
_, err = ports.Update(networkingClient, d.Id(), updateOpts).Extract()
if err != nil {
return fmt.Errorf("Error updating OpenStack Neutron Network: %s", err)
}
return resourceNetworkingPortV2Read(d, meta)
}
func resourceNetworkingPortV2Delete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
networkingClient, err := config.networkingV2Client(GetRegion(d))
if err != nil {
return fmt.Errorf("Error creating OpenStack networking client: %s", err)
}
stateConf := &resource.StateChangeConf{
Pending: []string{"ACTIVE"},
Target: []string{"DELETED"},
Refresh: waitForNetworkPortDelete(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 Network: %s", err)
}
d.SetId("")
return nil
}
func resourcePortSecurityGroupsV2(d *schema.ResourceData) []string {
rawSecurityGroups := d.Get("security_group_ids").(*schema.Set)
groups := make([]string, rawSecurityGroups.Len())
for i, raw := range rawSecurityGroups.List() {
groups[i] = raw.(string)
}
return groups
}
func resourcePortFixedIpsV2(d *schema.ResourceData) interface{} {
rawIP := d.Get("fixed_ip").([]interface{})
if len(rawIP) == 0 {
return nil
}
ip := make([]ports.IP, len(rawIP))
for i, raw := range rawIP {
rawMap := raw.(map[string]interface{})
ip[i] = ports.IP{
SubnetID: rawMap["subnet_id"].(string),
IPAddress: rawMap["ip_address"].(string),
}
}
return ip
}
func resourceAllowedAddressPairsV2(d *schema.ResourceData) []ports.AddressPair {
// ports.AddressPair
rawPairs := d.Get("allowed_address_pairs").(*schema.Set).List()
if len(rawPairs) == 0 {
return nil
}
pairs := make([]ports.AddressPair, len(rawPairs))
for i, raw := range rawPairs {
rawMap := raw.(map[string]interface{})
pairs[i] = ports.AddressPair{
IPAddress: rawMap["ip_address"].(string),
MACAddress: rawMap["mac_address"].(string),
}
}
return pairs
}
func resourcePortAdminStateUpV2(d *schema.ResourceData) *bool {
value := false
if raw, ok := d.GetOk("admin_state_up"); ok && raw == true {
value = true
}
return &value
}
func allowedAddressPairsHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s", m["ip_address"].(string)))
return hashcode.String(buf.String())
}
func waitForNetworkPortActive(networkingClient *gophercloud.ServiceClient, portId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
p, err := ports.Get(networkingClient, portId).Extract()
if err != nil {
return nil, "", err
}
log.Printf("[DEBUG] OpenStack Neutron Port: %+v", p)
if p.Status == "DOWN" || p.Status == "ACTIVE" {
return p, "ACTIVE", nil
}
return p, p.Status, nil
}
}
func waitForNetworkPortDelete(networkingClient *gophercloud.ServiceClient, portId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
log.Printf("[DEBUG] Attempting to delete OpenStack Neutron Port %s", portId)
p, err := ports.Get(networkingClient, portId).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
log.Printf("[DEBUG] Successfully deleted OpenStack Port %s", portId)
return p, "DELETED", nil
}
return p, "ACTIVE", err
}
err = ports.Delete(networkingClient, portId).ExtractErr()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
log.Printf("[DEBUG] Successfully deleted OpenStack Port %s", portId)
return p, "DELETED", nil
}
return p, "ACTIVE", err
}
log.Printf("[DEBUG] OpenStack Port %s still active.\n", portId)
return p, "ACTIVE", nil
}
}