Added AWS Resource WAF ByteMatchSet (#9681)

This commit is contained in:
Anshul Sharma 2016-10-28 18:06:16 +05:30 committed by Paul Stack
parent d64e645b8e
commit afc603c0f8
5 changed files with 505 additions and 0 deletions

View File

@ -354,6 +354,7 @@ func Provider() terraform.ResourceProvider {
"aws_vpn_connection_route": resourceAwsVpnConnectionRoute(),
"aws_vpn_gateway": resourceAwsVpnGateway(),
"aws_vpn_gateway_attachment": resourceAwsVpnGatewayAttachment(),
"aws_waf_byte_match_set": resourceAwsWafByteMatchSet(),
"aws_waf_web_acl": resourceAwsWafWebAcl(),
"aws_waf_rule": resourceAwsWafRule(),
"aws_waf_ipset": resourceAwsWafIPSet(),

View File

@ -0,0 +1,205 @@
package aws
import (
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/waf"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceAwsWafByteMatchSet() *schema.Resource {
return &schema.Resource{
Create: resourceAwsWafByteMatchSetCreate,
Read: resourceAwsWafByteMatchSetRead,
Update: resourceAwsWafByteMatchSetUpdate,
Delete: resourceAwsWafByteMatchSetDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"byte_match_tuples": &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,
},
},
},
},
"positional_constraint": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"target_string": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"text_transformation": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
},
},
},
}
}
func resourceAwsWafByteMatchSetCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).wafconn
log.Printf("[INFO] Creating ByteMatchSet: %s", d.Get("name").(string))
// ChangeToken
var ct *waf.GetChangeTokenInput
res, err := conn.GetChangeToken(ct)
if err != nil {
return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err)
}
params := &waf.CreateByteMatchSetInput{
ChangeToken: res.ChangeToken,
Name: aws.String(d.Get("name").(string)),
}
resp, err := conn.CreateByteMatchSet(params)
if err != nil {
return errwrap.Wrapf("[ERROR] Error creating ByteMatchSet: {{err}}", err)
}
d.SetId(*resp.ByteMatchSet.ByteMatchSetId)
return resourceAwsWafByteMatchSetUpdate(d, meta)
}
func resourceAwsWafByteMatchSetRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).wafconn
log.Printf("[INFO] Reading ByteMatchSet: %s", d.Get("name").(string))
params := &waf.GetByteMatchSetInput{
ByteMatchSetId: aws.String(d.Id()),
}
resp, err := conn.GetByteMatchSet(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "WAFNonexistentItemException" {
log.Printf("[WARN] WAF IPSet (%s) not found, error code (404)", d.Id())
d.SetId("")
return nil
}
return err
}
d.Set("name", resp.ByteMatchSet.Name)
return nil
}
func resourceAwsWafByteMatchSetUpdate(d *schema.ResourceData, meta interface{}) error {
log.Printf("[INFO] Updating ByteMatchSet: %s", d.Get("name").(string))
err := updateByteMatchSetResource(d, meta, waf.ChangeActionInsert)
if err != nil {
return errwrap.Wrapf("[ERROR] Error updating ByteMatchSet: {{err}}", err)
}
return resourceAwsWafByteMatchSetRead(d, meta)
}
func resourceAwsWafByteMatchSetDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).wafconn
log.Printf("[INFO] Deleting ByteMatchSet: %s", d.Get("name").(string))
err := updateByteMatchSetResource(d, meta, waf.ChangeActionDelete)
if err != nil {
return errwrap.Wrapf("[ERROR] Error deleting ByteMatchSet: {{err}}", err)
}
var ct *waf.GetChangeTokenInput
resp, err := conn.GetChangeToken(ct)
req := &waf.DeleteByteMatchSetInput{
ChangeToken: resp.ChangeToken,
ByteMatchSetId: aws.String(d.Id()),
}
_, err = conn.DeleteByteMatchSet(req)
if err != nil {
return errwrap.Wrapf("[ERROR] Error deleting ByteMatchSet: {{err}}", err)
}
return nil
}
func updateByteMatchSetResource(d *schema.ResourceData, meta interface{}, ChangeAction string) error {
conn := meta.(*AWSClient).wafconn
var ct *waf.GetChangeTokenInput
resp, err := conn.GetChangeToken(ct)
if err != nil {
return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err)
}
req := &waf.UpdateByteMatchSetInput{
ChangeToken: resp.ChangeToken,
ByteMatchSetId: aws.String(d.Id()),
}
ByteMatchTuples := d.Get("byte_match_tuples").(*schema.Set)
for _, ByteMatchTuple := range ByteMatchTuples.List() {
ByteMatch := ByteMatchTuple.(map[string]interface{})
ByteMatchUpdate := &waf.ByteMatchSetUpdate{
Action: aws.String(ChangeAction),
ByteMatchTuple: &waf.ByteMatchTuple{
FieldToMatch: expandFieldToMatch(ByteMatch["field_to_match"].(*schema.Set).List()[0].(map[string]interface{})),
PositionalConstraint: aws.String(ByteMatch["positional_constraint"].(string)),
TargetString: []byte(ByteMatch["target_string"].(string)),
TextTransformation: aws.String(ByteMatch["text_transformation"].(string)),
},
}
req.Updates = append(req.Updates, ByteMatchUpdate)
}
_, err = conn.UpdateByteMatchSet(req)
if err != nil {
return errwrap.Wrapf("[ERROR] Error updating ByteMatchSet: {{err}}", err)
}
return nil
}
func expandFieldToMatch(d map[string]interface{}) *waf.FieldToMatch {
return &waf.FieldToMatch{
Type: aws.String(d["type"].(string)),
Data: aws.String(d["data"].(string)),
}
}
func flattenFieldToMatch(fm *waf.FieldToMatch) map[string]interface{} {
m := make(map[string]interface{})
m["data"] = *fm.Data
m["type"] = *fm.Type
return m
}

