Skip to content

Commit

Permalink
Merge pull request #3796 from appilon/resource_wafregional_size_const…
Browse files Browse the repository at this point in the history
…raint_set

resource/aws_wafregional_size_constraint_set
  • Loading branch information
appilon authored Mar 22, 2018
2 parents 61fe3b2 + c215252 commit 618b1b1
Show file tree
Hide file tree
Showing 9 changed files with 666 additions and 105 deletions.
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,7 @@ func Provider() terraform.ResourceProvider {
"aws_waf_geo_match_set": resourceAwsWafGeoMatchSet(),
"aws_wafregional_byte_match_set": resourceAwsWafRegionalByteMatchSet(),
"aws_wafregional_ipset": resourceAwsWafRegionalIPSet(),
"aws_wafregional_size_constraint_set": resourceAwsWafRegionalSizeConstraintSet(),
"aws_wafregional_sql_injection_match_set": resourceAwsWafRegionalSqlInjectionMatchSet(),
"aws_wafregional_xss_match_set": resourceAwsWafRegionalXssMatchSet(),
"aws_wafregional_rule": resourceAwsWafRegionalRule(),
Expand Down
104 changes: 4 additions & 100 deletions aws/resource_aws_waf_size_constraint_set.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,50 +17,7 @@ func resourceAwsWafSizeConstraintSet() *schema.Resource {
Update: resourceAwsWafSizeConstraintSetUpdate,
Delete: resourceAwsWafSizeConstraintSetDelete,

Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"size_constraints": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"field_to_match": {
Type: schema.TypeSet,
Required: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"data": {
Type: schema.TypeString,
Optional: true,
},
"type": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"comparison_operator": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"size": &schema.Schema{
Type: schema.TypeInt,
Required: true,
},
"text_transformation": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
},
},
},
Schema: wafSizeConstraintSetSchema(),
}
}

