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

Implement data aws_pricing_product #5057

Merged
merged 5 commits into from
Jul 4, 2018
Merged
Show file tree
Hide file tree
Changes from 4 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
102 changes: 102 additions & 0 deletions aws/data_source_aws_pricing_product.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package aws

import (
"log"
Copy link
Contributor

Choose a reason for hiding this comment

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

Minor nitpick: The Go imports seem to be a little off formatting wise. The stdlib imports should be grouped and alphabetically sorted at the top, a blank line, then external imports grouped and alphabetically sorted.

We tend to prefer using goimports for managing these consistently (and automatically) everywhere 👍


"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/pricing"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/schema"
)

const (
awsPricingTermMatch = "TERM_MATCH"
Copy link
Contributor

Choose a reason for hiding this comment

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

We should prefer to use the available SDK constant: pricing.FilterTypeTermMatch

)

func dataSourceAwsPricingProduct() *schema.Resource {
return &schema.Resource{
Read: dataSourceAwsPricingProductRead,
Schema: map[string]*schema.Schema{
"service_code": {
Type: schema.TypeString,
Required: true,
},
"filters": {
Type: schema.TypeList,
Required: true,
MinItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"field": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
},
},
},
"result": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

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

params := &pricing.GetProductsInput{
ServiceCode: aws.String(d.Get("service_code").(string)),
Filters: []*pricing.Filter{},
}

filters := d.Get("filters")
for _, v := range filters.([]interface{}) {
m := v.(map[string]interface{})
params.Filters = append(params.Filters, &pricing.Filter{
Field: aws.String(m["field"].(string)),
Value: aws.String(m["value"].(string)),
Type: aws.String(awsPricingTermMatch),
})
}

log.Printf("[DEBUG] Reading pricing of products: %s", params)
resp, err := conn.GetProducts(params)
if err != nil {
return fmt.Errorf("Error reading pricing of products: %s", err)
}

if err = verifyProductsPriceListLength(resp.PriceList); 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.

Minor nitpick: given this function is not being used elsewhere and not explicitly unit tested, we can remove the indirection and just include the logic inline here.

return err
}

pricingResult, err := json.Marshal(resp.PriceList[0])
if err != nil {
return fmt.Errorf("Invalid JSON value returned by AWS: %s", err)
}

d.SetId(fmt.Sprintf("%d", hashcode.String(params.String())))
d.Set("result", string(pricingResult))
return nil
}

func verifyProductsPriceListLength(priceList []aws.JSONValue) error {
numberOfElements := len(priceList)
if numberOfElements == 0 {
return fmt.Errorf("Pricing product query did not return any elements")
} else if numberOfElements > 1 {
priceListBytes, err := json.Marshal(priceList)
priceListString := string(priceListBytes)
if err != nil {
priceListString = err.Error()
}
return fmt.Errorf("Pricing product query not precise enough. Returned more than one element: %s", priceListString)
}
return nil
}
120 changes: 120 additions & 0 deletions aws/data_source_aws_pricing_product_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package aws

import (
"encoding/json"
"fmt"
"os"
"testing"

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

func TestAccDataSourceAwsPricingProduct_ec2(t *testing.T) {
os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
Copy link
Contributor

Choose a reason for hiding this comment

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

We should save the original value and reset it after completion or this could break other tests:

	oldRegion := os.Getenv("AWS_DEFAULT_REGION")
	os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
	defer os.Setenv("AWS_DEFAULT_REGION", oldRegion)

The same should be applied to the other acceptance test. Admittedly, we need to remove using environment variables for this purpose. 🙁

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceAwsPricingProductConfigEc2("test", "c5.large"),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet("data.aws_pricing_product.test", "result"),
testAccPricingCheckValueIsJSON("data.aws_pricing_product.test"),
),
},
},
})
}

func TestAccDataSourceAwsPricingProduct_redshift(t *testing.T) {
os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceAwsPricingProductConfigRedshift(),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet("data.aws_pricing_product.test", "result"),
testAccPricingCheckValueIsJSON("data.aws_pricing_product.test"),
),
},
},
})
}

