-
Notifications
You must be signed in to change notification settings - Fork 132
/
block_fastly_service_v1_header.go
256 lines (231 loc) · 6.91 KB
/
block_fastly_service_v1_header.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
package fastly
import (
"fmt"
"log"
"strings"
gofastly "github.com/fastly/go-fastly/fastly"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
type HeaderServiceAttributeHandler struct {
*DefaultServiceAttributeHandler
}
func NewServiceHeader(sa ServiceMetadata) ServiceAttributeDefinition {
return &HeaderServiceAttributeHandler{
&DefaultServiceAttributeHandler{
key: "header",
serviceMetadata: sa,
},
}
}
func (h *HeaderServiceAttributeHandler) Process(d *schema.ResourceData, latestVersion int, conn *gofastly.Client) error {
oh, nh := d.GetChange(h.GetKey())
if oh == nil {
oh = new(schema.Set)
}
if nh == nil {
nh = new(schema.Set)
}
ohs := oh.(*schema.Set)
nhs := nh.(*schema.Set)
remove := ohs.Difference(nhs).List()
add := nhs.Difference(ohs).List()
// Delete removed headers
for _, dRaw := range remove {
df := dRaw.(map[string]interface{})
opts := gofastly.DeleteHeaderInput{
Service: d.Id(),
Version: latestVersion,
Name: df["name"].(string),
}
log.Printf("[DEBUG] Fastly Header removal opts: %#v", opts)
err := conn.DeleteHeader(&opts)
if errRes, ok := err.(*gofastly.HTTPError); ok {
if errRes.StatusCode != 404 {
return err
}
} else if err != nil {
return err
}
}
// POST new Headers
for _, dRaw := range add {
opts, err := buildHeader(dRaw.(map[string]interface{}))
if err != nil {
log.Printf("[DEBUG] Error building Header: %s", err)
return err
}
opts.Service = d.Id()
opts.Version = latestVersion
log.Printf("[DEBUG] Fastly Header Addition opts: %#v", opts)
_, err = conn.CreateHeader(opts)
if err != nil {
return err
}
}
return nil
}
func (h *HeaderServiceAttributeHandler) Read(d *schema.ResourceData, s *gofastly.ServiceDetail, conn *gofastly.Client) error {
log.Printf("[DEBUG] Refreshing Headers for (%s)", d.Id())
headerList, err := conn.ListHeaders(&gofastly.ListHeadersInput{
Service: d.Id(),
Version: s.ActiveVersion.Number,
})
if err != nil {
return fmt.Errorf("[ERR] Error looking up Headers for (%s), version (%v): %s", d.Id(), s.ActiveVersion.Number, err)
}
hl := flattenHeaders(headerList)
if err := d.Set(h.GetKey(), hl); err != nil {
log.Printf("[WARN] Error setting Headers for (%s): %s", d.Id(), err)
}
return nil
}
func (h *HeaderServiceAttributeHandler) Register(s *schema.Resource) error {
s.Schema[h.GetKey()] = &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// required fields
"name": {
Type: schema.TypeString,
Required: true,
Description: "A name to refer to this Header object",
},
"action": {
Type: schema.TypeString,
Required: true,
Description: "One of set, append, delete, regex, or regex_repeat",
ValidateFunc: validateHeaderAction(),
},
"type": {
Type: schema.TypeString,
Required: true,
Description: "Type to manipulate: request, fetch, cache, response",
ValidateFunc: validateHeaderType(),
},
"destination": {
Type: schema.TypeString,
Required: true,
Description: "Header this affects",
},
// Optional fields, defaults where they exist
"ignore_if_set": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Don't add the header if it is already. (Only applies to 'set' action.). Default `false`",
},
"source": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Variable to be used as a source for the header content (Does not apply to 'delete' action.)",
},
"regex": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Regular expression to use (Only applies to 'regex' and 'regex_repeat' actions.)",
},
"substitution": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Value to substitute in place of regular expression. (Only applies to 'regex' and 'regex_repeat'.)",
},
"priority": {
Type: schema.TypeInt,
Optional: true,
Default: 100,
Description: "Lower priorities execute first. (Default: 100.)",
},
"request_condition": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Optional name of a request condition to apply.",
},
"cache_condition": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Optional name of a cache condition to apply.",
},
"response_condition": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Optional name of a response condition to apply.",
},
},
},
}
return nil
}
func flattenHeaders(headerList []*gofastly.Header) []map[string]interface{} {
var hl []map[string]interface{}
for _, h := range headerList {
// Convert Header to a map for saving to state.
nh := map[string]interface{}{
"name": h.Name,
"action": h.Action,
"ignore_if_set": h.IgnoreIfSet,
"type": h.Type,
"destination": h.Destination,
"source": h.Source,
"regex": h.Regex,
"substitution": h.Substitution,
"priority": int(h.Priority),
"request_condition": h.RequestCondition,
"cache_condition": h.CacheCondition,
"response_condition": h.ResponseCondition,
}
for k, v := range nh {
if v == "" {
delete(nh, k)
}
}
hl = append(hl, nh)
}
return hl
}
func buildHeader(headerMap interface{}) (*gofastly.CreateHeaderInput, error) {
df := headerMap.(map[string]interface{})
opts := gofastly.CreateHeaderInput{
Name: df["name"].(string),
IgnoreIfSet: gofastly.CBool(df["ignore_if_set"].(bool)),
Destination: df["destination"].(string),
Priority: uint(df["priority"].(int)),
Source: df["source"].(string),
Regex: df["regex"].(string),
Substitution: df["substitution"].(string),
RequestCondition: df["request_condition"].(string),
CacheCondition: df["cache_condition"].(string),
ResponseCondition: df["response_condition"].(string),
}
act := strings.ToLower(df["action"].(string))
switch act {
case "set":
opts.Action = gofastly.HeaderActionSet
case "append":
opts.Action = gofastly.HeaderActionAppend
case "delete":
opts.Action = gofastly.HeaderActionDelete
case "regex":
opts.Action = gofastly.HeaderActionRegex
case "regex_repeat":
opts.Action = gofastly.HeaderActionRegexRepeat
}
ty := strings.ToLower(df["type"].(string))
switch ty {
case "request":
opts.Type = gofastly.HeaderTypeRequest
case "fetch":
opts.Type = gofastly.HeaderTypeFetch
case "cache":
opts.Type = gofastly.HeaderTypeCache
case "response":
opts.Type = gofastly.HeaderTypeResponse
}
return &opts, nil
}