-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
resource_compute_firewall.go
488 lines (416 loc) · 12.9 KB
/
resource_compute_firewall.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package google
import (
"bytes"
"fmt"
"sort"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
computeBeta "google.golang.org/api/compute/v0.beta"
"google.golang.org/api/compute/v1"
)
const COMPUTE_FIREWALL_PRIORITY_DEFAULT = 1000
var FirewallBaseApiVersion = v1
var FirewallVersionedFeatures = []Feature{
Feature{Version: v0beta, Item: "deny"},
Feature{Version: v0beta, Item: "direction"},
Feature{Version: v0beta, Item: "destination_ranges"},
Feature{Version: v0beta, Item: "priority", DefaultValue: COMPUTE_FIREWALL_PRIORITY_DEFAULT},
}
func resourceComputeFirewall() *schema.Resource {
return &schema.Resource{
Create: resourceComputeFirewallCreate,
Read: resourceComputeFirewallRead,
Update: resourceComputeFirewallUpdate,
Delete: resourceComputeFirewallDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
SchemaVersion: 1,
MigrateState: resourceComputeFirewallMigrateState,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"network": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
},
"priority": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Default: COMPUTE_FIREWALL_PRIORITY_DEFAULT,
ValidateFunc: validation.IntBetween(0, 65535),
},
"allow": {
Type: schema.TypeSet,
Optional: true,
ConflictsWith: []string{"deny"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"protocol": {
Type: schema.TypeString,
Required: true,
},
"ports": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
Set: resourceComputeFirewallRuleHash,
},
"deny": {
Type: schema.TypeSet,
Optional: true,
ConflictsWith: []string{"allow"},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"protocol": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"ports": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
ForceNew: true,
},
},
},
Set: resourceComputeFirewallRuleHash,
// Unlike allow, deny can't be updated upstream
ForceNew: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"direction": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"INGRESS", "EGRESS"}, false),
ForceNew: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"self_link": {
Type: schema.TypeString,
Computed: true,
},
"source_ranges": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"source_tags": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
"destination_ranges": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
ConflictsWith: []string{"source_ranges", "source_tags"},
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
ForceNew: true,
},
"target_tags": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
},
}
}
func resourceComputeFirewallRuleHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["protocol"].(string)))
// We need to make sure to sort the strings below so that we always
// generate the same hash code no matter what is in the set.
if v, ok := m["ports"]; ok {
s := convertStringArr(v.([]interface{}))
sort.Strings(s)
for _, v := range s {
buf.WriteString(fmt.Sprintf("%s-", v))
}
}
return hashcode.String(buf.String())
}
func resourceComputeFirewallCreate(d *schema.ResourceData, meta interface{}) error {
computeApiVersion := getComputeApiVersion(d, FirewallBaseApiVersion, FirewallVersionedFeatures)
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
firewall, err := resourceFirewall(d, meta, computeApiVersion)
if err != nil {
return err
}
var op interface{}
switch computeApiVersion {
case v1:
firewallV1 := &compute.Firewall{}
err = Convert(firewall, firewallV1)
if err != nil {
return err
}
op, err = config.clientCompute.Firewalls.Insert(project, firewallV1).Do()
if err != nil {
return fmt.Errorf("Error creating firewall: %s", err)
}
case v0beta:
firewallV0Beta := &computeBeta.Firewall{}
err = Convert(firewall, firewallV0Beta)
if err != nil {
return err
}
op, err = config.clientComputeBeta.Firewalls.Insert(project, firewallV0Beta).Do()
if err != nil {
return fmt.Errorf("Error creating firewall: %s", err)
}
}
// It probably maybe worked, so store the ID now
d.SetId(firewall.Name)
err = computeSharedOperationWait(config.clientCompute, op, project, "Creating Firewall")
if err != nil {
return err
}
return resourceComputeFirewallRead(d, meta)
}
func flattenAllowed(allowed []*computeBeta.FirewallAllowed) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(allowed))
for _, allow := range allowed {
allowMap := make(map[string]interface{})
allowMap["protocol"] = allow.IPProtocol
allowMap["ports"] = allow.Ports
result = append(result, allowMap)
}
return result
}
func flattenDenied(denied []*computeBeta.FirewallDenied) []map[string]interface{} {
result := make([]map[string]interface{}, 0, len(denied))
for _, deny := range denied {
denyMap := make(map[string]interface{})
denyMap["protocol"] = deny.IPProtocol
denyMap["ports"] = deny.Ports
result = append(result, denyMap)
}
return result
}
func resourceComputeFirewallRead(d *schema.ResourceData, meta interface{}) error {
computeApiVersion := getComputeApiVersion(d, FirewallBaseApiVersion, FirewallVersionedFeatures)
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
firewall := &computeBeta.Firewall{}
switch computeApiVersion {
case v1:
firewallV1, err := config.clientCompute.Firewalls.Get(project, d.Id()).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Firewall %q", d.Get("name").(string)))
}
err = Convert(firewallV1, firewall)
if err != nil {
return err
}
// During firewall conversion from v1 to v0beta, the value for Priority is read as 0 (as it doesn't exist in
// v1). Unfortunately this is a valid value, but not the same as the default. To avoid this, we explicitly set
// the default value here.
firewall.Priority = COMPUTE_FIREWALL_PRIORITY_DEFAULT
case v0beta:
firewallV0Beta, err := config.clientComputeBeta.Firewalls.Get(project, d.Id()).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Firewall %q", d.Get("name").(string)))
}
err = Convert(firewallV0Beta, firewall)
if err != nil {
return err
}
}
d.Set("self_link", ConvertSelfLinkToV1(firewall.SelfLink))
d.Set("name", firewall.Name)
d.Set("network", ConvertSelfLinkToV1(firewall.Network))
// Unlike most other Beta properties, direction will always have a value even when
// a zero is sent by the client. We'll never revert back to v1 without conditionally reading it.
// This if statement blocks Beta import for this resource.
if _, ok := d.GetOk("direction"); ok {
d.Set("direction", firewall.Direction)
}
d.Set("description", firewall.Description)
d.Set("project", project)
d.Set("source_ranges", firewall.SourceRanges)
d.Set("source_tags", firewall.SourceTags)
d.Set("destination_ranges", firewall.DestinationRanges)
d.Set("target_tags", firewall.TargetTags)
d.Set("allow", flattenAllowed(firewall.Allowed))
d.Set("deny", flattenDenied(firewall.Denied))
d.Set("priority", int(firewall.Priority))
return nil
}
func resourceComputeFirewallUpdate(d *schema.ResourceData, meta interface{}) error {
computeApiVersion := getComputeApiVersionUpdate(d, FirewallBaseApiVersion, FirewallVersionedFeatures, []Feature{})
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
d.Partial(true)
firewall, err := resourceFirewall(d, meta, computeApiVersion)
if err != nil {
return err
}
var op interface{}
switch computeApiVersion {
case v1:
firewallV1 := &compute.Firewall{}
err = Convert(firewall, firewallV1)
if err != nil {
return err
}
op, err = config.clientCompute.Firewalls.Update(project, d.Id(), firewallV1).Do()
if err != nil {
return fmt.Errorf("Error updating firewall: %s", err)
}
case v0beta:
firewallV0Beta := &computeBeta.Firewall{}
err = Convert(firewall, firewallV0Beta)
if err != nil {
return err
}
op, err = config.clientComputeBeta.Firewalls.Update(project, d.Id(), firewallV0Beta).Do()
if err != nil {
return fmt.Errorf("Error updating firewall: %s", err)
}
}
err = computeSharedOperationWait(config.clientCompute, op, project, "Updating Firewall")
if err != nil {
return err
}
d.Partial(false)
return resourceComputeFirewallRead(d, meta)
}
func resourceComputeFirewallDelete(d *schema.ResourceData, meta interface{}) error {
computeApiVersion := getComputeApiVersion(d, FirewallBaseApiVersion, FirewallVersionedFeatures)
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
}
// Delete the firewall
var op interface{}
switch computeApiVersion {
case v1:
op, err = config.clientCompute.Firewalls.Delete(project, d.Id()).Do()
if err != nil {
return fmt.Errorf("Error deleting firewall: %s", err)
}
case v0beta:
op, err = config.clientComputeBeta.Firewalls.Delete(project, d.Id()).Do()
if err != nil {
return fmt.Errorf("Error deleting firewall: %s", err)
}
}
err = computeSharedOperationWait(config.clientCompute, op, project, "Deleting Firewall")
if err != nil {
return err
}
d.SetId("")
return nil
}
func resourceFirewall(d *schema.ResourceData, meta interface{}, computeApiVersion ComputeApiVersion) (*computeBeta.Firewall, error) {
config := meta.(*Config)
network, err := ParseNetworkFieldValue(d.Get("network").(string), d, config)
if err != nil {
return nil, err
}
// Build up the list of allowed entries
var allowed []*computeBeta.FirewallAllowed
if v := d.Get("allow").(*schema.Set); v.Len() > 0 {
allowed = make([]*computeBeta.FirewallAllowed, 0, v.Len())
for _, v := range v.List() {
m := v.(map[string]interface{})
allowed = append(allowed, &computeBeta.FirewallAllowed{
IPProtocol: m["protocol"].(string),
Ports: convertStringArr(m["ports"].([]interface{})),
})
}
}
// Build up the list of denied entries
var denied []*computeBeta.FirewallDenied
if v := d.Get("deny").(*schema.Set); v.Len() > 0 {
denied = make([]*computeBeta.FirewallDenied, 0, v.Len())
for _, v := range v.List() {
m := v.(map[string]interface{})
denied = append(denied, &computeBeta.FirewallDenied{
IPProtocol: m["protocol"].(string),
Ports: convertStringArr(m["ports"].([]interface{})),
})
}
}
// Build up the list of sources
var sourceRanges, sourceTags []string
if v := d.Get("source_ranges").(*schema.Set); v.Len() > 0 {
sourceRanges = make([]string, v.Len())
for i, v := range v.List() {
sourceRanges[i] = v.(string)
}
}
if v := d.Get("source_tags").(*schema.Set); v.Len() > 0 {
sourceTags = make([]string, v.Len())
for i, v := range v.List() {
sourceTags[i] = v.(string)
}
}
// Build up the list of destinations
var destinationRanges []string
if v := d.Get("destination_ranges").(*schema.Set); v.Len() > 0 {
destinationRanges = make([]string, v.Len())
for i, v := range v.List() {
destinationRanges[i] = v.(string)
}
}
// Build up the list of targets
var targetTags []string
if v := d.Get("target_tags").(*schema.Set); v.Len() > 0 {
targetTags = make([]string, v.Len())
for i, v := range v.List() {
targetTags[i] = v.(string)
}
}
// Build the firewall parameter
return &computeBeta.Firewall{
Name: d.Get("name").(string),
Description: d.Get("description").(string),
Direction: d.Get("direction").(string),
Network: network.RelativeLink(),
Allowed: allowed,
Denied: denied,
SourceRanges: sourceRanges,
SourceTags: sourceTags,
DestinationRanges: destinationRanges,
TargetTags: targetTags,
Priority: int64(d.Get("priority").(int)),
}, nil
}