forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_arm_loadbalancer_nat_rule.go
315 lines (259 loc) · 9.81 KB
/
resource_arm_loadbalancer_nat_rule.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
package azurerm
import (
"fmt"
"log"
"time"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-04-01/network"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
func resourceArmLoadBalancerNatRule() *schema.Resource {
return &schema.Resource{
Create: resourceArmLoadBalancerNatRuleCreateUpdate,
Read: resourceArmLoadBalancerNatRuleRead,
Update: resourceArmLoadBalancerNatRuleCreateUpdate,
Delete: resourceArmLoadBalancerNatRuleDelete,
Importer: &schema.ResourceImporter{
State: loadBalancerSubResourceStateImporter,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.NoZeroValues,
},
"location": deprecatedLocationSchema(),
"resource_group_name": resourceGroupNameSchema(),
"loadbalancer_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: azure.ValidateResourceID,
},
"protocol": {
Type: schema.TypeString,
Required: true,
StateFunc: ignoreCaseStateFunc,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: validation.StringInSlice([]string{
string(network.TransportProtocolAll),
string(network.TransportProtocolTCP),
string(network.TransportProtocolUDP),
}, true),
},
"enable_floating_ip": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"frontend_port": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validate.PortNumber,
},
"backend_port": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validate.PortNumber,
},
"frontend_ip_configuration_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.NoZeroValues,
},
"frontend_ip_configuration_id": {
Type: schema.TypeString,
Computed: true,
},
"backend_ip_configuration_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceArmLoadBalancerNatRuleCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).loadBalancerClient
ctx := meta.(*ArmClient).StopContext
loadBalancerID := d.Get("loadbalancer_id").(string)
armMutexKV.Lock(loadBalancerID)
defer armMutexKV.Unlock(loadBalancerID)
loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta)
if err != nil {
return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err)
}
if !exists {
d.SetId("")
log.Printf("[INFO] Load Balancer %q not found. Removing from state", d.Get("name").(string))
return nil
}
newNatRule, err := expandAzureRmLoadBalancerNatRule(d, loadBalancer)
if err != nil {
return fmt.Errorf("Error Expanding NAT Rule: %+v", err)
}
natRules := append(*loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules, *newNatRule)
existingNatRule, existingNatRuleIndex, exists := findLoadBalancerNatRuleByName(loadBalancer, d.Get("name").(string))
if exists {
if d.Get("name").(string) == *existingNatRule.Name {
// this nat rule is being updated/reapplied remove old copy from the slice
natRules = append(natRules[:existingNatRuleIndex], natRules[existingNatRuleIndex+1:]...)
}
}
loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules = &natRules
resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
if err != nil {
return fmt.Errorf("Error Getting Load Balancer Name and Group: %+v", err)
}
future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer)
if err != nil {
return fmt.Errorf("Error Creating / Updating Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err)
}
err = future.WaitForCompletionRef(ctx, client.Client)
if err != nil {
return fmt.Errorf("Error waiting for completion of Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err)
}
read, err := client.Get(ctx, resGroup, loadBalancerName, "")
if err != nil {
return fmt.Errorf("Error retrieving Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read Load Balancer %q (Resource Group %q) ID", loadBalancerName, resGroup)
}
var natRuleId string
for _, InboundNatRule := range *(*read.LoadBalancerPropertiesFormat).InboundNatRules {
if *InboundNatRule.Name == d.Get("name").(string) {
natRuleId = *InboundNatRule.ID
}
}
if natRuleId != "" {
d.SetId(natRuleId)
} else {
return fmt.Errorf("Cannot find created Load Balancer NAT Rule ID %q", natRuleId)
}
// TODO: is this still needed?
log.Printf("[DEBUG] Waiting for Load Balancer (%s) to become available", loadBalancerName)
stateConf := &resource.StateChangeConf{
Pending: []string{"Accepted", "Updating"},
Target: []string{"Succeeded"},
Refresh: loadbalancerStateRefreshFunc(ctx, client, resGroup, loadBalancerName),
Timeout: 10 * time.Minute,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Error waiting for Load Balancer (%s) to become available: %s", loadBalancerName, err)
}
return resourceArmLoadBalancerNatRuleRead(d, meta)
}
func resourceArmLoadBalancerNatRuleRead(d *schema.ResourceData, meta interface{}) error {
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
name := id.Path["inboundNatRules"]
loadBalancer, exists, err := retrieveLoadBalancerById(d.Get("loadbalancer_id").(string), meta)
if err != nil {
return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err)
}
if !exists {
d.SetId("")
log.Printf("[INFO] Load Balancer %q not found. Removing from state", name)
return nil
}
config, _, exists := findLoadBalancerNatRuleByName(loadBalancer, name)
if !exists {
d.SetId("")
log.Printf("[INFO] Load Balancer Nat Rule %q not found. Removing from state", name)
return nil
}
d.Set("name", config.Name)
d.Set("resource_group_name", id.ResourceGroup)
if props := config.InboundNatRulePropertiesFormat; props != nil {
d.Set("protocol", props.Protocol)
d.Set("frontend_port", props.FrontendPort)
d.Set("backend_port", props.BackendPort)
d.Set("enable_floating_ip", props.EnableFloatingIP)
if ipconfiguration := props.FrontendIPConfiguration; ipconfiguration != nil {
fipID, err := parseAzureResourceID(*ipconfiguration.ID)
if err != nil {
return err
}
d.Set("frontend_ip_configuration_name", fipID.Path["frontendIPConfigurations"])
d.Set("frontend_ip_configuration_id", ipconfiguration.ID)
}
if ipconfiguration := props.BackendIPConfiguration; ipconfiguration != nil {
d.Set("backend_ip_configuration_id", ipconfiguration.ID)
}
}
return nil
}
func resourceArmLoadBalancerNatRuleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).loadBalancerClient
ctx := meta.(*ArmClient).StopContext
loadBalancerID := d.Get("loadbalancer_id").(string)
armMutexKV.Lock(loadBalancerID)
defer armMutexKV.Unlock(loadBalancerID)
loadBalancer, exists, err := retrieveLoadBalancerById(loadBalancerID, meta)
if err != nil {
return fmt.Errorf("Error Getting Load Balancer By ID: %+v", err)
}
if !exists {
d.SetId("")
return nil
}
_, index, exists := findLoadBalancerNatRuleByName(loadBalancer, d.Get("name").(string))
if !exists {
return nil
}
oldNatRules := *loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules
newNatRules := append(oldNatRules[:index], oldNatRules[index+1:]...)
loadBalancer.LoadBalancerPropertiesFormat.InboundNatRules = &newNatRules
resGroup, loadBalancerName, err := resourceGroupAndLBNameFromId(d.Get("loadbalancer_id").(string))
if err != nil {
return fmt.Errorf("Error Getting Load Balancer Name and Group: %+v", err)
}
future, err := client.CreateOrUpdate(ctx, resGroup, loadBalancerName, *loadBalancer)
if err != nil {
return fmt.Errorf("Error Creating/Updating Load Balancer %q (Resource Group %q) %+v", loadBalancerName, resGroup, err)
}
err = future.WaitForCompletionRef(ctx, client.Client)
if err != nil {
return fmt.Errorf("Error waiting for the completion of Load Balancer updates for %q (Resource Group %q) %+v", loadBalancerName, resGroup, err)
}
read, err := client.Get(ctx, resGroup, loadBalancerName, "")
if err != nil {
return fmt.Errorf("Error retrieving Load Balancer %q (Resource Group %q): %+v", loadBalancerName, resGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read Load Balancer %q (resource group %q) ID", loadBalancerName, resGroup)
}
return nil
}
func expandAzureRmLoadBalancerNatRule(d *schema.ResourceData, lb *network.LoadBalancer) (*network.InboundNatRule, error) {
properties := network.InboundNatRulePropertiesFormat{
Protocol: network.TransportProtocol(d.Get("protocol").(string)),
FrontendPort: utils.Int32(int32(d.Get("frontend_port").(int))),
BackendPort: utils.Int32(int32(d.Get("backend_port").(int))),
}
if v, ok := d.GetOk("enable_floating_ip"); ok {
properties.EnableFloatingIP = utils.Bool(v.(bool))
}
if v := d.Get("frontend_ip_configuration_name").(string); v != "" {
rule, exists := findLoadBalancerFrontEndIpConfigurationByName(lb, v)
if !exists {
return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v)
}
properties.FrontendIPConfiguration = &network.SubResource{
ID: rule.ID,
}
}
natRule := network.InboundNatRule{
Name: utils.String(d.Get("name").(string)),
InboundNatRulePropertiesFormat: &properties,
}
return &natRule, nil
}