Skip to content

Commit

Permalink
Merge pull request #14 from kvrhdn/sdk-v2
Browse files Browse the repository at this point in the history
 Upgrade to Terraform Plugin SDK v2
  • Loading branch information
Koenraad Verheyden authored Aug 9, 2020
2 parents f438cac + d283bd4 commit cc19233
Show file tree
Hide file tree
Showing 18 changed files with 499 additions and 168 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
*.tfplan
*.tfstate
*.tfstate.backup
*.tfvars
.terraform/
*.log

Expand Down
2 changes: 1 addition & 1 deletion .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ builds:
flags:
- -trimpath
ldflags:
- '-s -w -X main.version={{.Version}} -X main.commit={{.Commit}}'
- '-s -w -X github.com/kvrhdn/terraform-provider-honeycombio/honeycombio.providerVersion={{.Version}}'
goos:
- freebsd
- windows
Expand Down
16 changes: 16 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,22 @@ Finally, **run the acceptance tests** by passing the API key and dataset as envi
HONEYCOMBIO_APIKEY=<your API key> HONEYCOMBIO_DATASET=<dataset> make testacc
```

### Enabling log output

To print logs (including full dumps of requests and their responses), you have to set `TF_LOG` to at least `debug` and enable `HONEYCOMBIO_DEBUG` when running Terraform:

```sh
TF_LOG=debug HONEYCOMBIO_DEBUG=true terraform apply
```

A handy one-liner to simultaneously write the output to a file:

```sh
TF_LOG=debug HONEYCOMBIO_DEBUG=true terraform apply 2>&1 | tee output.log
```

For more information, see [Debugging Terraform](https://www.terraform.io/docs/internals/debugging.html).

### Style convention

CI will run the following tools to style code:
Expand Down
3 changes: 2 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,5 @@ The key can be set with the `api_key` argument or via the `HONEYCOMBIO_APIKEY` e
Arguments accepted by this provider include:

* `api_key` - (Required) The Honeycomb API key to use. It can also be set using the `HONEYCOMBIO_APIKEY` environment variable.
* `api_url` - (Optional) Override the url of the Honeycomb.io API. Defaults to `https://api.honeycomb.io`
* `api_url` - (Optional) Override the url of the Honeycomb.io API. Defaults to `https://api.honeycomb.io`.
* `debug` - (Optional) Enable to log additional debug information. To view the logs, set `TF_LOG` to at least debug.
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ module github.com/kvrhdn/terraform-provider-honeycombio
go 1.14

require (
github.com/hashicorp/terraform-plugin-sdk v1.15.0
github.com/kvrhdn/go-honeycombio v0.0.9
github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320
github.com/hashicorp/terraform-plugin-sdk/v2 v2.0.1-0.20200806005530-dc34c138a984
github.com/kvrhdn/go-honeycombio v0.0.10
github.com/stretchr/testify v1.6.1
)
309 changes: 258 additions & 51 deletions go.sum

Large diffs are not rendered by default.

57 changes: 43 additions & 14 deletions honeycombio/data_source_query.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package honeycombio

import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"

"github.com/hashicorp/terraform-plugin-sdk/helper/hashcode"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
honeycombio "github.com/kvrhdn/go-honeycombio"
"github.com/kvrhdn/terraform-provider-honeycombio/util"
)

