-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathweb_acl.go
357 lines (307 loc) · 11.3 KB
/
web_acl.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
package wafv2
import (
"context"
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/wafv2"
"github.com/hashicorp/aws-sdk-go-base/v2/awsv1shim/v2/tfawserr"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
)
const (
webACLCreateTimeout = 5 * time.Minute
webACLUpdateTimeout = 5 * time.Minute
webACLDeleteTimeout = 5 * time.Minute
)
func ResourceWebACL() *schema.Resource {
return &schema.Resource{
CreateWithoutTimeout: resourceWebACLCreate,
ReadWithoutTimeout: resourceWebACLRead,
UpdateWithoutTimeout: resourceWebACLUpdate,
DeleteWithoutTimeout: resourceWebACLDelete,
Importer: &schema.ResourceImporter{
State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
idParts := strings.Split(d.Id(), "/")
if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" {
return nil, fmt.Errorf("Unexpected format of ID (%q), expected ID/NAME/SCOPE", d.Id())
}
id := idParts[0]
name := idParts[1]
scope := idParts[2]
d.SetId(id)
d.Set("name", name)
d.Set("scope", scope)
return []*schema.ResourceData{d}, nil
},
},
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"capacity": {
Type: schema.TypeInt,
Computed: true,
},
"custom_response_body": customResponseBodySchema(),
"default_action": {
Type: schema.TypeList,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allow": allowConfigSchema(),
"block": blockConfigSchema(),
},
},
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(1, 256),
},
"lock_token": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.All(
validation.StringLenBetween(1, 128),
validation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9-_]+$`), "must contain only alphanumeric hyphen and underscore characters"),
),
},
"rule": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"action": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allow": allowConfigSchema(),
"block": blockConfigSchema(),
"captcha": captchaConfigSchema(),
"challenge": challengeConfigSchema(),
"count": countConfigSchema(),
},
},
},
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 128),
},
"override_action": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"count": emptySchema(),
"none": emptySchema(),
},
},
},
"priority": {
Type: schema.TypeInt,
Required: true,
},
"rule_label": ruleLabelsSchema(),
"statement": webACLRootStatementSchema(webACLRootStatementSchemaLevel),
"visibility_config": visibilityConfigSchema(),
"captcha_config": outerCaptchaConfigSchema(),
},
},
},
"scope": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice(wafv2.Scope_Values(), false),
},
"tags": tftags.TagsSchema(),
"tags_all": tftags.TagsSchemaComputed(),
"visibility_config": visibilityConfigSchema(),
"captcha_config": outerCaptchaConfigSchema(),
},
CustomizeDiff: verify.SetTagsDiff,
}
}
func resourceWebACLCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).WAFV2Conn()
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{})))
name := d.Get("name").(string)
input := &wafv2.CreateWebACLInput{
DefaultAction: expandDefaultAction(d.Get("default_action").([]interface{})),
Name: aws.String(name),
Rules: expandWebACLRules(d.Get("rule").(*schema.Set).List()),
Scope: aws.String(d.Get("scope").(string)),
VisibilityConfig: expandVisibilityConfig(d.Get("visibility_config").([]interface{})),
CaptchaConfig: expandCaptchaConfig(d.Get("captcha_config").([]interface{})),
}
if v, ok := d.GetOk("custom_response_body"); ok && v.(*schema.Set).Len() > 0 {
input.CustomResponseBodies = expandCustomResponseBodies(v.(*schema.Set).List())
}
if v, ok := d.GetOk("description"); ok {
input.Description = aws.String(v.(string))
}
if len(tags) > 0 {
input.Tags = Tags(tags.IgnoreAWS())
}
log.Printf("[INFO] Creating WAFv2 WebACL: %s", input)
outputRaw, err := tfresource.RetryWhenAWSErrCodeEqualsContext(ctx, webACLCreateTimeout, func() (interface{}, error) {
return conn.CreateWebACLWithContext(ctx, input)
}, wafv2.ErrCodeWAFUnavailableEntityException)
if err != nil {
return diag.Errorf("creating WAFv2 WebACL (%s): %s", name, err)
}
output := outputRaw.(*wafv2.CreateWebACLOutput)
d.SetId(aws.StringValue(output.Summary.Id))
return resourceWebACLRead(ctx, d, meta)
}
func resourceWebACLRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).WAFV2Conn()
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig
output, err := FindWebACLByThreePartKey(ctx, conn, d.Id(), d.Get("name").(string), d.Get("scope").(string))
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] WAFv2 WebACL (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
if err != nil {
return diag.Errorf("reading WAFv2 WebACL (%s): %s", d.Id(), err)
}
webACL := output.WebACL
arn := aws.StringValue(webACL.ARN)
d.Set("arn", arn)
d.Set("capacity", webACL.Capacity)
if err := d.Set("custom_response_body", flattenCustomResponseBodies(webACL.CustomResponseBodies)); err != nil {
return diag.Errorf("setting custom_response_body: %s", err)
}
if err := d.Set("default_action", flattenDefaultAction(webACL.DefaultAction)); err != nil {
return diag.Errorf("setting default_action: %s", err)
}
d.Set("description", webACL.Description)
d.Set("lock_token", output.LockToken)
d.Set("name", webACL.Name)
if err := d.Set("rule", flattenWebACLRules(webACL.Rules)); err != nil {
return diag.Errorf("setting rule: %s", err)
}
if err := d.Set("visibility_config", flattenVisibilityConfig(webACL.VisibilityConfig)); err != nil {
return diag.Errorf("setting visibility_config: %s", err)
}
if err := d.Set("captcha_config", flattenCaptchaConfig(webACL.CaptchaConfig)); err != nil {
return diag.Errorf("setting captcha_config: %s", err)
}
tags, err := ListTagsWithContext(ctx, conn, arn)
if err != nil {
return diag.Errorf("listing tags for WAFv2 WebACL (%s): %s", arn, err)
}
tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig)
//lintignore:AWSR002
if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil {
return diag.Errorf("setting tags: %s", err)
}
if err := d.Set("tags_all", tags.Map()); err != nil {
return diag.Errorf("setting tags_all: %s", err)
}
return nil
}
func resourceWebACLUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).WAFV2Conn()
if d.HasChangesExcept("tags", "tags_all") {
input := &wafv2.UpdateWebACLInput{
DefaultAction: expandDefaultAction(d.Get("default_action").([]interface{})),
Id: aws.String(d.Id()),
LockToken: aws.String(d.Get("lock_token").(string)),
Name: aws.String(d.Get("name").(string)),
Rules: expandWebACLRules(d.Get("rule").(*schema.Set).List()),
Scope: aws.String(d.Get("scope").(string)),
VisibilityConfig: expandVisibilityConfig(d.Get("visibility_config").([]interface{})),
CaptchaConfig: expandCaptchaConfig(d.Get("captcha_config").([]interface{})),
}
if v, ok := d.GetOk("custom_response_body"); ok && v.(*schema.Set).Len() > 0 {
input.CustomResponseBodies = expandCustomResponseBodies(v.(*schema.Set).List())
}
if v, ok := d.GetOk("description"); ok {
input.Description = aws.String(v.(string))
}
log.Printf("[INFO] Updating WAFv2 WebACL: %s", input)
_, err := tfresource.RetryWhenAWSErrCodeEqualsContext(ctx, webACLUpdateTimeout, func() (interface{}, error) {
return conn.UpdateWebACLWithContext(ctx, input)
}, wafv2.ErrCodeWAFUnavailableEntityException)
if tfawserr.ErrCodeEquals(err, wafv2.ErrCodeWAFOptimisticLockException) {
return diag.Errorf("updating WAFv2 WebACL (%s), resource has changed since last refresh please run a new plan before applying again: %s", d.Id(), err)
}
if err != nil {
return diag.Errorf("updating WAFv2 WebACL (%s): %s", d.Id(), err)
}
}
if d.HasChange("tags_all") {
o, n := d.GetChange("tags_all")
arn := d.Get("arn").(string)
if err := UpdateTagsWithContext(ctx, conn, arn, o, n); err != nil {
return diag.Errorf("updating tags for WAFv2 WebACL (%s): %s", arn, err)
}
}
return resourceWebACLRead(ctx, d, meta)
}
func resourceWebACLDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).WAFV2Conn()
input := &wafv2.DeleteWebACLInput{
Id: aws.String(d.Id()),
LockToken: aws.String(d.Get("lock_token").(string)),
Name: aws.String(d.Get("name").(string)),
Scope: aws.String(d.Get("scope").(string)),
}
log.Printf("[INFO] Deleting WAFv2 WebACL: %s", d.Id())
_, err := tfresource.RetryWhenAWSErrCodeEqualsContext(ctx, webACLDeleteTimeout, func() (interface{}, error) {
return conn.DeleteWebACLWithContext(ctx, input)
}, wafv2.ErrCodeWAFAssociatedItemException, wafv2.ErrCodeWAFUnavailableEntityException)
if tfawserr.ErrCodeEquals(err, wafv2.ErrCodeWAFNonexistentItemException) {
return nil
}
if err != nil {
return diag.Errorf("deleting WAFv2 WebACL (%s): %s", d.Id(), err)
}
return nil
}
func FindWebACLByThreePartKey(ctx context.Context, conn *wafv2.WAFV2, id, name, scope string) (*wafv2.GetWebACLOutput, error) {
input := &wafv2.GetWebACLInput{
Id: aws.String(id),
Name: aws.String(name),
Scope: aws.String(scope),
}
output, err := conn.GetWebACLWithContext(ctx, input)
if tfawserr.ErrCodeEquals(err, wafv2.ErrCodeWAFNonexistentItemException) {
return nil, &resource.NotFoundError{
LastError: err,
LastRequest: input,
}
}
if err != nil {
return nil, err
}
if output == nil || output.WebACL == nil {
return nil, tfresource.NewEmptyResultError(input)
}
return output, nil
}