From bd1f235b9b63aecb4acd2167a2c9ea84153bdb9b Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Thu, 5 Jun 2014 06:23:41 -0700 Subject: [PATCH] config: allow applying variables to resources --- config/config.go | 20 ++++++++++++++++++++ config/config_test.go | 44 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/config/config.go b/config/config.go index 44388970c..990cd905a 100644 --- a/config/config.go +++ b/config/config.go @@ -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 { diff --git a/config/config_test.go b/config/config_test.go index cc97f9f8d..7baaa7e3b 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -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