View File

@ -0,0 +1,256 @@
package aws
import (
"fmt"
"testing"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/waf"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/acctest"
)
func TestAccAWSWafByteMatchSet_basic(t *testing.T) {
var v waf.ByteMatchSet
byteMatchSet := fmt.Sprintf("byteMatchSet-%s", acctest.RandString(5))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSWafByteMatchSetDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSWafByteMatchSetConfig(byteMatchSet),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSWafByteMatchSetExists("aws_waf_byte_match_set.byte_set", &v),
resource.TestCheckResourceAttr(
"aws_waf_byte_match_set.byte_set", "name", byteMatchSet),
resource.TestCheckResourceAttr(
"aws_waf_byte_match_set.byte_set", "byte_match_tuples.#", "2"),
),
},
},
})
}
func TestAccAWSWafByteMatchSet_changeNameForceNew(t *testing.T) {
var before, after waf.ByteMatchSet
byteMatchSet := fmt.Sprintf("byteMatchSet-%s", acctest.RandString(5))
byteMatchSetNewName := fmt.Sprintf("byteMatchSet-%s", acctest.RandString(5))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSWafByteMatchSetDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSWafByteMatchSetConfig(byteMatchSet),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSWafByteMatchSetExists("aws_waf_byte_match_set.byte_set", &before),
resource.TestCheckResourceAttr(
"aws_waf_byte_match_set.byte_set", "name", byteMatchSet),
resource.TestCheckResourceAttr(
"aws_waf_byte_match_set.byte_set", "byte_match_tuples.#", "2"),
),
},
{
Config: testAccAWSWafByteMatchSetConfigChangeName(byteMatchSetNewName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSWafByteMatchSetExists("aws_waf_byte_match_set.byte_set", &after),
resource.TestCheckResourceAttr(
"aws_waf_byte_match_set.byte_set", "name", byteMatchSetNewName),
resource.TestCheckResourceAttr(
"aws_waf_byte_match_set.byte_set", "byte_match_tuples.#", "2"),
),
},
},
})
}
func TestAccAWSWafByteMatchSet_disappears(t *testing.T) {
var v waf.ByteMatchSet
byteMatchSet := fmt.Sprintf("byteMatchSet-%s", acctest.RandString(5))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSWafByteMatchSetDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSWafByteMatchSetConfig(byteMatchSet),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSWafByteMatchSetExists("aws_waf_byte_match_set.byte_set", &v),
testAccCheckAWSWafByteMatchSetDisappears(&v),
),
ExpectNonEmptyPlan: true,
},
},
})
}
func testAccCheckAWSWafByteMatchSetDisappears(v *waf.ByteMatchSet) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).wafconn
// ChangeToken
var ct *waf.GetChangeTokenInput
resp, err := conn.GetChangeToken(ct)
if err != nil {
return fmt.Errorf("Error getting change token: %s", err)
}
req := &waf.UpdateByteMatchSetInput{
ChangeToken: resp.ChangeToken,
ByteMatchSetId: v.ByteMatchSetId,
}
for _, ByteMatchTuple := range v.ByteMatchTuples {
ByteMatchUpdate := &waf.ByteMatchSetUpdate{
Action: aws.String("DELETE"),
ByteMatchTuple: &waf.ByteMatchTuple{
FieldToMatch: ByteMatchTuple.FieldToMatch,
PositionalConstraint: ByteMatchTuple.PositionalConstraint,
TargetString: ByteMatchTuple.TargetString,
TextTransformation: ByteMatchTuple.TextTransformation,
},
}
req.Updates = append(req.Updates, ByteMatchUpdate)
}
_, err = conn.UpdateByteMatchSet(req)
if err != nil {
return errwrap.Wrapf("[ERROR] Error updating ByteMatchSet: {{err}}", err)
}
resp, err = conn.GetChangeToken(ct)
if err != nil {
return errwrap.Wrapf("[ERROR] Error getting change token: {{err}}", err)
}
opts := &waf.DeleteByteMatchSetInput{
ChangeToken: resp.ChangeToken,
ByteMatchSetId: v.ByteMatchSetId,
}
if _, err := conn.DeleteByteMatchSet(opts); err != nil {
return err
}
return nil
}
}
func testAccCheckAWSWafByteMatchSetExists(n string, v *waf.ByteMatchSet) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No WAF ByteMatchSet ID is set")
}
conn := testAccProvider.Meta().(*AWSClient).wafconn
resp, err := conn.GetByteMatchSet(&waf.GetByteMatchSetInput{
ByteMatchSetId: aws.String(rs.Primary.ID),
})
if err != nil {
return err
}
if *resp.ByteMatchSet.ByteMatchSetId == rs.Primary.ID {
*v = *resp.ByteMatchSet
return nil
}
return fmt.Errorf("WAF ByteMatchSet (%s) not found", rs.Primary.ID)
}
}
func testAccCheckAWSWafByteMatchSetDestroy(s *terraform.State) error {
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_waf_byte_match_set" {
continue
}
conn := testAccProvider.Meta().(*AWSClient).wafconn
resp, err := conn.GetByteMatchSet(
&waf.GetByteMatchSetInput{
ByteMatchSetId: aws.String(rs.Primary.ID),
})
if err == nil {
if *resp.ByteMatchSet.ByteMatchSetId == rs.Primary.ID {
return fmt.Errorf("WAF ByteMatchSet %s still exists", rs.Primary.ID)
}
}
// Return nil if the ByteMatchSet is already destroyed
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == "WAFNonexistentItemException" {
return nil
}
}
return err
}
return nil
}
func testAccAWSWafByteMatchSetConfig(name string) string {
return fmt.Sprintf(`
resource "aws_waf_byte_match_set" "byte_set" {
name = "%s"
byte_match_tuples {
text_transformation = "NONE"
target_string = "badrefer1"
positional_constraint = "CONTAINS"
field_to_match {
type = "HEADER"
data = "referer"
}
}
byte_match_tuples {
text_transformation = "NONE"
target_string = "badrefer2"
positional_constraint = "CONTAINS"
field_to_match {
type = "HEADER"
data = "referer"
}
}
}`, name)
}
func testAccAWSWafByteMatchSetConfigChangeName(name string) string {
return fmt.Sprintf(`
resource "aws_waf_byte_match_set" "byte_set" {
name = "%s"
byte_match_tuples {
text_transformation = "NONE"
target_string = "badrefer1"
positional_constraint = "CONTAINS"
field_to_match {
type = "HEADER"
data = "referer"
}
}
byte_match_tuples {
text_transformation = "NONE"
target_string = "badrefer2"
positional_constraint = "CONTAINS"
field_to_match {
type = "HEADER"
data = "referer"
}
}
}`, name)
}

