-
Notifications
You must be signed in to change notification settings - Fork 21
/
resource_natgateway.go
383 lines (321 loc) · 11.2 KB
/
resource_natgateway.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
package ionoscloud
import (
"context"
"fmt"
"log"
"strings"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/services"
"github.com/ionos-cloud/terraform-provider-ionoscloud/v6/services/cloudapi"
"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"
ionoscloud "github.com/ionos-cloud/sdk-go/v6"
)
func resourceNatGateway() *schema.Resource {
return &schema.Resource{
CreateContext: resourceNatGatewayCreate,
ReadContext: resourceNatGatewayRead,
UpdateContext: resourceNatGatewayUpdate,
DeleteContext: resourceNatGatewayDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceNatGatewayImport,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Description: "Name of the NAT gateway",
Required: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace),
},
"public_ips": {
Type: schema.TypeSet,
Description: "Collection of public IP addresses of the NAT gateway. Should be customer reserved IP addresses in that location",
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"lans": {
Type: schema.TypeList,
Description: "A list of Local Area Networks the node pool should be part of",
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeInt,
Description: "Id for the LAN connected to the NAT gateway",
Required: true,
},
"gateway_ips": {
Type: schema.TypeList,
Description: "Collection of gateway IP addresses of the NAT gateway. Will be auto-generated " +
"if not provided. Should ideally be an IP belonging to the same subnet as the LAN",
Optional: true,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
DiffSuppressFunc: DiffCidr,
},
},
},
},
"datacenter_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsNotWhiteSpace),
},
},
Timeouts: &resourceDefaultTimeouts,
}
}
func resourceNatGatewayCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
name := d.Get("name").(string)
natGateway := ionoscloud.NatGateway{
Properties: &ionoscloud.NatGatewayProperties{
Name: &name,
},
}
if publicIpsVal, publicIpsOk := d.GetOk("public_ips"); publicIpsOk {
publicIpsVal := publicIpsVal.(*schema.Set).List()
if publicIpsVal != nil {
publicIps := make([]string, 0)
for _, publicIp := range publicIpsVal {
publicIps = append(publicIps, publicIp.(string))
}
natGateway.Properties.PublicIps = &publicIps
} else {
diags := diag.FromErr(fmt.Errorf("you must provide public_ips for nat gateway resource \n"))
return diags
}
}
if lansVal, lansOK := d.GetOk("lans"); lansOK {
if lansVal.([]interface{}) != nil {
updateLans := false
var lans []ionoscloud.NatGatewayLanProperties
for lanIndex := range lansVal.([]interface{}) {
lan := ionoscloud.NatGatewayLanProperties{}
addLan := false
if lanID, lanIdOk := d.GetOk(fmt.Sprintf("lans.%d.id", lanIndex)); lanIdOk {
lanID := int32(lanID.(int))
lan.Id = &lanID
addLan = true
}
if lanGatewayIps, lanGatewayIpsOk := d.GetOk(fmt.Sprintf("lans.%d.gateway_ips", lanIndex)); lanGatewayIpsOk {
lanGatewayIps := lanGatewayIps.([]interface{})
if lanGatewayIps != nil {
gatewayIps := make([]string, len(lanGatewayIps), len(lanGatewayIps))
for idx := range lanGatewayIps {
gatewayIps[idx] = fmt.Sprint(lanGatewayIps[idx])
}
lan.GatewayIps = &gatewayIps
}
}
if addLan {
lans = append(lans, lan)
}
}
if len(lans) > 0 {
updateLans = true
}
if updateLans == true {
log.Printf("[INFO] NatGateway LANs set to %+v", lans)
natGateway.Properties.Lans = &lans
} else {
diags := diag.FromErr(fmt.Errorf("you must provide lans for the nat gateway resource \n"))
return diags
}
}
}
dcId := d.Get("datacenter_id").(string)
log.Printf("[*****] %+v\n", natGateway)
natGatewayResp, apiResponse, err := client.NATGatewaysApi.DatacentersNatgatewaysPost(ctx, dcId).NatGateway(natGateway).Execute()
logApiRequestTime(apiResponse)
if err != nil {
d.SetId("")
diags := diag.FromErr(fmt.Errorf("error creating natGateway: %w, %s", err, responseBody(apiResponse)))
return diags
}
d.SetId(*natGatewayResp.Id)
if errState := cloudapi.WaitForStateChange(ctx, meta, d, apiResponse, schema.TimeoutCreate); errState != nil {
if cloudapi.IsRequestFailed(errState) {
d.SetId("")
}
return diag.FromErr(errState)
}
return resourceNatGatewayRead(ctx, d, meta)
}
func resourceNatGatewayRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
dcId := d.Get("datacenter_id").(string)
natGateway, apiResponse, err := client.NATGatewaysApi.DatacentersNatgatewaysFindByNatGatewayId(ctx, dcId, d.Id()).Execute()
logApiRequestTime(apiResponse)
if err != nil {
log.Printf("[INFO] Resource %s not found: %+v", d.Id(), err)
if httpNotFound(apiResponse) {
d.SetId("")
return nil
}
}
log.Printf("[INFO] Successfully retreived nat gateway %s: %+v", d.Id(), natGateway)
if err := setNatGatewayData(d, &natGateway); err != nil {
diags := diag.FromErr(err)
return diags
}
return nil
}
func resourceNatGatewayUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
request := ionoscloud.NatGateway{
Properties: &ionoscloud.NatGatewayProperties{},
}
dcId := d.Get("datacenter_id").(string)
if d.HasChange("name") {
_, v := d.GetChange("name")
vStr := v.(string)
request.Properties.Name = &vStr
}
if d.HasChange("public_ips") {
oldPublicIps, newPublicIps := d.GetChange("public_ips")
log.Printf("[INFO] nat gateway public IPs changed from %+v to %+v", oldPublicIps, newPublicIps)
publicIpsVal := newPublicIps.(*schema.Set).List()
if publicIpsVal != nil {
publicIps := make([]string, 0)
for _, publicIp := range publicIpsVal {
publicIps = append(publicIps, publicIp.(string))
}
request.Properties.PublicIps = &publicIps
}
}
if d.HasChange("lans") {
oldLANs, newLANs := d.GetChange("lans")
if newLANs.([]interface{}) != nil {
updateLans := false
var lans []ionoscloud.NatGatewayLanProperties
for lanIndex := range newLANs.([]interface{}) {
lan := ionoscloud.NatGatewayLanProperties{}
addLan := false
if lanID, lanIdOk := d.GetOk(fmt.Sprintf("lans.%d.id", lanIndex)); lanIdOk {
lanID := int32(lanID.(int))
lan.Id = &lanID
addLan = true
}
if lanGatewayIps, lanGatewayIpsOk := d.GetOk(fmt.Sprintf("lans.%d.gateway_ips", lanIndex)); lanGatewayIpsOk {
lanGatewayIps := lanGatewayIps.([]interface{})
if lanGatewayIps != nil {
gatewayIps := make([]string, 0)
for _, lanGatewayIp := range lanGatewayIps {
gatewayIps = append(gatewayIps, lanGatewayIp.(string))
}
lan.GatewayIps = &gatewayIps
}
}
if addLan {
lans = append(lans, lan)
}
}
if len(lans) > 0 {
updateLans = true
}
if updateLans == true {
log.Printf("[INFO] nat gateway LANs changed from %+v to %+v", oldLANs, newLANs)
request.Properties.Lans = &lans
}
}
}
_, apiResponse, err := client.NATGatewaysApi.DatacentersNatgatewaysPatch(ctx, dcId, d.Id()).NatGatewayProperties(*request.Properties).Execute()
logApiRequestTime(apiResponse)
if err != nil {
diags := diag.FromErr(fmt.Errorf("an error occured while updating a nat gateway ID %s %w", d.Id(), err))
return diags
}
if errState := cloudapi.WaitForStateChange(ctx, meta, d, apiResponse, schema.TimeoutUpdate); errState != nil {
return diag.FromErr(errState)
}
return resourceNatGatewayRead(ctx, d, meta)
}
func resourceNatGatewayDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(services.SdkBundle).CloudApiClient
dcId := d.Get("datacenter_id").(string)
apiResponse, err := client.NATGatewaysApi.DatacentersNatgatewaysDelete(ctx, dcId, d.Id()).Execute()
logApiRequestTime(apiResponse)
if err != nil {
diags := diag.FromErr(fmt.Errorf("an error occured while deleting a nat gateway %s %w", d.Id(), err))
return diags
}
if errState := cloudapi.WaitForStateChange(ctx, meta, d, apiResponse, schema.TimeoutDelete); errState != nil {
return diag.FromErr(errState)
}
d.SetId("")
return nil
}
func resourceNatGatewayImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
client := meta.(services.SdkBundle).CloudApiClient
parts := strings.Split(d.Id(), "/")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return nil, fmt.Errorf("invalid import id %q. Expecting {datacenter}/{natgateway}", d.Id())
}
dcId := parts[0]
natGatewayId := parts[1]
natGateway, apiResponse, err := client.NATGatewaysApi.DatacentersNatgatewaysFindByNatGatewayId(ctx, dcId, natGatewayId).Execute()
logApiRequestTime(apiResponse)
if err != nil {
log.Printf("[INFO] Resource %s not found: %+v", d.Id(), err)
if httpNotFound(apiResponse) {
d.SetId("")
return nil, fmt.Errorf("unable to find nat gateway %q", natGatewayId)
}
return nil, fmt.Errorf("an error occured while retrieving nat gateway %q: %q ", natGatewayId, err)
}
if err := d.Set("datacenter_id", dcId); err != nil {
return nil, err
}
if err := setNatGatewayData(d, &natGateway); err != nil {
return nil, err
}
return []*schema.ResourceData{d}, nil
}
func setNatGatewayData(d *schema.ResourceData, natGateway *ionoscloud.NatGateway) error {
if natGateway.Id != nil {
d.SetId(*natGateway.Id)
}
if natGateway.Properties != nil {
if natGateway.Properties.Name != nil {
err := d.Set("name", *natGateway.Properties.Name)
if err != nil {
return fmt.Errorf("error while setting name property for nat gateway %s: %w", d.Id(), err)
}
}
if natGateway.Properties.PublicIps != nil {
err := d.Set("public_ips", *natGateway.Properties.PublicIps)
if err != nil {
return fmt.Errorf("error while setting public_ips property for nat gateway %s: %w", d.Id(), err)
}
}
if natGateway.Properties.Lans != nil && len(*natGateway.Properties.Lans) > 0 {
var natGatewayLans []interface{}
for _, lan := range *natGateway.Properties.Lans {
lanEntry := make(map[string]interface{})
if lan.Id != nil {
lanEntry["id"] = *lan.Id
}
if len(*lan.GatewayIps) > 0 {
var gatewayIps []interface{}
for _, gatewayIp := range *lan.GatewayIps {
gatewayIps = append(gatewayIps, gatewayIp)
}
lanEntry["gateway_ips"] = gatewayIps
}
natGatewayLans = append(natGatewayLans, lanEntry)
}
if len(natGatewayLans) > 0 {
if err := d.Set("lans", natGatewayLans); err != nil {
return fmt.Errorf("error while setting lans property for nat gateway %s: %w", d.Id(), err)
}
}
}
}
return nil
}