var validQueryCalculationOps = []string{
Expand Down Expand Up @@ -49,7 +50,7 @@ var validQueryFilterOps = []string{

func dataSourceHoneycombioQuery() *schema.Resource {
return &schema.Resource{
Read: dataSourceHoneycombioQueryRead,
ReadContext: dataSourceHoneycombioQueryRead,

Schema: map[string]*schema.Schema{
"calculation": {
Expand Down Expand Up @@ -83,7 +84,6 @@ func dataSourceHoneycombioQuery() *schema.Resource {
Required: true,
ValidateFunc: validation.StringInSlice(validQueryFilterOps, false),
},
//TODO add validation to make sure this doesn't exist when Op in ('exists', 'does-not-exist') if v2 SDK supports that
"value": {
Type: schema.TypeString,
Optional: true,
Expand Down Expand Up @@ -112,7 +112,7 @@ func dataSourceHoneycombioQuery() *schema.Resource {
}
}

func dataSourceHoneycombioQueryRead(d *schema.ResourceData, meta interface{}) error {
func dataSourceHoneycombioQueryRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
calculationSchemas := d.Get("calculation").(*schema.Set).List()
calculations := make([]honeycombio.CalculationSpec, len(calculationSchemas))

Expand All @@ -138,10 +138,17 @@ func dataSourceHoneycombioQueryRead(d *schema.ResourceData, meta interface{}) er
Op: honeycombio.FilterOp(fMap["op"].(string)),
Value: fMap["value"].(string),
}
hf := filters[i]
if hf.Op == honeycombio.FilterOpExists || hf.Op == honeycombio.FilterOpDoesNotExist {
if hf.Value != "" {
return errors.New(fmt.Sprintf("Filter operation %s must not contain a value", hf.Op))

// Ensure we don't send filter.Value if op is "exists" or
// "does-not-exist". The Honeycomb API will refuse this.
//
// TODO ideally this check is part of the schema (as a ValidateFunc),
// but this is not yet supported by the SDK.
// https://github.com/hashicorp/terraform-plugin-sdk/issues/155#issuecomment-489699737
filter := filters[i]
if filter.Op == honeycombio.FilterOpExists || filter.Op == honeycombio.FilterOpDoesNotExist {
if filter.Value != "" {
return diag.Errorf("Filter operation %s must not contain a value", filter.Op)
}
filters[i].Value = nil
}
Expand All @@ -165,11 +172,11 @@ func dataSourceHoneycombioQueryRead(d *schema.ResourceData, meta interface{}) er

jsonQuery, err := encodeQuery(query)
if err != nil {
return err
return diag.FromErr(err)
}

d.Set("json", jsonQuery)
d.SetId(strconv.Itoa(hashcode.String(jsonQuery)))
d.SetId(strconv.Itoa(util.HashString(jsonQuery)))

return nil
}
Expand All @@ -179,3 +186,25 @@ func encodeQuery(q *honeycombio.QuerySpec) (string, error) {
jsonQueryBytes, err := json.MarshalIndent(q, "", " ")
return string(jsonQueryBytes), err
}

type querySpecValidateDiagFunc func(q *honeycombio.QuerySpec) diag.Diagnostics

// validateQueryJSON checks that the input can be deserialized as a QuerySpec
// and optionally runs a list of custom validation functions.
func validateQueryJSON(validators ...querySpecValidateDiagFunc) schema.SchemaValidateDiagFunc {
return func(i interface{}, path cty.Path) diag.Diagnostics {
var q honeycombio.QuerySpec

err := json.Unmarshal([]byte(i.(string)), &q)
if err != nil {
return diag.Errorf("Value of query_json is not a valid query specification")
}

var diagnostics diag.Diagnostics

for _, validator := range validators {
diagnostics = append(diagnostics, validator(&q)...)
}
return diagnostics
}
}
2 changes: 1 addition & 1 deletion honeycombio/data_source_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"regexp"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccDataSourceHoneycombioQuery_basic(t *testing.T) {
Expand Down
48 changes: 38 additions & 10 deletions honeycombio/provider.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
package honeycombio

import (
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"context"
"log"
"os"
"strconv"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
honeycombio "github.com/kvrhdn/go-honeycombio"
)

// providerVersion represents the current version of the provider. It should be
// overwritten during the release process.
var providerVersion = "dev"

func Provider() *schema.Provider {
return &schema.Provider{
provider := &schema.Provider{
Schema: map[string]*schema.Schema{
"api_key": {
Type: schema.TypeString,
Expand All @@ -17,6 +27,14 @@ func Provider() *schema.Provider {
Type: schema.TypeString,
Optional: true,
},
"debug": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: func() (interface{}, error) {
b, _ := strconv.ParseBool(os.Getenv("HONEYCOMBIO_DEBUG"))
return b, nil
},
},
},
DataSourcesMap: map[string]*schema.Resource{
"honeycombio_query": dataSourceHoneycombioQuery(),
Expand All @@ -26,15 +44,25 @@ func Provider() *schema.Provider {
"honeycombio_marker": newMarker(),
"honeycombio_trigger": newTrigger(),
},
ConfigureFunc: Configure,
}
}

func Configure(d *schema.ResourceData) (interface{}, error) {
config := &honeycombio.Config{
APIKey: d.Get("api_key").(string),
APIUrl: d.Get("api_url").(string),
UserAgent: "terraform-provider-honeycombio",
provider.ConfigureContextFunc = func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {
config := &honeycombio.Config{
APIKey: d.Get("api_key").(string),
APIUrl: d.Get("api_url").(string),
UserAgent: provider.UserAgent("terraform-provider-honeycombio", providerVersion),
Debug: d.Get("debug").(bool),
}
c, err := honeycombio.NewClient(config)
if err != nil {
return nil, diag.FromErr(err)
}

log.Printf("Configured honeycombio client with debug = %t", config.Debug)
log.Printf("To log requests and responses, set environment variable HONEYCOMBIO_DEBUG to true")

return c, nil
}
return honeycombio.NewClient(config)

return provider
}
7 changes: 3 additions & 4 deletions honeycombio/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@ import (
"os"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

var testAccProvider *schema.Provider
var testAccProviders map[string]terraform.ResourceProvider
var testAccProviders map[string]*schema.Provider

func init() {
testAccProvider = Provider()
testAccProviders = map[string]terraform.ResourceProvider{
testAccProviders = map[string]*schema.Provider{
"honeycombio": testAccProvider,
}
}
Expand Down
Loading

0 comments on commit cc19233

Please sign in to comment.