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 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
92 changes: 92 additions & 0 deletions aws/data_source_aws_pricing_product.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
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"
)

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(pricing.FilterTypeTermMatch),
})
}

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)
}

numberOfElements := len(resp.PriceList)
if numberOfElements == 0 {
return fmt.Errorf("Pricing product query did not return any elements")
} else if numberOfElements > 1 {
priceListBytes, err := json.Marshal(resp.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)
}

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
}
124 changes: 124 additions & 0 deletions aws/data_source_aws_pricing_product_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
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) {
oldRegion := os.Getenv("AWS_DEFAULT_REGION")
os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
defer os.Setenv("AWS_DEFAULT_REGION", oldRegion)
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) {
oldRegion := os.Getenv("AWS_DEFAULT_REGION")
os.Setenv("AWS_DEFAULT_REGION", "us-east-1")
defer os.Setenv("AWS_DEFAULT_REGION", oldRegion)
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
3 changes: 3 additions & 0 deletions website/aws.erb
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,9 @@
<li<%= sidebar_current("docs-aws-datasource-prefix-list") %>>
<a href="/docs/providers/aws/d/prefix_list.html">aws_prefix_list</a>
</li>
<li<%= sidebar_current("docs-aws-datasource-pricing-product") %>>
<a href="/docs/providers/aws/d/pricing_product.html">aws_pricing_product</a>
</li>
<li<%= sidebar_current("docs-aws-datasource-rds-cluster") %>>
<a href="/docs/providers/aws/d/rds_cluster.html">aws_rds_cluster</a>
</li>
Expand Down
78 changes: 78 additions & 0 deletions website/docs/d/pricing_product.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
---
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" "example" {
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"
},
]
}
```

```hcl
data "aws_pricing_product" "example" {
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.


### `filters`

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

## Attributes Reference

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