forked from hashicorp/terraform-provider-azurerm
/
resource_arm_firewall_network_rule_collection.go
432 lines (366 loc) · 13.4 KB
/
resource_arm_firewall_network_rule_collection.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
package azurerm
import (
"fmt"
"log"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-08-01/network"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/set"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
func resourceArmFirewallNetworkRuleCollection() *schema.Resource {
return &schema.Resource{
Create: resourceArmFirewallNetworkRuleCollectionCreateUpdate,
Read: resourceArmFirewallNetworkRuleCollectionRead,
Update: resourceArmFirewallNetworkRuleCollectionCreateUpdate,
Delete: resourceArmFirewallNetworkRuleCollectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateAzureFirewallName,
},
"azure_firewall_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateAzureFirewallName,
},
"resource_group_name": resourceGroupNameSchema(),
"priority": {
Type: schema.TypeInt,
Required: true,
ValidateFunc: validation.IntBetween(100, 65000),
},
"action": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(network.AzureFirewallRCActionTypeAllow),
string(network.AzureFirewallRCActionTypeDeny),
}, false),
},
"rule": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validate.NoEmptyStrings,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"source_addresses": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"destination_addresses": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"destination_ports": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"protocols": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice([]string{
string(network.Any),
string(network.ICMP),
string(network.TCP),
string(network.UDP),
}, false),
},
Set: schema.HashString,
},
},
},
},
},
}
}
func resourceArmFirewallNetworkRuleCollectionCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).azureFirewallsClient
ctx := meta.(*ArmClient).StopContext
name := d.Get("name").(string)
firewallName := d.Get("azure_firewall_name").(string)
resourceGroup := d.Get("resource_group_name").(string)
azureRMLockByName(firewallName, azureFirewallResourceName)
defer azureRMUnlockByName(firewallName, azureFirewallResourceName)
firewall, err := client.Get(ctx, resourceGroup, firewallName)
if err != nil {
return fmt.Errorf("Error retrieving Firewall %q (Resource Group %q): %+v", firewallName, resourceGroup, err)
}
if firewall.AzureFirewallPropertiesFormat == nil {
return fmt.Errorf("Error expanding Firewall %q (Resource Group %q): `properties` was nil.", firewallName, resourceGroup)
}
props := *firewall.AzureFirewallPropertiesFormat
if props.NetworkRuleCollections == nil {
return fmt.Errorf("Error expanding Firewall %q (Resource Group %q): `properties.NetworkRuleCollections` was nil.", firewallName, resourceGroup)
}
ruleCollections := *props.NetworkRuleCollections
networkRules := expandArmFirewallNetworkRules(d.Get("rule").(*schema.Set))
priority := d.Get("priority").(int)
newRuleCollection := network.AzureFirewallNetworkRuleCollection{
Name: utils.String(name),
AzureFirewallNetworkRuleCollectionPropertiesFormat: &network.AzureFirewallNetworkRuleCollectionPropertiesFormat{
Action: &network.AzureFirewallRCAction{
Type: network.AzureFirewallRCActionType(d.Get("action").(string)),
},
Priority: utils.Int32(int32(priority)),
Rules: &networkRules,
},
}
index := -1
var id string
// determine if this already exists
for i, v := range ruleCollections {
if v.Name == nil || v.ID == nil {
continue
}
if *v.Name == name {
index = i
id = *v.ID
break
}
}
if !d.IsNewResource() {
if index == -1 {
return fmt.Errorf("Error locating Network Rule Collection %q (Firewall %q / Resource Group %q)", name, firewallName, resourceGroup)
}
ruleCollections[index] = newRuleCollection
} else {
if requireResourcesToBeImported && d.IsNewResource() {
if index != -1 {
return tf.ImportAsExistsError("azurerm_firewall_network_rule_collection", id)
}
}
// first double check it doesn't already exist
ruleCollections = append(ruleCollections, newRuleCollection)
}
firewall.AzureFirewallPropertiesFormat.NetworkRuleCollections = &ruleCollections
future, err := client.CreateOrUpdate(ctx, resourceGroup, firewallName, firewall)
if err != nil {
return fmt.Errorf("Error creating/updating Network Rule Collection %q in Firewall %q (Resource Group %q): %+v", name, firewallName, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for creation/update of Network Rule Collection %q of Firewall %q (Resource Group %q): %+v", name, firewallName, resourceGroup, err)
}
read, err := client.Get(ctx, resourceGroup, firewallName)
if err != nil {
return fmt.Errorf("Error retrieving Firewall %q (Resource Group %q): %+v", firewallName, resourceGroup, err)
}
var collectionID string
if props := read.AzureFirewallPropertiesFormat; props != nil {
if collections := props.NetworkRuleCollections; collections != nil {
for _, collection := range *collections {
if collection.Name == nil {
continue
}
if *collection.Name == name {
collectionID = *collection.ID
break
}
}
}
}
if collectionID == "" {
return fmt.Errorf("Cannot find ID for Network Rule Collection %q (Azure Firewall %q / Resource Group %q)", name, firewallName, resourceGroup)
}
d.SetId(collectionID)
return resourceArmFirewallNetworkRuleCollectionRead(d, meta)
}
func resourceArmFirewallNetworkRuleCollectionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).azureFirewallsClient
ctx := meta.(*ArmClient).StopContext
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
firewallName := id.Path["azureFirewalls"]
name := id.Path["networkRuleCollections"]
read, err := client.Get(ctx, resourceGroup, firewallName)
if err != nil {
if utils.ResponseWasNotFound(read.Response) {
log.Printf("[DEBUG] Azure Firewall %q (Resource Group %q) was not found - removing from state!", name, resourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("Error retrieving Azure Firewall %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if read.AzureFirewallPropertiesFormat == nil {
return fmt.Errorf("Error retrieving Network Rule Collection %q (Firewall %q / Resource Group %q): `props` was nil", name, firewallName, resourceGroup)
}
props := *read.AzureFirewallPropertiesFormat
if props.NetworkRuleCollections == nil {
return fmt.Errorf("Error retrieving Network Rule Collection %q (Firewall %q / Resource Group %q): `props.NetworkRuleCollections` was nil", name, firewallName, resourceGroup)
}
var rule *network.AzureFirewallNetworkRuleCollection
for _, r := range *props.NetworkRuleCollections {
if r.Name == nil {
continue
}
if *r.Name == name {
rule = &r
break
}
}
if rule == nil {
log.Printf("[DEBUG] Network Rule Collection %q was not found on Firewall %q (Resource Group %q) - removing from state!", name, firewallName, resourceGroup)
d.SetId("")
return nil
}
d.Set("name", rule.Name)
d.Set("azure_firewall_name", firewallName)
d.Set("resource_group_name", resourceGroup)
if props := rule.AzureFirewallNetworkRuleCollectionPropertiesFormat; props != nil {
if action := props.Action; action != nil {
d.Set("action", string(action.Type))
}
if priority := props.Priority; priority != nil {
d.Set("priority", int(*priority))
}
flattenedRules := flattenFirewallNetworkRuleCollectionRules(props.Rules)
if err := d.Set("rule", flattenedRules); err != nil {
return fmt.Errorf("Error setting `rule`: %+v", err)
}
}
return nil
}
func resourceArmFirewallNetworkRuleCollectionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).azureFirewallsClient
ctx := meta.(*ArmClient).StopContext
id, err := parseAzureResourceID(d.Id())
if err != nil {
return err
}
resourceGroup := id.ResourceGroup
firewallName := id.Path["azureFirewalls"]
name := id.Path["networkRuleCollections"]
azureRMLockByName(firewallName, azureFirewallResourceName)
defer azureRMUnlockByName(firewallName, azureFirewallResourceName)
firewall, err := client.Get(ctx, resourceGroup, firewallName)
if err != nil {
if utils.ResponseWasNotFound(firewall.Response) {
// assume deleted
return nil
}
return fmt.Errorf("Error making Read request on Azure Firewall %q (Resource Group %q): %+v", firewallName, resourceGroup, err)
}
props := firewall.AzureFirewallPropertiesFormat
if props == nil {
return fmt.Errorf("Error retrieving Network Rule Collection %q (Firewall %q / Resource Group %q): `props` was nil", name, firewallName, resourceGroup)
}
if props.NetworkRuleCollections == nil {
return fmt.Errorf("Error retrieving Network Rule Collection %q (Firewall %q / Resource Group %q): `props.NetworkRuleCollections` was nil", name, firewallName, resourceGroup)
}
networkRules := make([]network.AzureFirewallNetworkRuleCollection, 0)
for _, rule := range *props.NetworkRuleCollections {
if rule.Name == nil {
continue
}
if *rule.Name != name {
networkRules = append(networkRules, rule)
}
}
props.NetworkRuleCollections = &networkRules
future, err := client.CreateOrUpdate(ctx, resourceGroup, firewallName, firewall)
if err != nil {
return fmt.Errorf("Error deleting Network Rule Collection %q from Firewall %q (Resource Group %q): %+v", name, firewallName, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting for deletion of Network Rule Collection %q from Firewall %q (Resource Group %q): %+v", name, firewallName, resourceGroup, err)
}
return nil
}
func expandArmFirewallNetworkRules(input *schema.Set) []network.AzureFirewallNetworkRule {
nwRules := input.List()
rules := make([]network.AzureFirewallNetworkRule, 0)
for _, nwRule := range nwRules {
rule := nwRule.(map[string]interface{})
name := rule["name"].(string)
description := rule["description"].(string)
sourceAddresses := make([]string, 0)
for _, v := range rule["source_addresses"].(*schema.Set).List() {
sourceAddresses = append(sourceAddresses, v.(string))
}
destinationAddresses := make([]string, 0)
for _, v := range rule["destination_addresses"].(*schema.Set).List() {
destinationAddresses = append(destinationAddresses, v.(string))
}
destinationPorts := make([]string, 0)
for _, v := range rule["destination_ports"].(*schema.Set).List() {
destinationPorts = append(destinationPorts, v.(string))
}
ruleToAdd := network.AzureFirewallNetworkRule{
Name: utils.String(name),
Description: utils.String(description),
SourceAddresses: &sourceAddresses,
DestinationAddresses: &destinationAddresses,
DestinationPorts: &destinationPorts,
}
nrProtocols := make([]network.AzureFirewallNetworkRuleProtocol, 0)
protocols := rule["protocols"].(*schema.Set)
for _, v := range protocols.List() {
s := network.AzureFirewallNetworkRuleProtocol(v.(string))
nrProtocols = append(nrProtocols, s)
}
ruleToAdd.Protocols = &nrProtocols
rules = append(rules, ruleToAdd)
}
return rules
}
func flattenFirewallNetworkRuleCollectionRules(rules *[]network.AzureFirewallNetworkRule) []map[string]interface{} {
outputs := make([]map[string]interface{}, 0)
if rules == nil {
return outputs
}
for _, rule := range *rules {
output := make(map[string]interface{})
if rule.Name != nil {
output["name"] = *rule.Name
}
if rule.Description != nil {
output["description"] = *rule.Description
}
if rule.SourceAddresses != nil {
output["source_addresses"] = set.FromStringSlice(*rule.SourceAddresses)
}
if rule.DestinationAddresses != nil {
output["destination_addresses"] = set.FromStringSlice(*rule.DestinationAddresses)
}
if rule.DestinationPorts != nil {
output["destination_ports"] = set.FromStringSlice(*rule.DestinationPorts)
}
protocols := make([]string, 0)
if rule.Protocols != nil {
for _, protocol := range *rule.Protocols {
protocols = append(protocols, string(protocol))
}
}
output["protocols"] = set.FromStringSlice(protocols)
outputs = append(outputs, output)
}
return outputs
}