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 new data source aws_api_gateway_rest_api #4172

Merged
merged 3 commits into from
Apr 12, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
88 changes: 88 additions & 0 deletions aws/data_source_aws_api_gateway_rest_api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package aws

import (
"fmt"
"log"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/apigateway"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/schema"
)

func dataSourceAwsApiGatewayRestApi() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsApiGatewayRestApiRead,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"id": {
Copy link
Contributor

Choose a reason for hiding this comment

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

id does not need to be declared as a schema attribute 👍

Type: schema.TypeString,
Computed: true,
},
"root_resource_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func dataSourceAwsApiGatewayRestApiRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).apigateway
params := &apigateway.GetRestApisInput{}

target := d.Get("name")
var matchedApis []*apigateway.RestApi
log.Printf("[DEBUG] Reading API Gateway REST APIs: %s", params)
err := conn.GetRestApisPages(params, func(page *apigateway.GetRestApisOutput, lastPage bool) bool {
for _, api := range page.Items {
if *api.Name == target {
Copy link
Contributor

Choose a reason for hiding this comment

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

To prevent a potential crash, we should wrap this with aws.StringValue(api.Name) in the unlikely scenario that its returned as nil

matchedApis = append(matchedApis, api)
}
}
return true
Copy link
Contributor

Choose a reason for hiding this comment

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

Should use return !lastPage here

})
if err != nil {
return errwrap.Wrapf("error describing API Gateway REST APIs: {{err}}", err)
Copy link
Contributor

Choose a reason for hiding this comment

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

We do not need the context of the error when returning a message back to the user here. We can use the simpler fmt.Errorf("error describing API Gateway REST APIs: %s", err) here 👍

}

if len(matchedApis) == 0 {
return fmt.Errorf("no REST APIs with name %q found in this region", target)
}
if len(matchedApis) > 1 {
return fmt.Errorf("multiple REST APIs with name %q found in this region", target)
}

match := matchedApis[0]

d.SetId(*match.Id)

if err = dataSourceAwsApiGatewayRestApiRefreshResources(d, meta); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

We do not need the extra function here, its contents can be included in the read function 👍

return err
}

return nil
}

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

resp, err := conn.GetResources(&apigateway.GetResourcesInput{
RestApiId: aws.String(d.Id()),
})
if err != nil {
return err
}

for _, item := range resp.Items {
if *item.Path == "/" {
d.Set("root_resource_id", item.Id)
break
}
}

return nil
}
80 changes: 80 additions & 0 deletions aws/data_source_aws_api_gateway_rest_api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package aws

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccDataSourceAwsApiGatewayRestApi(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccDataSourceAwsApiGatewayRestApiConfig,
Check: resource.ComposeTestCheckFunc(
testAccDataSourceAwsApiGatewayRestApiCheck("data.aws_api_gateway_rest_api.by_name"),
),
},
},
})
}

func testAccDataSourceAwsApiGatewayRestApiCheck(name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
resources, ok := s.RootModule().Resources[name]
if !ok {
return fmt.Errorf("root module has no resource called %s", name)
}

apiGatewayRestApiResources, ok := s.RootModule().Resources["aws_api_gateway_rest_api.tf_test"]
if !ok {
return fmt.Errorf("can't find aws_api_gateway_rest_api.tf_test in state")
}

attr := resources.Primary.Attributes

if attr["name"] != apiGatewayRestApiResources.Primary.Attributes["name"] {
return fmt.Errorf(
"name is %s; want %s",
attr["name"],
apiGatewayRestApiResources.Primary.Attributes["name"],
)
}

if attr["root_resource_id"] != apiGatewayRestApiResources.Primary.Attributes["root_resource_id"] {
return fmt.Errorf(
"root_resource_id is %s; want %s",
attr["root_resource_id"],
apiGatewayRestApiResources.Primary.Attributes["root_resource_id"],
)
}

return nil
}
}

const testAccDataSourceAwsApiGatewayRestApiConfig = `
provider "aws" {
Copy link
Contributor

Choose a reason for hiding this comment

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

We do not need to declare the provider block in the testing framework, it defaults to us-west-2 if not provided via AWS_DEFAULT_REGION

region = "us-west-2"
}

resource "aws_api_gateway_rest_api" "tf_wrong1" {
name = "wrong1"
}

resource "aws_api_gateway_rest_api" "tf_test" {
name = "tf_test"
Copy link
Contributor

Choose a reason for hiding this comment

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

These should have randomized names to prevent hitting the multiple match error condition after test panics/AWS failures. Usually we achieve this by wrapping the test configuration in fmt.Sprintf() and passing a randomized name from the test function, e.g. rName := acctest.StringWithPrefix("tf_acc_test_")

}

resource "aws_api_gateway_rest_api" "tf_wrong2" {
name = "wrong2"
}

data "aws_api_gateway_rest_api" "by_name" {
name = "${aws_api_gateway_rest_api.tf_test.name}"
}
`
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ func Provider() terraform.ResourceProvider {
"aws_acm_certificate": dataSourceAwsAcmCertificate(),
"aws_ami": dataSourceAwsAmi(),
"aws_ami_ids": dataSourceAwsAmiIds(),
"aws_api_gateway_rest_api": dataSourceAwsApiGatewayRestApi(),
"aws_autoscaling_groups": dataSourceAwsAutoscalingGroups(),
"aws_availability_zone": dataSourceAwsAvailabilityZone(),
"aws_availability_zones": dataSourceAwsAvailabilityZones(),
Expand Down
3 changes: 3 additions & 0 deletions website/aws.erb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
<li<%= sidebar_current("docs-aws-datasource-ami-ids") %>>
<a href="/docs/providers/aws/d/ami_ids.html">aws_ami_ids</a>
</li>
<li<%= sidebar_current("docs-aws_api_gateway_rest_api") %>>
<a href="/docs/providers/aws/d/api_gateway_rest_api.html">aws_api_gateway_rest_api</a>
</li>
<li<%= sidebar_current("docs-aws-datasource-autoscaling-groups") %>>
<a href="/docs/providers/aws/d/autoscaling_groups.html">aws_autoscaling_groups</a>
</li>
Expand Down
32 changes: 32 additions & 0 deletions website/docs/d/api_gateway_rest_api.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
layout: "aws"
page_title: "AWS: aws_api_gateway_rest_api"
sidebar_current: "docs-aws_api_gateway_rest_api"
description: |-
Get information on a API Gateway REST API
---

# Data Source: aws_api_gateway_rest_api

Use this data source to get the id and root_resource_id of a REST API in
API Gateway. To fetch the REST API you must provide a name to match against.
As there is no unique name constraint on REST APIs this data source will
error if there is more than one match.

## Example Usage

```hcl
data "aws_api_gateway_rest_api" "my_rest_api" {
name = "my-rest-api"
}
```

## Argument Reference

* `name` - (Required) The name of the REST API to look up. If no REST API is found with this name, an error will be returned.
If multiple REST APIs are found with this name, an error will be returned.

## Attributes Reference

* `id` - Set to the ID of the found REST API.
* `root_resource_id` - Set to the ID of the API Gateway Resource on the found REST API where the route matches '/'.