Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Api Gateway method request validators. #1064

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ func Provider() terraform.ResourceProvider {
"aws_api_gateway_method_response": resourceAwsApiGatewayMethodResponse(),
"aws_api_gateway_method_settings": resourceAwsApiGatewayMethodSettings(),
"aws_api_gateway_model": resourceAwsApiGatewayModel(),
"aws_api_gateway_request_validator": resourceAwsApiGatewayRequestValidator(),
"aws_api_gateway_resource": resourceAwsApiGatewayResource(),
"aws_api_gateway_rest_api": resourceAwsApiGatewayRestApi(),
"aws_api_gateway_stage": resourceAwsApiGatewayStage(),
Expand Down
26 changes: 26 additions & 0 deletions aws/resource_aws_api_gateway_method.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ func resourceAwsApiGatewayMethod() *schema.Resource {
ConflictsWith: []string{"request_parameters"},
Deprecated: "Use field request_parameters instead",
},

"request_validator_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
}
}
Expand Down Expand Up @@ -121,6 +126,10 @@ func resourceAwsApiGatewayMethodCreate(d *schema.ResourceData, meta interface{})
input.AuthorizerId = aws.String(v.(string))
}

if v, ok := d.GetOk("request_validator_id"); ok {
input.RequestValidatorId = aws.String(v.(string))
}

_, err := conn.PutMethod(&input)
if err != nil {
return fmt.Errorf("Error creating API Gateway Method: %s", err)
Expand Down Expand Up @@ -156,6 +165,7 @@ func resourceAwsApiGatewayMethodRead(d *schema.ResourceData, meta interface{}) e
d.Set("authorization_type", out.AuthorizationType)
d.Set("authorizer_id", out.AuthorizerId)
d.Set("request_models", aws.StringValueMap(out.RequestModels))
d.Set("request_validator_id", out.RequestValidatorId)

return nil
}
Expand Down Expand Up @@ -226,6 +236,22 @@ func resourceAwsApiGatewayMethodUpdate(d *schema.ResourceData, meta interface{})
})
}

if d.HasChange("request_validator_id") {
var request_validator_id *string
if v, ok := d.GetOk("request_validator_id"); ok {
// requestValidatorId cannot be an empty string; it must either be nil
// or it must have some value. Otherwise, updating fails.
if s := v.(string); len(s) > 0 {
request_validator_id = &s
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need to compare the old value here with the new one. If the old one is an ID, and the new one is "", then we're deleting a request valuator, and we should issue a remove update here on the method, correct? It doesn't look like we can otherwise remove anything as-is

Copy link
Contributor

@catsby catsby Jul 7, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked this out and tried manually, it seems we're sending nil in the operations below which is effectively doing what we want and removing it, so I guess this is fine 👍

operations = append(operations, &apigateway.PatchOperation{
Op: aws.String("replace"),
Path: aws.String("/requestValidatorId"),
Value: request_validator_id,
})
}

method, err := conn.UpdateMethod(&apigateway.UpdateMethodInput{
HttpMethod: aws.String(d.Get("http_method").(string)),
ResourceId: aws.String(d.Get("resource_id").(string)),
Expand Down
111 changes: 111 additions & 0 deletions aws/resource_aws_api_gateway_method_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,44 @@ func TestAccAWSAPIGatewayMethod_customauthorizer(t *testing.T) {
})
}

func TestAccAWSAPIGatewayMethod_customrequestvalidator(t *testing.T) {
var conf apigateway.Method
rInt := acctest.RandInt()

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSAPIGatewayMethodDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSAPIGatewayMethodConfigWithCustomRequestValidator(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf),
testAccCheckAWSAPIGatewayMethodAttributes(&conf),
resource.TestCheckResourceAttr(
"aws_api_gateway_method.test", "http_method", "GET"),
resource.TestCheckResourceAttr(
"aws_api_gateway_method.test", "authorization", "NONE"),
resource.TestCheckResourceAttr(
"aws_api_gateway_method.test", "request_models.application/json", "Error"),
resource.TestMatchResourceAttr(
"aws_api_gateway_method.test", "request_validator_id", regexp.MustCompile("^[a-z0-9]{6}$")),
),
},

{
Config: testAccAWSAPIGatewayMethodConfigWithCustomRequestValidatorUpdate(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSAPIGatewayMethodExists("aws_api_gateway_method.test", &conf),
testAccCheckAWSAPIGatewayMethodAttributesUpdate(&conf),
resource.TestCheckResourceAttr(
"aws_api_gateway_method.test", "request_validator_id", ""),
),
},
},
})
}

