-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathrule_group.go
323 lines (274 loc) · 10.2 KB
/
rule_group.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
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 (
ruleGroupCreateTimeout = 5 * time.Minute
ruleGroupUpdateTimeout = 5 * time.Minute
ruleGroupDeleteTimeout = 5 * time.Minute
)
func ResourceRuleGroup() *schema.Resource {
return &schema.Resource{
CreateWithoutTimeout: resourceRuleGroupCreate,
ReadWithoutTimeout: resourceRuleGroupRead,
UpdateWithoutTimeout: resourceRuleGroupUpdate,
DeleteWithoutTimeout: resourceRuleGroupDelete,
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,
Required: true,
ForceNew: true,
ValidateFunc: validation.IntAtLeast(1),
},
"custom_response_body": customResponseBodySchema(),
"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,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allow": allowConfigSchema(),
"block": blockConfigSchema(),
"count": countConfigSchema(),
"captcha": captchaConfigSchema(),
},
},
},
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 128),
},
"priority": {
Type: schema.TypeInt,
Required: true,
},
"rule_label": ruleLabelsSchema(),
"statement": ruleGroupRootStatementSchema(ruleGroupRootStatementSchemaLevel),
"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 resourceRuleGroupCreate(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.CreateRuleGroupInput{
Capacity: aws.Int64(int64(d.Get("capacity").(int))),
Name: aws.String(name),
Rules: expandRules(d.Get("rule").(*schema.Set).List()),
Scope: aws.String(d.Get("scope").(string)),
VisibilityConfig: expandVisibilityConfig(d.Get("visibility_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 RuleGroup: %s", input)
outputRaw, err := tfresource.RetryWhenAWSErrCodeEqualsContext(ctx, ruleGroupCreateTimeout, func() (interface{}, error) {
return conn.CreateRuleGroupWithContext(ctx, input)
}, wafv2.ErrCodeWAFUnavailableEntityException)
if err != nil {
return diag.Errorf("creating WAFv2 RuleGroup (%s): %s", name, err)
}
output := outputRaw.(*wafv2.CreateRuleGroupOutput)
d.SetId(aws.StringValue(output.Summary.Id))
return resourceRuleGroupRead(ctx, d, meta)
}
func resourceRuleGroupRead(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 := FindRuleGroupByThreePartKey(ctx, conn, d.Id(), d.Get("name").(string), d.Get("scope").(string))
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] WAFv2 RuleGroup (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
if err != nil {
return diag.Errorf("reading WAFv2 RuleGroup (%s): %s", d.Id(), err)
}
ruleGroup := output.RuleGroup
arn := aws.StringValue(ruleGroup.ARN)
d.Set("arn", ruleGroup.ARN)
d.Set("capacity", ruleGroup.Capacity)
if err := d.Set("custom_response_body", flattenCustomResponseBodies(ruleGroup.CustomResponseBodies)); err != nil {
return diag.Errorf("setting custom_response_body: %s", err)
}
d.Set("description", ruleGroup.Description)
d.Set("lock_token", output.LockToken)
d.Set("name", ruleGroup.Name)
if err := d.Set("rule", flattenRules(ruleGroup.Rules)); err != nil {
return diag.Errorf("setting rule: %s", err)
}
if err := d.Set("visibility_config", flattenVisibilityConfig(ruleGroup.VisibilityConfig)); err != nil {
return diag.Errorf("setting visibility_config: %s", err)
}
tags, err := ListTagsWithContext(ctx, conn, arn)
if err != nil {
return diag.Errorf("listing tags for WAFv2 RuleGroup (%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 resourceRuleGroupUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).WAFV2Conn()
if d.HasChangesExcept("tags", "tags_all") {
input := &wafv2.UpdateRuleGroupInput{
Id: aws.String(d.Id()),
LockToken: aws.String(d.Get("lock_token").(string)),
Name: aws.String(d.Get("name").(string)),
Rules: expandRules(d.Get("rule").(*schema.Set).List()),
Scope: aws.String(d.Get("scope").(string)),
VisibilityConfig: expandVisibilityConfig(d.Get("visibility_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 RuleGroup: %s", input)
_, err := tfresource.RetryWhenAWSErrCodeEqualsContext(ctx, ruleGroupUpdateTimeout, func() (interface{}, error) {
return conn.UpdateRuleGroupWithContext(ctx, input)
}, wafv2.ErrCodeWAFUnavailableEntityException)
if err != nil {
return diag.Errorf("updating WAFv2 RuleGroup (%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 RuleGroup (%s): %s", arn, err)
}
}
return resourceRuleGroupRead(ctx, d, meta)
}
func resourceRuleGroupDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*conns.AWSClient).WAFV2Conn()
input := &wafv2.DeleteRuleGroupInput{
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 RuleGroup: %s", d.Id())
_, err := tfresource.RetryWhenAWSErrCodeEqualsContext(ctx, ruleGroupDeleteTimeout, func() (interface{}, error) {
return conn.DeleteRuleGroupWithContext(ctx, input)
}, wafv2.ErrCodeWAFAssociatedItemException, wafv2.ErrCodeWAFUnavailableEntityException)
if tfawserr.ErrCodeEquals(err, wafv2.ErrCodeWAFNonexistentItemException) {
return nil
}
if err != nil {
return diag.Errorf("deleting WAFv2 RuleGroup (%s): %s", d.Id(), err)
}
return nil
}
func FindRuleGroupByThreePartKey(ctx context.Context, conn *wafv2.WAFV2, id, name, scope string) (*wafv2.GetRuleGroupOutput, error) {
input := &wafv2.GetRuleGroupInput{
Id: aws.String(id),
Name: aws.String(name),
Scope: aws.String(scope),
}
output, err := conn.GetRuleGroupWithContext(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.RuleGroup == nil {
return nil, tfresource.NewEmptyResultError(input)
}
return output, nil
}