-
Notifications
You must be signed in to change notification settings - Fork 132
/
block_fastly_service_v1_backend.go
466 lines (431 loc) · 15.1 KB
/
block_fastly_service_v1_backend.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
package fastly
import (
"fmt"
"log"
"strings"
gofastly "github.com/fastly/go-fastly/v3/fastly"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
type BackendServiceAttributeHandler struct {
*DefaultServiceAttributeHandler
}
func NewServiceBackend(sa ServiceMetadata) ServiceAttributeDefinition {
return &BackendServiceAttributeHandler{
&DefaultServiceAttributeHandler{
key: "backend",
serviceMetadata: sa,
},
}
}
func (h *BackendServiceAttributeHandler) Process(d *schema.ResourceData, latestVersion int, conn *gofastly.Client) error {
ob, nb := d.GetChange(h.GetKey())
if ob == nil {
ob = new(schema.Set)
}
if nb == nil {
nb = new(schema.Set)
}
oldSet := ob.(*schema.Set)
newSet := nb.(*schema.Set)
setDiff := NewSetDiff(func(resource interface{}) (interface{}, error) {
t, ok := resource.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("resource failed to be type asserted: %+v", resource)
}
return t["name"], nil
})
diffResult, err := setDiff.Diff(oldSet, newSet)
if err != nil {
return err
}
// DELETE removed resources
for _, resource := range diffResult.Deleted {
resource := resource.(map[string]interface{})
opts := h.createDeleteBackendInput(d.Id(), latestVersion, resource)
log.Printf("[DEBUG] Fastly Backend removal opts: %#v", opts)
err := conn.DeleteBackend(&opts)
if errRes, ok := err.(*gofastly.HTTPError); ok {
if errRes.StatusCode != 404 {
return err
}
} else if err != nil {
return err
}
}
// CREATE new resources
for _, resource := range diffResult.Added {
resource := resource.(map[string]interface{})
opts := h.buildCreateBackendInput(d.Id(), latestVersion, resource)
log.Printf("[DEBUG] Create Backend Opts: %#v", opts)
_, err := conn.CreateBackend(&opts)
if err != nil {
return err
}
}
// UPDATE modified resources
//
// NOTE: although the go-fastly API client enables updating of a resource by
// its 'name' attribute, this isn't possible within terraform due to
// constraints in the data model/schema of the resources not having a uid.
for _, resource := range diffResult.Modified {
resource := resource.(map[string]interface{})
// only attempt to update attributes that have changed
modified := setDiff.Filter(resource, oldSet)
opts := h.buildUpdateBackendInput(d.Id(), latestVersion, resource, modified)
log.Printf("[DEBUG] Update Backend Opts: %#v", opts)
_, err := conn.UpdateBackend(&opts)
if err != nil {
return err
}
}
return nil
}
func (h *BackendServiceAttributeHandler) createDeleteBackendInput(service string, latestVersion int, bf map[string]interface{}) gofastly.DeleteBackendInput {
return gofastly.DeleteBackendInput{
ServiceID: service,
ServiceVersion: latestVersion,
Name: bf["name"].(string),
}
}
func (h *BackendServiceAttributeHandler) buildCreateBackendInput(service string, latestVersion int, df map[string]interface{}) gofastly.CreateBackendInput {
opts := gofastly.CreateBackendInput{
ServiceID: service,
ServiceVersion: latestVersion,
Name: df["name"].(string),
Address: df["address"].(string),
OverrideHost: df["override_host"].(string),
AutoLoadbalance: gofastly.Compatibool(df["auto_loadbalance"].(bool)),
SSLCheckCert: gofastly.Compatibool(df["ssl_check_cert"].(bool)),
SSLHostname: df["ssl_hostname"].(string),
SSLCACert: df["ssl_ca_cert"].(string),
SSLCertHostname: df["ssl_cert_hostname"].(string),
SSLSNIHostname: df["ssl_sni_hostname"].(string),
UseSSL: gofastly.Compatibool(df["use_ssl"].(bool)),
SSLClientKey: df["ssl_client_key"].(string),
SSLClientCert: df["ssl_client_cert"].(string),
MaxTLSVersion: df["max_tls_version"].(string),
MinTLSVersion: df["min_tls_version"].(string),
SSLCiphers: strings.Split(df["ssl_ciphers"].(string), ","),
Shield: df["shield"].(string),
Port: uint(df["port"].(int)),
BetweenBytesTimeout: uint(df["between_bytes_timeout"].(int)),
ConnectTimeout: uint(df["connect_timeout"].(int)),
ErrorThreshold: uint(df["error_threshold"].(int)),
FirstByteTimeout: uint(df["first_byte_timeout"].(int)),
MaxConn: uint(df["max_conn"].(int)),
Weight: uint(df["weight"].(int)),
HealthCheck: df["healthcheck"].(string),
}
if h.GetServiceMetadata().serviceType == ServiceTypeVCL {
opts.RequestCondition = df["request_condition"].(string)
}
return opts
}
func (h *BackendServiceAttributeHandler) buildUpdateBackendInput(serviceID string, latestVersion int, resource, modified map[string]interface{}) gofastly.UpdateBackendInput {
opts := gofastly.UpdateBackendInput{
ServiceID: serviceID,
ServiceVersion: latestVersion,
Name: resource["name"].(string),
}
// NOTE: where we transition between interface{} we lose the ability to
// infer the underlying type being either a uint vs an int. This
// materializes as a panic (yay) and so it's only at runtime we discover
// this and so we've updated the below code to convert the type asserted
// int into a uint before passing the value to gofastly.Uint().
if v, ok := modified["comment"]; ok {
opts.Comment = gofastly.String(v.(string))
}
if v, ok := modified["address"]; ok {
opts.Address = gofastly.String(v.(string))
}
if v, ok := modified["port"]; ok {
opts.Port = gofastly.Uint(uint(v.(int)))
}
if v, ok := modified["override_host"]; ok {
opts.OverrideHost = gofastly.String(v.(string))
}
if v, ok := modified["connect_timeout"]; ok {
opts.ConnectTimeout = gofastly.Uint(uint(v.(int)))
}
if v, ok := modified["max_conn"]; ok {
opts.MaxConn = gofastly.Uint(uint(v.(int)))
}
if v, ok := modified["error_threshold"]; ok {
opts.ErrorThreshold = gofastly.Uint(uint(v.(int)))
}
if v, ok := modified["first_byte_timeout"]; ok {
opts.FirstByteTimeout = gofastly.Uint(uint(v.(int)))
}
if v, ok := modified["between_bytes_timeout"]; ok {
opts.BetweenBytesTimeout = gofastly.Uint(uint(v.(int)))
}
if v, ok := modified["auto_loadbalance"]; ok {
opts.AutoLoadbalance = gofastly.CBool(v.(bool))
}
if v, ok := modified["weight"]; ok {
opts.Weight = gofastly.Uint(uint(v.(int)))
}
if v, ok := modified["request_condition"]; ok {
if h.GetServiceMetadata().serviceType == ServiceTypeVCL {
opts.RequestCondition = gofastly.String(v.(string))
}
}
if v, ok := modified["healthcheck"]; ok {
opts.HealthCheck = gofastly.String(v.(string))
}
if v, ok := modified["shield"]; ok {
opts.Shield = gofastly.String(v.(string))
}
if v, ok := modified["use_ssl"]; ok {
opts.UseSSL = gofastly.CBool(v.(bool))
}
if v, ok := modified["ssl_check_cert"]; ok {
opts.SSLCheckCert = gofastly.CBool(v.(bool))
}
if v, ok := modified["ssl_ca_cert"]; ok {
opts.SSLCACert = gofastly.String(v.(string))
}
if v, ok := modified["ssl_client_cert"]; ok {
opts.SSLClientCert = gofastly.String(v.(string))
}
if v, ok := modified["ssl_client_key"]; ok {
opts.SSLClientKey = gofastly.String(v.(string))
}
if v, ok := modified["ssl_hostname"]; ok {
opts.SSLHostname = gofastly.String(v.(string))
}
if v, ok := modified["ssl_cert_hostname"]; ok {
opts.SSLCertHostname = gofastly.String(v.(string))
}
if v, ok := modified["ssl_sni_hostname"]; ok {
opts.SSLSNIHostname = gofastly.String(v.(string))
}
if v, ok := modified["min_tls_version"]; ok {
opts.MinTLSVersion = gofastly.String(v.(string))
}
if v, ok := modified["max_tls_version"]; ok {
opts.MaxTLSVersion = gofastly.String(v.(string))
}
if v, ok := modified["ssl_ciphers"]; ok {
opts.SSLCiphers = strings.Split(v.(string), ",")
}
return opts
}
func (h *BackendServiceAttributeHandler) Read(d *schema.ResourceData, s *gofastly.ServiceDetail, conn *gofastly.Client) error {
log.Printf("[DEBUG] Refreshing Backends for (%s)", d.Id())
backendList, err := conn.ListBackends(&gofastly.ListBackendsInput{
ServiceID: d.Id(),
ServiceVersion: s.ActiveVersion.Number,
})
if err != nil {
return fmt.Errorf("[ERR] Error looking up Backends for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err)
}
bl := flattenBackend(backendList, h.GetServiceMetadata())
if err := d.Set(h.GetKey(), bl); err != nil {
log.Printf("[WARN] Error setting Backends for (%s): %s", d.Id(), err)
}
return nil
}
func (h *BackendServiceAttributeHandler) Register(s *schema.Resource) error {
var blockAttributes = map[string]*schema.Schema{
// required fields
"name": {
Type: schema.TypeString,
Required: true,
Description: "Name for this Backend. Must be unique to this Service. It is important to note that changing this attribute will delete and recreate the resource",
},
"address": {
Type: schema.TypeString,
Required: true,
Description: "An IPv4, hostname, or IPv6 address for the Backend",
},
// Optional fields, defaults where they exist
"auto_loadbalance": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Denotes if this Backend should be included in the pool of backends that requests are load balanced against. Default `true`",
},
"between_bytes_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 10000,
Description: "How long to wait between bytes in milliseconds. Default `10000`",
},
"connect_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 1000,
Description: "How long to wait for a timeout in milliseconds. Default `1000`",
},
"error_threshold": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
Description: "Number of errors to allow before the Backend is marked as down. Default `0`",
},
"first_byte_timeout": {
Type: schema.TypeInt,
Optional: true,
Default: 15000,
Description: "How long to wait for the first bytes in milliseconds. Default `15000`",
},
"healthcheck": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Name of a defined `healthcheck` to assign to this backend",
},
"max_conn": {
Type: schema.TypeInt,
Optional: true,
Default: 200,
Description: "Maximum number of connections for this Backend. Default `200`",
},
"port": {
Type: schema.TypeInt,
Optional: true,
Default: 80,
Description: "The port number on which the Backend responds. Default `80`",
},
"override_host": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "The hostname to override the Host header",
},
"shield": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "The POP of the shield designated to reduce inbound load. Valid values for `shield` are included in the `GET /datacenters` API response",
},
"use_ssl": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether or not to use SSL to reach the Backend. Default `false`",
},
"max_tls_version": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Maximum allowed TLS version on SSL connections to this backend.",
},
"min_tls_version": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Minimum allowed TLS version on SSL connections to this backend.",
},
"ssl_ciphers": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Comma separated list of OpenSSL Ciphers to try when negotiating to the backend",
},
"ssl_check_cert": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Be strict about checking SSL certs. Default `true`",
},
"ssl_hostname": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Used for both SNI during the TLS handshake and to validate the cert",
Deprecated: "Use ssl_cert_hostname and ssl_sni_hostname instead.",
},
"ssl_ca_cert": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "CA certificate attached to origin.",
},
"ssl_cert_hostname": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Overrides ssl_hostname, but only for cert verification. Does not affect SNI at all",
},
"ssl_sni_hostname": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Overrides ssl_hostname, but only for SNI in the handshake. Does not affect cert validation at all",
},
"ssl_client_cert": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Client certificate attached to origin. Used when connecting to the backend",
Sensitive: true,
},
"ssl_client_key": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Client key attached to origin. Used when connecting to the backend",
Sensitive: true,
},
"weight": {
Type: schema.TypeInt,
Optional: true,
Default: 100,
Description: "The [portion of traffic](https://docs.fastly.com/en/guides/load-balancing-configuration#how-weight-affects-load-balancing) to send to this Backend. Each Backend receives weight / total of the traffic. Default `100`",
},
}
if h.GetServiceMetadata().serviceType == ServiceTypeVCL {
blockAttributes["request_condition"] = &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Name of a condition, which if met, will select this backend during a request.",
}
}
s.Schema[h.GetKey()] = &schema.Schema{
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: blockAttributes,
},
}
return nil
}
func flattenBackend(backendList []*gofastly.Backend, sa ServiceMetadata) []map[string]interface{} {
bl := make([]map[string]interface{}, 0, len(backendList))
for _, b := range backendList {
backend := map[string]interface{}{
"name": b.Name,
"address": b.Address,
"auto_loadbalance": b.AutoLoadbalance,
"between_bytes_timeout": int(b.BetweenBytesTimeout),
"connect_timeout": int(b.ConnectTimeout),
"error_threshold": int(b.ErrorThreshold),
"first_byte_timeout": int(b.FirstByteTimeout),
"max_conn": int(b.MaxConn),
"port": int(b.Port),
"override_host": b.OverrideHost,
"shield": b.Shield,
"ssl_check_cert": b.SSLCheckCert,
"ssl_hostname": b.SSLHostname,
"ssl_ca_cert": b.SSLCACert,
"ssl_client_key": b.SSLClientKey,
"ssl_client_cert": b.SSLClientCert,
"max_tls_version": b.MaxTLSVersion,
"min_tls_version": b.MinTLSVersion,
"ssl_ciphers": strings.Join(b.SSLCiphers, ","),
"use_ssl": b.UseSSL,
"ssl_cert_hostname": b.SSLCertHostname,
"ssl_sni_hostname": b.SSLSNIHostname,
"weight": int(b.Weight),
"healthcheck": b.HealthCheck,
}
if sa.serviceType == ServiceTypeVCL {
backend["request_condition"] = b.RequestCondition
}
bl = append(bl, backend)
}
return bl
}