-
Notifications
You must be signed in to change notification settings - Fork 675
/
Copy pathresource_ibm_network_public_ip.go
361 lines (305 loc) · 11.3 KB
/
resource_ibm_network_public_ip.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
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package classicinfrastructure
import (
"fmt"
"log"
"net"
"strconv"
"strings"
"time"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/softlayer/softlayer-go/datatypes"
"github.com/softlayer/softlayer-go/filter"
"github.com/softlayer/softlayer-go/helpers/product"
"github.com/softlayer/softlayer-go/services"
"github.com/softlayer/softlayer-go/session"
"github.com/softlayer/softlayer-go/sl"
)
const (
AdditionalServicesGlobalIpAddressesPackageType = "ADDITIONAL_SERVICES_GLOBAL_IP_ADDRESSES"
GlobalIpMask = "id,ipAddress[ipAddress,id,note],destinationIpAddress[ipAddress]"
)
func ResourceIBMNetworkPublicIp() *schema.Resource {
return &schema.Resource{
Create: resourceIBMNetworkPublicIpCreate,
Read: resourceIBMNetworkPublicIpRead,
Update: resourceIBMNetworkPublicIpUpdate,
Delete: resourceIBMNetworkPublicIpDelete,
Exists: resourceIBMNetworkPublicIpExists,
Importer: &schema.ResourceImporter{},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"ip_address": {
Type: schema.TypeString,
Computed: true,
Description: "IP Address",
},
"routes_to": {
Type: schema.TypeString,
Required: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
address := v.(string)
if net.ParseIP(address) == nil {
errors = append(errors, fmt.Errorf("[ERROR] Invalid IP format: %s", address))
}
return
},
DiffSuppressFunc: func(k, o, n string, d *schema.ResourceData) bool {
newRoutesTo := net.ParseIP(n)
// Return true when n has the appropriate IPv6 format and
// the compressed value of n equals the compressed value of o.
return newRoutesTo != nil && (newRoutesTo.String() == net.ParseIP(o).String())
},
Description: "Route info",
},
"tags": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
Description: "List of tags",
},
"notes": {
Type: schema.TypeString,
Optional: true,
Description: "Additional notes",
},
},
}
}
func resourceIBMNetworkPublicIpCreate(d *schema.ResourceData, meta interface{}) error {
sess := meta.(conns.ClientSession).SoftLayerSession()
// Find price items with AdditionalServicesGlobalIpAddresses
productOrderContainer, err := buildGlobalIpProductOrderContainer(d, sess, AdditionalServicesGlobalIpAddressesPackageType)
if err != nil {
// Find price items with AdditionalServices
productOrderContainer, err = buildGlobalIpProductOrderContainer(d, sess, AdditionalServicesPackageType)
if err != nil {
return fmt.Errorf("[ERROR] Error creating network public ip: %s", err)
}
}
log.Println("[INFO] Creating network public ip")
receipt, err := services.GetProductOrderService(sess.SetRetries(0)).
PlaceOrder(productOrderContainer, sl.Bool(false))
if err != nil {
return fmt.Errorf("[ERROR] Error during creation of network public ip: %s", err)
}
globalIp, err := findGlobalIpByOrderId(sess, *receipt.OrderId, d)
if err != nil {
return fmt.Errorf("[ERROR] Error during creation of network public ip: %s", err)
}
d.SetId(fmt.Sprintf("%d", *globalIp.Id))
d.Set("ip_address", *globalIp.IpAddress.IpAddress)
return resourceIBMNetworkPublicIpUpdate(d, meta)
}
func resourceIBMNetworkPublicIpRead(d *schema.ResourceData, meta interface{}) error {
sess := meta.(conns.ClientSession).SoftLayerSession()
service := services.GetNetworkSubnetIpAddressGlobalService(sess)
globalIpId, err := strconv.Atoi(d.Id())
if err != nil {
return fmt.Errorf("[ERROR] Not a valid network public ip ID, must be an integer: %s", err)
}
globalIp, err := service.Id(globalIpId).Mask(GlobalIpMask).GetObject()
if err != nil {
return fmt.Errorf("[ERROR] Error retrieving network public Ip: %s", err)
}
d.Set("ip_address", *globalIp.IpAddress.IpAddress)
if globalIp.DestinationIpAddress != nil {
d.Set("routes_to", *globalIp.DestinationIpAddress.IpAddress)
}
if globalIp.IpAddress.Note != nil {
d.Set("notes", *globalIp.IpAddress.Note)
}
return nil
}
func resourceIBMNetworkPublicIpUpdate(d *schema.ResourceData, meta interface{}) error {
sess := meta.(conns.ClientSession).SoftLayerSession()
service := services.GetNetworkSubnetIpAddressGlobalService(sess)
globalIpId, err := strconv.Atoi(d.Id())
if err != nil {
return fmt.Errorf("[ERROR] Not a valid network public ip ID, must be an integer: %s", err)
}
routes_to := d.Get("routes_to").(string)
if strings.Contains(routes_to, ":") && len(routes_to) != 39 {
parts := strings.Split(routes_to, ":")
for x, s := range parts {
if s == "" {
zeroes := 9 - len(parts)
parts[x] = strings.Repeat("0000:", zeroes)[:(zeroes*4)+(zeroes-1)]
} else {
parts[x] = fmt.Sprintf("%04s", s)
}
}
routes_to = strings.Join(parts, ":")
d.Set("routes_to", routes_to)
}
_, err = service.Id(globalIpId).Route(sl.String(routes_to))
if err != nil {
return fmt.Errorf("[ERROR] Error editing network public Ip: %s", err)
}
// Update notes
if d.HasChange("notes") {
publicIp, err := service.Id(globalIpId).Mask(GlobalIpMask).GetObject()
if err != nil {
return fmt.Errorf("[ERROR] Error updating network public Ip: %s", err)
}
err = updatePublicIPNotes(d, sess, publicIp)
if err != nil {
return fmt.Errorf("[ERROR] Error editing network public Ip: %s", err)
}
}
stateConf := &resource.StateChangeConf{
Pending: []string{"pending"},
Target: []string{"complete"},
Refresh: func() (interface{}, string, error) {
transaction, err := service.Id(globalIpId).GetActiveTransaction()
if err != nil {
return datatypes.Network_Subnet_IpAddress_Global{}, "pending", err
}
if transaction.Id == nil {
return datatypes.Network_Subnet_IpAddress_Global{}, "complete", nil
}
return datatypes.Network_Subnet_IpAddress_Global{}, "pending", nil
},
Timeout: 10 * time.Minute,
Delay: 5 * time.Second,
MinTimeout: 3 * time.Second,
}
pendingResult, err := stateConf.WaitForState()
if err != nil {
return fmt.Errorf("[ERROR] Error waiting for network public ip destination ip address to become active: %s", err)
}
if _, ok := pendingResult.(datatypes.Network_Subnet_IpAddress_Global); ok {
return nil
}
return nil
}
func resourceIBMNetworkPublicIpDelete(d *schema.ResourceData, meta interface{}) error {
sess := meta.(conns.ClientSession).SoftLayerSession()
service := services.GetNetworkSubnetIpAddressGlobalService(sess)
globalIpId, err := strconv.Atoi(d.Id())
if err != nil {
return fmt.Errorf("[ERROR] Not a valid network public ip ID, must be an integer: %s", err)
}
billingItem, err := service.Id(globalIpId).GetBillingItem()
if err != nil {
return fmt.Errorf("[ERROR] Error deleting network public ip: %s", err)
}
if billingItem.Id == nil {
return nil
}
_, err = services.GetBillingItemService(sess).Id(*billingItem.Id).CancelService()
return err
}
func resourceIBMNetworkPublicIpExists(d *schema.ResourceData, meta interface{}) (bool, error) {
sess := meta.(conns.ClientSession).SoftLayerSession()
service := services.GetNetworkSubnetIpAddressGlobalService(sess)
globalIpId, err := strconv.Atoi(d.Id())
if err != nil {
return false, fmt.Errorf("[ERROR] Not a valid ID, must be an integer: %s", err)
}
result, err := service.Id(globalIpId).GetObject()
if err != nil {
if apiErr, ok := err.(sl.Error); ok && apiErr.StatusCode == 404 {
return false, nil
}
return false, fmt.Errorf("[ERROR] Error retrieving network public ip: %s", err)
}
return result.Id != nil && *result.Id == globalIpId, nil
}
func findGlobalIpByOrderId(sess *session.Session, orderId int, d *schema.ResourceData) (datatypes.Network_Subnet_IpAddress_Global, error) {
stateConf := &resource.StateChangeConf{
Pending: []string{"pending"},
Target: []string{"complete"},
Refresh: func() (interface{}, string, error) {
globalIps, err := services.GetAccountService(sess).
Filter(filter.Path("globalIpRecords.billingItem.orderItem.order.id").
Eq(strconv.Itoa(orderId)).Build()).
Mask("id,ipAddress[ipAddress]").
GetGlobalIpRecords()
if err != nil {
return datatypes.Network_Subnet_IpAddress_Global{}, "", err
}
if len(globalIps) == 1 && globalIps[0].IpAddress != nil {
return globalIps[0], "complete", nil
} else if len(globalIps) == 0 || len(globalIps) == 1 {
return datatypes.Network_Subnet_IpAddress_Global{}, "pending", nil
} else {
return nil, "", fmt.Errorf("[ERROR] Expected one network public ip: %s", err)
}
},
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 5 * time.Second,
MinTimeout: 3 * time.Second,
NotFoundChecks: 24 * 60,
}
pendingResult, err := stateConf.WaitForState()
if err != nil {
return datatypes.Network_Subnet_IpAddress_Global{}, err
}
if result, ok := pendingResult.(datatypes.Network_Subnet_IpAddress_Global); ok {
return result, nil
}
return datatypes.Network_Subnet_IpAddress_Global{},
fmt.Errorf("[ERROR] Cannot find network public ip with order id '%d'", orderId)
}
func buildGlobalIpProductOrderContainer(d *schema.ResourceData, sess *session.Session, packageType string) (
*datatypes.Container_Product_Order_Network_Subnet, error) {
// 1. Get a package
pkg, err := product.GetPackageByType(sess, packageType)
if err != nil {
return &datatypes.Container_Product_Order_Network_Subnet{}, err
}
// 2. Get all prices for the package
productItems, err := product.GetPackageProducts(sess, *pkg.Id)
if err != nil {
return &datatypes.Container_Product_Order_Network_Subnet{}, err
}
// 3. Find global ip prices
// the following looks for only IPV4 Global Ips only
globalIpKeyname := "GLOBAL_IPV4"
if strings.Contains(d.Get("routes_to").(string), ":") {
globalIpKeyname = "GLOBAL_IPV6"
}
// 4. Select items with a matching keyname
globalIpItems := []datatypes.Product_Item{}
for _, item := range productItems {
if *item.KeyName == globalIpKeyname {
globalIpItems = append(globalIpItems, item)
}
}
if len(globalIpItems) == 0 {
return &datatypes.Container_Product_Order_Network_Subnet{},
fmt.Errorf("[ERROR] No product items matching %s could be found", globalIpKeyname)
}
productOrderContainer := datatypes.Container_Product_Order_Network_Subnet{
Container_Product_Order: datatypes.Container_Product_Order{
PackageId: pkg.Id,
Prices: []datatypes.Product_Item_Price{
{
Id: globalIpItems[0].Prices[0].Id,
},
},
Quantity: sl.Int(1),
},
}
return &productOrderContainer, nil
}
func updatePublicIPNotes(d *schema.ResourceData, sess *session.Session, publicIP datatypes.Network_Subnet_IpAddress_Global) error {
id := *publicIP.IpAddress.Id
notes := d.Get("notes").(string)
if (publicIP.IpAddress.Note != nil && *publicIP.IpAddress.Note != notes) || (publicIP.IpAddress.Note == nil && notes != "") {
_, err := services.GetNetworkSubnetIpAddressService(sess).
Id(id).
EditObject(&datatypes.Network_Subnet_IpAddress{Note: sl.String(notes)})
if err != nil {
return fmt.Errorf("[ERROR] Error adding note to network public IP (%d): %s", id, err)
}
}
return nil
}