From eaac13dd9b8dc0e53bae7f7520c8f41d08d6ebda Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Sun, 17 Aug 2014 15:01:27 -0700 Subject: [PATCH] helper/schema: ResourceProvider.Configure --- helper/schema/provider.go | 26 +++++++++++- helper/schema/provider_test.go | 73 ++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 1 deletion(-) diff --git a/helper/schema/provider.go b/helper/schema/provider.go index d6f1c1a0b..1ac2c2ff2 100644 --- a/helper/schema/provider.go +++ b/helper/schema/provider.go @@ -15,7 +15,7 @@ type Provider struct { Schema map[string]*Schema Resources map[string]*Resource - Configure ConfigureFunc + ConfigureFunc ConfigureFunc } // ConfigureFunc is the function used to configure a Provider. @@ -38,3 +38,27 @@ func (p *Provider) ValidateResource( return r.Validate(c) } + +// Configure implementation of terraform.ResourceProvider interface. +func (p *Provider) Configure(c *terraform.ResourceConfig) error { + // No configuration + if p.ConfigureFunc == nil { + return nil + } + + sm := schemaMap(p.Schema) + + // Get a ResourceData for this configuration. To do this, we actually + // generate an intermediary "diff" although that is never exposed. + diff, err := sm.Diff(nil, c) + if err != nil { + return err + } + + data, err := sm.Data(nil, diff) + if err != nil { + return err + } + + return p.ConfigureFunc(data) +} diff --git a/helper/schema/provider_test.go b/helper/schema/provider_test.go index aebffa81e..4a00522fd 100644 --- a/helper/schema/provider_test.go +++ b/helper/schema/provider_test.go @@ -1,12 +1,85 @@ package schema import ( + "fmt" "testing" "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/terraform" ) +func TestProviderConfigure(t *testing.T) { + cases := []struct { + P *Provider + Config map[string]interface{} + Err bool + }{ + { + P: &Provider{}, + Config: nil, + Err: false, + }, + + { + P: &Provider{ + Schema: map[string]*Schema{ + "foo": &Schema{ + Type: TypeInt, + Optional: true, + }, + }, + + ConfigureFunc: func(d *ResourceData) error { + if d.Get("foo").(int) == 42 { + return nil + } + + return fmt.Errorf("nope") + }, + }, + Config: map[string]interface{}{ + "foo": 42, + }, + Err: false, + }, + + { + P: &Provider{ + Schema: map[string]*Schema{ + "foo": &Schema{ + Type: TypeInt, + Optional: true, + }, + }, + + ConfigureFunc: func(d *ResourceData) error { + if d.Get("foo").(int) == 42 { + return nil + } + + return fmt.Errorf("nope") + }, + }, + Config: map[string]interface{}{ + "foo": 52, + }, + Err: true, + }, + } + + for i, tc := range cases { + c, err := config.NewRawConfig(tc.Config) + if err != nil { + t.Fatalf("err: %s", err) + } + + err = tc.P.Configure(terraform.NewResourceConfig(c)) + if (err != nil) != tc.Err { + t.Fatalf("%d: %s", i, err) + } + } +} + func TestProviderValidateResource(t *testing.T) { cases := []struct { P *Provider