config: allow applying variables to resources

This commit is contained in:
Mitchell Hashimoto 2014-06-05 06:23:41 -07:00
parent e904fca3da
commit bd1f235b9b
2 changed files with 64 additions and 0 deletions

View File

@ -7,6 +7,7 @@ import (
"strings"
"github.com/hashicorp/terraform/depgraph"
"github.com/mitchellh/reflectwalk"
)
// ResourceGraphRoot is the name of the resource graph root that should be
@ -81,6 +82,25 @@ func (r *Resource) Id() string {
return fmt.Sprintf("%s.%s", r.Type, r.Name)
}
// ReplaceVariables replaces the variables in the configuration
// with the given values.
//
// This replacement is not in place. Instead, this function will
// return a new resource with the variables replaced.
func (r *Resource) ReplaceVariables(vs map[string]string) *Resource {
result := *r
w := &variableReplaceWalker{
Values: vs,
}
if err := reflectwalk.Walk(result.Config, w); err != nil {
panic(err)
}
return &result
}
// ResourceGraph returns a dependency graph of the resources from this
// Terraform configuration.
func (c *Config) ResourceGraph() *depgraph.Graph {

View File

@ -2,6 +2,7 @@ package config
import (
"path/filepath"
"reflect"
"strings"
"testing"
)
@ -63,6 +64,49 @@ func TestNewUserVariable(t *testing.T) {
}
}
func TestResourceReplaceVariables(t *testing.T) {
r := &Resource{
Name: "foo",
Type: "bar",
Config: map[string]interface{}{
"foo": "${var.bar}",
},
}
values := map[string]string{
"var.bar": "value",
}
r2 := r.ReplaceVariables(values)
expected := &Resource{
Name: "foo",
Type: "bar",
Config: map[string]interface{}{
"foo": "value",
},
}
if !reflect.DeepEqual(r2, expected) {
t.Fatalf("bad: %#v", r2)
}
/*
TODO(mitchellh): Eventually, preserve original config...
expectedOriginal := &Resource{
Name: "foo",
Type: "bar",
Config: map[string]interface{}{
"foo": "${var.bar}",
},
}
if !reflect.DeepEqual(r, expectedOriginal) {
t.Fatalf("bad: %#v", r)
}
*/
}
const resourceGraphValue = `
root: root
root -> aws_security_group.firewall