View File

@ -0,0 +1,39 @@
---
layout: "aws"
page_title: "AWS: waf_byte_match_set"
sidebar_current: "docs-aws-resource-waf-bytematchset"
description: |-
Provides a AWS WAF ByteMatchSet resource.
---
## Example Usage
```
resource "aws_waf_byte_match_set" "byte_set" {
name = "tf_waf_byte_match_set"
byte_match_tuples {
text_transformation = "NONE"
target_string = "badrefer1"
positional_constraint = "CONTAINS"
field_to_match {
type = "HEADER"
data = "referer"
}
}
}
```
## Argument Reference
The following arguments are supported:
* `name` - (Required) The name or description of the ByteMatchSet.
* `byte_match_tuples` - Settings for the ByteMatchSet, such as the bytes (typically a string that corresponds with ASCII characters) that you want AWS WAF to search for in web requests.
## Remarks
## Attributes Reference
The following attributes are exported:
* `id` - The ID of the WAF ByteMatchSet.

View File

@ -803,6 +803,10 @@
<li<%= sidebar_current("docs-aws-resource-waf-webacl") %>>
<a href="/docs/providers/aws/r/waf_web_acl.html">aws_waf_web_acl</a>
</li>
<li<%= sidebar_current("docs-aws-resource-waf-bytematchset") %>>
<a href="/docs/providers/aws/r/waf_waf_byte_match_set.html">aws_waf_byte_match_set</a>
</li>
<li<%= sidebar_current("docs-aws-resource-waf-rule") %>>
<a href="/docs/providers/aws/r/aws_waf_rule.html">aws_waf_rule</a>