helper/resource: automatically validate resources

/cc @pearkes - So, just set a ConfigValidator struct up on your
resources and it'll now automatically validate.
This commit is contained in:
Mitchell Hashimoto 2014-07-08 10:17:36 -07:00
parent 50b8e761f1
commit 0c812ba9e8
3 changed files with 71 additions and 5 deletions

View File

@ -13,6 +13,21 @@ type Map struct {
Mapping map[string]Resource
}
func (m *Map) Validate(
t string, c *terraform.ResourceConfig) ([]string, []error) {
r, ok := m.Mapping[t]
if !ok {
return nil, []error{fmt.Errorf("Unknown resource type: %s", t)}
}
// If there is no validator set, then it is valid
if r.ConfigValidator == nil {
return nil, nil
}
return r.ConfigValidator.Validate(c)
}
// Apply performs a create or update depending on the diff, and calls
// the proper function on the matching Resource.
func (m *Map) Apply(

View File

@ -4,6 +4,8 @@ import (
"reflect"
"testing"
tfconfig "github.com/hashicorp/terraform/config"
"github.com/hashicorp/terraform/helper/config"
"github.com/hashicorp/terraform/terraform"
)
@ -30,3 +32,50 @@ func TestMapResources(t *testing.T) {
t.Fatalf("bad: %#v", rts)
}
}
func TestMapValidate(t *testing.T) {
m := &Map{
Mapping: map[string]Resource{
"aws_elb": Resource{
ConfigValidator: &config.Validator{
Required: []string{"foo"},
},
},
},
}
var c *terraform.ResourceConfig
var ws []string
var es []error
// Valid
c = testConfig(t, map[string]interface{}{"foo": "bar"})
ws, es = m.Validate("aws_elb", c)
if len(ws) > 0 {
t.Fatalf("bad: %#v", ws)
}
if len(es) > 0 {
t.Fatalf("bad: %#v", es)
}
// Invalid
c = testConfig(t, map[string]interface{}{})
ws, es = m.Validate("aws_elb", c)
if len(ws) > 0 {
t.Fatalf("bad: %#v", ws)
}
if len(es) == 0 {
t.Fatalf("bad: %#v", es)
}
}
func testConfig(
t *testing.T,
c map[string]interface{}) *terraform.ResourceConfig {
r, err := tfconfig.NewRawConfig(c)
if err != nil {
t.Fatalf("bad: %s", err)
}
return terraform.NewResourceConfig(r)
}

View File

@ -1,10 +1,12 @@
package resource
import (
"github.com/hashicorp/terraform/helper/config"
"github.com/hashicorp/terraform/terraform"
)
type Resource struct {
ConfigValidator *config.Validator
Create CreateFunc
Destroy DestroyFunc
Diff DiffFunc