func testAccCheckAWSAPIGatewayMethodAttributes(conf *apigateway.Method) resource.TestCheckFunc {
return func(s *terraform.State) error {
if *conf.HttpMethod != "GET" {
Expand Down Expand Up @@ -357,3 +395,76 @@ resource "aws_api_gateway_method" "test" {
}
`, rInt)
}

func testAccAWSAPIGatewayMethodConfigWithCustomRequestValidator(rInt int) string {
return fmt.Sprintf(`
resource "aws_api_gateway_rest_api" "test" {
name = "tf-acc-test-apig-method-custom-req-validator-%d"
}

resource "aws_api_gateway_resource" "test" {
rest_api_id = "${aws_api_gateway_rest_api.test.id}"
parent_id = "${aws_api_gateway_rest_api.test.root_resource_id}"
path_part = "test"
}

resource "aws_api_gateway_request_validator" "validator" {
rest_api_id = "${aws_api_gateway_rest_api.test.id}"
name = "paramsValidator"
validate_request_parameters = true
}

resource "aws_api_gateway_method" "test" {
rest_api_id = "${aws_api_gateway_rest_api.test.id}"
resource_id = "${aws_api_gateway_resource.test.id}"
http_method = "GET"
authorization = "NONE"

request_models = {
"application/json" = "Error"
}

request_parameters = {
"method.request.header.Content-Type" = false,
"method.request.querystring.page" = true
}

request_validator_id = "${aws_api_gateway_request_validator.validator.id}"
}
`, rInt)
}

func testAccAWSAPIGatewayMethodConfigWithCustomRequestValidatorUpdate(rInt int) string {
return fmt.Sprintf(`
resource "aws_api_gateway_rest_api" "test" {
name = "tf-acc-test-apig-method-custom-req-validator-%d"
}

resource "aws_api_gateway_resource" "test" {
rest_api_id = "${aws_api_gateway_rest_api.test.id}"
parent_id = "${aws_api_gateway_rest_api.test.root_resource_id}"
path_part = "test"
}

resource "aws_api_gateway_request_validator" "validator" {
rest_api_id = "${aws_api_gateway_rest_api.test.id}"
name = "paramsValidator"
validate_request_parameters = true
}

resource "aws_api_gateway_method" "test" {
rest_api_id = "${aws_api_gateway_rest_api.test.id}"
resource_id = "${aws_api_gateway_resource.test.id}"
http_method = "GET"
authorization = "NONE"

request_models = {
"application/json" = "Error"
}

request_parameters = {
"method.request.querystring.page" = false
}
}
`, rInt)
}
154 changes: 154 additions & 0 deletions aws/resource_aws_api_gateway_request_validator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
package aws

import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/apigateway"
"github.com/hashicorp/terraform/helper/schema"
"log"
"strings"
)

func resourceAwsApiGatewayRequestValidator() *schema.Resource {
return &schema.Resource{
Create: resourceAwsApiGatewayRequestValidatorCreate,
Read: resourceAwsApiGatewayRequestValidatorRead,
Update: resourceAwsApiGatewayRequestValidatorUpdate,
Delete: resourceAwsApiGatewayRequestValidatorDelete,

Schema: map[string]*schema.Schema{
"rest_api_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},

"name": {
Type: schema.TypeString,
Required: true,
},

"validate_request_body": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},

"validate_request_parameters": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
},
}
}

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

input := apigateway.CreateRequestValidatorInput{
Name: aws.String(d.Get("name").(string)),
RestApiId: aws.String(d.Get("rest_api_id").(string)),
ValidateRequestBody: aws.Bool(d.Get("validate_request_body").(bool)),
ValidateRequestParameters: aws.Bool(d.Get("validate_request_parameters").(bool)),
}

out, err := conn.CreateRequestValidator(&input)
if err != nil {
return fmt.Errorf("Error creating Request Validator: %s", err)
}

d.SetId(*out.Id)

return nil
}

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

input := apigateway.GetRequestValidatorInput{
RequestValidatorId: aws.String(d.Id()),
RestApiId: aws.String(d.Get("rest_api_id").(string)),
}

out, err := conn.GetRequestValidator(&input)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == apigateway.ErrCodeNotFoundException {
d.SetId("")
return nil
}
return err
}

d.Set("name", out.Name)
d.Set("validate_request_body", out.ValidateRequestBody)
d.Set("validate_request_parameters", out.ValidateRequestParameters)

return nil
}

func resourceAwsApiGatewayRequestValidatorUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).apigateway
log.Printf("[DEBUG] Updating Request Validator %s", d.Id())

operations := make([]*apigateway.PatchOperation, 0)

if d.HasChange("name") {
operations = append(operations, &apigateway.PatchOperation{
Op: aws.String("replace"),
Path: aws.String("/name"),
Value: aws.String(d.Get("name").(string)),
})
}

if d.HasChange("validate_request_body") {
operations = append(operations, &apigateway.PatchOperation{
Op: aws.String("replace"),
Path: aws.String("/validateRequestBody"),
Value: aws.String(fmt.Sprintf("%t", d.Get("validate_request_body").(bool))),
})
}

if d.HasChange("validate_request_parameters") {
operations = append(operations, &apigateway.PatchOperation{
Op: aws.String("replace"),
Path: aws.String("/validateRequestParameters"),
Value: aws.String(fmt.Sprintf("%t", d.Get("validate_request_parameters").(bool))),
})
}

input := apigateway.UpdateRequestValidatorInput{
RequestValidatorId: aws.String(d.Id()),
RestApiId: aws.String(d.Get("rest_api_id").(string)),
PatchOperations: operations,
}

_, err := conn.UpdateRequestValidator(&input)
if err != nil {
return err
}

log.Printf("[DEBUG] Updated Request Validator %s", d.Id())

return resourceAwsApiGatewayRequestValidatorRead(d, meta)
}

func resourceAwsApiGatewayRequestValidatorDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).apigateway
log.Printf("[DEBUG] Deleting Request Validator %s", d.Id())

_, err := conn.DeleteRequestValidator(&apigateway.DeleteRequestValidatorInput{
RequestValidatorId: aws.String(d.Id()),
RestApiId: aws.String(d.Get("rest_api_id").(string)),
})
if err != nil {
// XXX: Figure out a way to delete the method that depends on the request validator first
// otherwise the validator will be dangling until the API is deleted
if !strings.Contains(err.Error(), apigateway.ErrCodeConflictException) {
return fmt.Errorf("Deleting Request Validator failed: %s", err)
}
}

return nil
}
Loading