-
Notifications
You must be signed in to change notification settings - Fork 140
/
block_fastly_service_requestsetting.go
308 lines (282 loc) · 10 KB
/
block_fastly_service_requestsetting.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
package fastly
import (
"context"
"fmt"
"log"
"strings"
gofastly "github.com/fastly/go-fastly/v6/fastly"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
// RequestSettingServiceAttributeHandler provides a base implementation for ServiceAttributeDefinition.
type RequestSettingServiceAttributeHandler struct {
*DefaultServiceAttributeHandler
}
// NewServiceRequestSetting returns a new resource.
func NewServiceRequestSetting(sa ServiceMetadata) ServiceAttributeDefinition {
return ToServiceAttributeDefinition(&RequestSettingServiceAttributeHandler{
&DefaultServiceAttributeHandler{
key: "request_setting",
serviceMetadata: sa,
},
})
}
// Key returns the resource key.
func (h *RequestSettingServiceAttributeHandler) Key() string {
return h.key
}
// GetSchema returns the resource schema.
func (h *RequestSettingServiceAttributeHandler) GetSchema() *schema.Schema {
return &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"action": {
Type: schema.TypeString,
Optional: true,
Description: "Allows you to terminate request handling and immediately perform an action. When set it can be `lookup` or `pass` (Ignore the cache completely)",
},
"bypass_busy_wait": {
Type: schema.TypeBool,
Optional: true,
Description: "Disable collapsed forwarding, so you don't wait for other objects to origin",
},
"default_host": {
Type: schema.TypeString,
Optional: true,
Description: "Sets the host header",
},
"force_miss": {
Type: schema.TypeBool,
Optional: true,
Description: "Force a cache miss for the request. If specified, can be `true` or `false`",
},
"force_ssl": {
Type: schema.TypeBool,
Optional: true,
Description: "Forces the request to use SSL (Redirects a non-SSL request to SSL)",
},
// TODO: Although Fastly API has been exposing this parameter over years
// it turned out that setting this parameter does nothing. We should remove this attribute in v3.0.0
"geo_headers": {
Type: schema.TypeBool,
Optional: true,
Deprecated: "'geo_headers' attribute has been deprecated and will be removed in the next major version release",
Description: "Injects Fastly-Geo-Country, Fastly-Geo-City, and Fastly-Geo-Region into the request headers",
},
"hash_keys": {
Type: schema.TypeString,
Optional: true,
Description: "Comma separated list of varnish request object fields that should be in the hash key",
},
"max_stale_age": {
Type: schema.TypeInt,
Optional: true,
Description: "How old an object is allowed to be to serve `stale-if-error` or `stale-while-revalidate`, in seconds",
},
"name": {
Type: schema.TypeString,
Required: true,
Description: "Unique name to refer to this Request Setting. It is important to note that changing this attribute will delete and recreate the resource",
},
"request_condition": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Name of already defined `condition` to determine if this request setting should be applied",
},
"timer_support": {
Type: schema.TypeBool,
Optional: true,
Description: "Injects the X-Timer info into the request for viewing origin fetch durations",
},
"xff": {
Type: schema.TypeString,
Optional: true,
Default: "append",
Description: "X-Forwarded-For, should be `clear`, `leave`, `append`, `append_all`, or `overwrite`. Default `append`",
},
},
},
}
}
// Create creates the resource.
func (h *RequestSettingServiceAttributeHandler) Create(_ context.Context, d *schema.ResourceData, resource map[string]any, serviceVersion int, conn *gofastly.Client) error {
opts, err := buildRequestSetting(resource)
if err != nil {
log.Printf("[DEBUG] Error building Request Setting: %s", err)
return err
}
opts.ServiceID = d.Id()
opts.ServiceVersion = serviceVersion
log.Printf("[DEBUG] Create Request Setting Opts: %#v", opts)
_, err = conn.CreateRequestSetting(opts)
if err != nil {
return err
}
return nil
}
// Read refreshes the resource.
func (h *RequestSettingServiceAttributeHandler) Read(_ context.Context, d *schema.ResourceData, _ map[string]any, serviceVersion int, conn *gofastly.Client) error {
resources := d.Get(h.GetKey()).(*schema.Set).List()
if len(resources) > 0 || d.Get("imported").(bool) {
log.Printf("[DEBUG] Refreshing Request Settings for (%s)", d.Id())
rsList, err := conn.ListRequestSettings(&gofastly.ListRequestSettingsInput{
ServiceID: d.Id(),
ServiceVersion: serviceVersion,
})
if err != nil {
return fmt.Errorf("error looking up Request Settings for (%s), version (%v): %s", d.Id(), serviceVersion, err)
}
rl := flattenRequestSettings(rsList)
if err := d.Set(h.GetKey(), rl); err != nil {
log.Printf("[WARN] Error setting Request Settings for (%s): %s", d.Id(), err)
}
}
return nil
}
// Update updates the resource.
func (h *RequestSettingServiceAttributeHandler) Update(_ context.Context, d *schema.ResourceData, resource, modified map[string]any, serviceVersion int, conn *gofastly.Client) error {
opts := gofastly.UpdateRequestSettingInput{
ServiceID: d.Id(),
ServiceVersion: serviceVersion,
Name: resource["name"].(string),
}
if v, ok := modified["force_miss"]; ok {
opts.ForceMiss = gofastly.CBool(v.(bool))
}
if v, ok := modified["force_ssl"]; ok {
opts.ForceSSL = gofastly.CBool(v.(bool))
}
if v, ok := modified["action"]; ok {
switch strings.ToLower(v.(string)) {
case "lookup":
opts.Action = gofastly.RequestSettingActionLookup
case "pass":
opts.Action = gofastly.RequestSettingActionPass
}
}
if v, ok := modified["bypass_busy_wait"]; ok {
opts.BypassBusyWait = gofastly.CBool(v.(bool))
}
if v, ok := modified["max_stale_age"]; ok {
opts.MaxStaleAge = gofastly.Uint(uint(v.(int)))
}
if v, ok := modified["hash_keys"]; ok {
opts.HashKeys = gofastly.String(v.(string))
}
if v, ok := modified["xff"]; ok {
switch strings.ToLower(v.(string)) {
case "clear":
opts.XForwardedFor = gofastly.RequestSettingXFFClear
case "leave":
opts.XForwardedFor = gofastly.RequestSettingXFFLeave
case "append":
opts.XForwardedFor = gofastly.RequestSettingXFFAppend
case "append_all":
opts.XForwardedFor = gofastly.RequestSettingXFFAppendAll
case "overwrite":
opts.XForwardedFor = gofastly.RequestSettingXFFOverwrite
}
}
if v, ok := modified["timer_support"]; ok {
opts.TimerSupport = gofastly.CBool(v.(bool))
}
if v, ok := modified["geo_headers"]; ok {
opts.GeoHeaders = gofastly.CBool(v.(bool))
}
if v, ok := modified["default_host"]; ok {
opts.DefaultHost = gofastly.String(v.(string))
}
if v, ok := modified["request_condition"]; ok {
opts.RequestCondition = gofastly.String(v.(string))
}
log.Printf("[DEBUG] Update Request Settings Opts: %#v", opts)
_, err := conn.UpdateRequestSetting(&opts)
if err != nil {
return err
}
return nil
}
// Delete deletes the resource.
func (h *RequestSettingServiceAttributeHandler) Delete(_ context.Context, d *schema.ResourceData, resource map[string]any, serviceVersion int, conn *gofastly.Client) error {
opts := gofastly.DeleteRequestSettingInput{
ServiceID: d.Id(),
ServiceVersion: serviceVersion,
Name: resource["name"].(string),
}
log.Printf("[DEBUG] Fastly Request Setting removal opts: %#v", opts)
err := conn.DeleteRequestSetting(&opts)
if errRes, ok := err.(*gofastly.HTTPError); ok {
if errRes.StatusCode != 404 {
return err
}
} else if err != nil {
return err
}
return nil
}
func flattenRequestSettings(rsList []*gofastly.RequestSetting) []map[string]any {
var rl []map[string]any
for _, r := range rsList {
// Convert Request Settings to a map for saving to state.
nrs := map[string]any{
"name": r.Name,
"max_stale_age": r.MaxStaleAge,
"force_miss": r.ForceMiss,
"force_ssl": r.ForceSSL,
"action": r.Action,
"bypass_busy_wait": r.BypassBusyWait,
"hash_keys": r.HashKeys,
"xff": r.XForwardedFor,
"timer_support": r.TimerSupport,
"geo_headers": r.GeoHeaders,
"default_host": r.DefaultHost,
"request_condition": r.RequestCondition,
}
// prune any empty values that come from the default string value in structs
for k, v := range nrs {
if v == "" {
delete(nrs, k)
}
}
rl = append(rl, nrs)
}
return rl
}
func buildRequestSetting(requestSettingMap any) (*gofastly.CreateRequestSettingInput, error) {
resource := requestSettingMap.(map[string]any)
opts := gofastly.CreateRequestSettingInput{
Name: resource["name"].(string),
MaxStaleAge: gofastly.Uint(uint(resource["max_stale_age"].(int))),
ForceMiss: gofastly.Compatibool(resource["force_miss"].(bool)),
ForceSSL: gofastly.Compatibool(resource["force_ssl"].(bool)),
BypassBusyWait: gofastly.Compatibool(resource["bypass_busy_wait"].(bool)),
HashKeys: resource["hash_keys"].(string),
TimerSupport: gofastly.Compatibool(resource["timer_support"].(bool)),
GeoHeaders: gofastly.Compatibool(resource["geo_headers"].(bool)),
DefaultHost: resource["default_host"].(string),
RequestCondition: resource["request_condition"].(string),
}
act := strings.ToLower(resource["action"].(string))
switch act {
case "lookup":
opts.Action = gofastly.RequestSettingActionLookup
case "pass":
opts.Action = gofastly.RequestSettingActionPass
}
xff := strings.ToLower(resource["xff"].(string))
switch xff {
case "clear":
opts.XForwardedFor = gofastly.RequestSettingXFFClear
case "leave":
opts.XForwardedFor = gofastly.RequestSettingXFFLeave
case "append":
opts.XForwardedFor = gofastly.RequestSettingXFFAppend
case "append_all":
opts.XForwardedFor = gofastly.RequestSettingXFFAppendAll
case "overwrite":
opts.XForwardedFor = gofastly.RequestSettingXFFOverwrite
}
return &opts, nil
}