func testAccDataSourceAwsPricingProductConfigEc2(dataName string, instanceType string) string {
return fmt.Sprintf(`data "aws_pricing_product" "%s" {
service_code = "AmazonEC2"

filters = [
{
field = "instanceType"
value = "%s"
},
{
field = "operatingSystem"
value = "Linux"
},
{
field = "location"
value = "US East (N. Virginia)"
},
{
field = "preInstalledSw"
value = "NA"
},
{
field = "licenseModel"
value = "No License required"
},
{
field = "tenancy"
value = "Shared"
},
]
}
`, dataName, instanceType)
}

func testAccDataSourceAwsPricingProductConfigRedshift() string {
return fmt.Sprintf(`data "aws_pricing_product" "test" {
service_code = "AmazonRedshift"

filters = [
{
field = "instanceType"
value = "ds1.xlarge"
},
{
field = "location"
value = "US East (N. Virginia)"
},
]
}
`)
}

func testAccPricingCheckValueIsJSON(data string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[data]

if !ok {
return fmt.Errorf("Can't find resource: %s", data)
}

result := rs.Primary.Attributes["result"]
var objmap map[string]*json.RawMessage

if err := json.Unmarshal([]byte(result), &objmap); err != nil {
return fmt.Errorf("%s result value (%s) is not JSON: %s", data, result, err)
}

if len(objmap) == 0 {
return fmt.Errorf("%s result value (%s) unmarshalling resulted in an empty map", data, result)
}

return nil
}
}
1 change: 1 addition & 0 deletions aws/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ func Provider() terraform.ResourceProvider {
"aws_network_interface": dataSourceAwsNetworkInterface(),
"aws_partition": dataSourceAwsPartition(),
"aws_prefix_list": dataSourceAwsPrefixList(),
"aws_pricing_product": dataSourceAwsPricingProduct(),
"aws_rds_cluster": dataSourceAwsRdsCluster(),
"aws_redshift_cluster": dataSourceAwsRedshiftCluster(),
"aws_redshift_service_account": dataSourceAwsRedshiftServiceAccount(),
Expand Down
71 changes: 71 additions & 0 deletions website/docs/d/pricing_product.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
layout: "aws"
page_title: "AWS: aws_pricing_product"
sidebar_current: "docs-aws-datasource-pricing-product"
Copy link
Contributor

Choose a reason for hiding this comment

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

This page needs a sidebar link added to website/aws.erb

description: |-
Get information regarding the pricing of an Amazon product
---

# Data Source: aws_pricing_product

Use this data source to get the pricing information of all products in AWS.
This data source is only available in a us-east-1 or ap-south-1 provider.

## Example Usage

```hcl
data "aws_pricing_product" "test1" {
service_code = "AmazonEC2"

filters = [
{
field = "instanceType"
value = "c5.xlarge"
},
{
field = "operatingSystem"
value = "Linux"
},
{
field = "location"
value = "US East (N. Virginia)"
},
{
field = "preInstalledSw"
value = "NA"
},
{
field = "licenseModel"
value = "No License required"
},
{
field = "tenancy"
value = "Shared"
},
]
}

data "aws_pricing_product" "test2" {
service_code = "AmazonRedshift"

filters = [
{
field = "instanceType"
value = "ds1.xlarge"
},
{
field = "location"
value = "US East (N. Virginia)"
},
]
}
```

## Argument Reference

* `service_code` - (Required) The code of the service. Available service codes can be fetched using the DescribeServices pricing API call.
* `filters` - (Required) A list of filters. Passed directly to the API (see GetProducts API reference). These filters must describe a single product, this resource will fail if more than one product is returned by the API.
Copy link
Contributor

Choose a reason for hiding this comment

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

We need to describe the filters nested fields as well, e.g.

### filters

* `field` (Required) The attribute name that you want to filter on.
* `value` (Required) The attribute value that you want to filter on.


## Attributes Reference

* `result` - Set to the product returned from the API.