Expand Down Expand Up @@ -98,7 +55,7 @@ func resourceAwsWafSizeConstraintSetRead(d *schema.ResourceData, meta interface{
resp, err := conn.GetSizeConstraintSet(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "WAFNonexistentItemException" {
log.Printf("[WARN] WAF IPSet (%s) not found, removing from state", d.Id())
log.Printf("[WARN] WAF SizeConstraintSet (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
Expand All @@ -117,9 +74,9 @@ func resourceAwsWafSizeConstraintSetUpdate(d *schema.ResourceData, meta interfac

if d.HasChange("size_constraints") {
o, n := d.GetChange("size_constraints")
oldS, newS := o.(*schema.Set).List(), n.(*schema.Set).List()
oldConstraints, newConstraints := o.(*schema.Set).List(), n.(*schema.Set).List()

err := updateSizeConstraintSetResource(d.Id(), oldS, newS, conn)
err := updateSizeConstraintSetResource(d.Id(), oldConstraints, newConstraints, conn)
if err != nil {
return errwrap.Wrapf("[ERROR] Error updating SizeConstraintSet: {{err}}", err)
}
Expand Down Expand Up @@ -174,56 +131,3 @@ func updateSizeConstraintSetResource(id string, oldS, newS []interface{}, conn *

return nil
}

func flattenWafSizeConstraints(sc []*waf.SizeConstraint) []interface{} {
out := make([]interface{}, len(sc), len(sc))
for i, c := range sc {
m := make(map[string]interface{})
m["comparison_operator"] = *c.ComparisonOperator
if c.FieldToMatch != nil {
m["field_to_match"] = flattenFieldToMatch(c.FieldToMatch)
}
m["size"] = *c.Size
m["text_transformation"] = *c.TextTransformation
out[i] = m
}
return out
}

func diffWafSizeConstraints(oldS, newS []interface{}) []*waf.SizeConstraintSetUpdate {
updates := make([]*waf.SizeConstraintSetUpdate, 0)

for _, os := range oldS {
constraint := os.(map[string]interface{})

if idx, contains := sliceContainsMap(newS, constraint); contains {
newS = append(newS[:idx], newS[idx+1:]...)
continue
}

updates = append(updates, &waf.SizeConstraintSetUpdate{
Action: aws.String(waf.ChangeActionDelete),
SizeConstraint: &waf.SizeConstraint{
FieldToMatch: expandFieldToMatch(constraint["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})),
ComparisonOperator: aws.String(constraint["comparison_operator"].(string)),
Size: aws.Int64(int64(constraint["size"].(int))),
TextTransformation: aws.String(constraint["text_transformation"].(string)),
},
})
}

for _, ns := range newS {
constraint := ns.(map[string]interface{})

updates = append(updates, &waf.SizeConstraintSetUpdate{
Action: aws.String(waf.ChangeActionInsert),
SizeConstraint: &waf.SizeConstraint{
FieldToMatch: expandFieldToMatch(constraint["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})),
ComparisonOperator: aws.String(constraint["comparison_operator"].(string)),
Size: aws.Int64(int64(constraint["size"].(int))),
TextTransformation: aws.String(constraint["text_transformation"].(string)),
},
})
}
return updates
}
6 changes: 3 additions & 3 deletions aws/resource_aws_waf_size_constraint_set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ func TestAccAWSWafSizeConstraintSet_changeConstraints(t *testing.T) {
}

func TestAccAWSWafSizeConstraintSet_noConstraints(t *testing.T) {
var ipset waf.SizeConstraintSet
var contraints waf.SizeConstraintSet
setName := fmt.Sprintf("sizeConstraintSet-%s", acctest.RandString(5))

resource.Test(t, resource.TestCase{
Expand All @@ -173,7 +173,7 @@ func TestAccAWSWafSizeConstraintSet_noConstraints(t *testing.T) {
{
Config: testAccAWSWafSizeConstraintSetConfig_noConstraints(setName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckAWSWafSizeConstraintSetExists("aws_waf_size_constraint_set.size_constraint_set", &ipset),
testAccCheckAWSWafSizeConstraintSetExists("aws_waf_size_constraint_set.size_constraint_set", &contraints),
resource.TestCheckResourceAttr(
"aws_waf_size_constraint_set.size_constraint_set", "name", setName),
resource.TestCheckResourceAttr(
Expand Down Expand Up @@ -258,7 +258,7 @@ func testAccCheckAWSWafSizeConstraintSetExists(n string, v *waf.SizeConstraintSe

func testAccCheckAWSWafSizeConstraintSetDestroy(s *terraform.State) error {
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_waf_byte_match_set" {
if rs.Type != "aws_waf_size_contraint_set" {
continue
}

Expand Down
135 changes: 135 additions & 0 deletions aws/resource_aws_wafregional_size_constraint_set.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package aws

import (
"fmt"
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/waf"
"github.com/aws/aws-sdk-go/service/wafregional"
"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsWafRegionalSizeConstraintSet() *schema.Resource {
return &schema.Resource{
Create: resourceAwsWafRegionalSizeConstraintSetCreate,
Read: resourceAwsWafRegionalSizeConstraintSetRead,
Update: resourceAwsWafRegionalSizeConstraintSetUpdate,
Delete: resourceAwsWafRegionalSizeConstraintSetDelete,

Schema: wafSizeConstraintSetSchema(),
}
}

func resourceAwsWafRegionalSizeConstraintSetCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).wafregionalconn
region := meta.(*AWSClient).region

name := d.Get("name").(string)

log.Printf("[INFO] Creating WAF Regional SizeConstraintSet: %s", name)

wr := newWafRegionalRetryer(conn, region)
out, err := wr.RetryWithToken(func(token *string) (interface{}, error) {
params := &waf.CreateSizeConstraintSetInput{
ChangeToken: token,
Name: aws.String(name),
}

return conn.CreateSizeConstraintSet(params)
})
if err != nil {
return fmt.Errorf("[ERROR] Error creating WAF Regional SizeConstraintSet: %s", err)
}
resp := out.(*waf.CreateSizeConstraintSetOutput)

d.SetId(*resp.SizeConstraintSet.SizeConstraintSetId)

return resourceAwsWafRegionalSizeConstraintSetUpdate(d, meta)
}

func resourceAwsWafRegionalSizeConstraintSetRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).wafregionalconn

log.Printf("[INFO] Reading WAF Regional SizeConstraintSet: %s", d.Get("name").(string))
params := &waf.GetSizeConstraintSetInput{
SizeConstraintSetId: aws.String(d.Id()),
}

resp, err := conn.GetSizeConstraintSet(params)
if err != nil {
if isAWSErr(err, wafregional.ErrCodeWAFNonexistentItemException, "") {
log.Printf("[WARN] WAF Regional SizeConstraintSet (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
return err
}

d.Set("name", resp.SizeConstraintSet.Name)
d.Set("size_constraints", flattenWafSizeConstraints(resp.SizeConstraintSet.SizeConstraints))

return nil
}

func resourceAwsWafRegionalSizeConstraintSetUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*AWSClient)

if d.HasChange("size_constraints") {
o, n := d.GetChange("size_constraints")
oldConstraints, newConstraints := o.(*schema.Set).List(), n.(*schema.Set).List()

if err := updateRegionalSizeConstraintSetResource(d.Id(), oldConstraints, newConstraints, client.wafregionalconn, client.region); err != nil {
return fmt.Errorf("[ERROR] Error updating WAF Regional SizeConstraintSet: %s", err)
}
}

return resourceAwsWafRegionalSizeConstraintSetRead(d, meta)
}

func resourceAwsWafRegionalSizeConstraintSetDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).wafregionalconn
region := meta.(*AWSClient).region

oldConstraints := d.Get("size_constraints").(*schema.Set).List()

if len(oldConstraints) > 0 {
noConstraints := []interface{}{}
if err := updateRegionalSizeConstraintSetResource(d.Id(), oldConstraints, noConstraints, conn, region); err != nil {
return fmt.Errorf("[ERROR] Error deleting WAF Regional SizeConstraintSet: %s", err)
}
}

wr := newWafRegionalRetryer(conn, region)
_, err := wr.RetryWithToken(func(token *string) (interface{}, error) {
req := &waf.DeleteSizeConstraintSetInput{
ChangeToken: token,
SizeConstraintSetId: aws.String(d.Id()),
}
return conn.DeleteSizeConstraintSet(req)
})
if err != nil {
return fmt.Errorf("[ERROR] Error deleting WAF Regional SizeConstraintSet: %s", err)
}

return nil
}

func updateRegionalSizeConstraintSetResource(id string, oldConstraints, newConstraints []interface{}, conn *wafregional.WAFRegional, region string) error {
wr := newWafRegionalRetryer(conn, region)
_, err := wr.RetryWithToken(func(token *string) (interface{}, error) {
req := &waf.UpdateSizeConstraintSetInput{
ChangeToken: token,
SizeConstraintSetId: aws.String(id),
Updates: diffWafSizeConstraints(oldConstraints, newConstraints),
}

log.Printf("[INFO] Updating WAF Regional SizeConstraintSet: %s", req)
return conn.UpdateSizeConstraintSet(req)
})
if err != nil {
return fmt.Errorf("[ERROR] Error updating WAF Regional SizeConstraintSet: %s", err)
}

return nil
}
Loading

0 comments on commit 618b1b1

Please sign in to comment.