diff --git a/terraform/data_source_state.go b/terraform/data_source_state.go new file mode 100644 index 000000000..730158550 --- /dev/null +++ b/terraform/data_source_state.go @@ -0,0 +1,112 @@ +package terraform + +import ( + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform/backend" + backendinit "github.com/hashicorp/terraform/backend/init" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +func dataSourceRemoteState() *schema.Resource { + return &schema.Resource{ + Read: dataSourceRemoteStateRead, + + Schema: map[string]*schema.Schema{ + "backend": { + Type: schema.TypeString, + Required: true, + ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) { + if vStr, ok := v.(string); ok && vStr == "_local" { + ws = append(ws, "Use of the %q backend is now officially "+ + "supported as %q. Please update your configuration to ensure "+ + "compatibility with future versions of Terraform.", + "_local", "local") + } + + return + }, + }, + + "config": { + Type: schema.TypeMap, + Optional: true, + }, + + "environment": { + Type: schema.TypeString, + Optional: true, + Default: backend.DefaultStateName, + }, + + "__has_dynamic_attributes": { + Type: schema.TypeString, + Optional: true, + }, + }, + } +} + +func dataSourceRemoteStateRead(d *schema.ResourceData, meta interface{}) error { + backend := d.Get("backend").(string) + + // Get the configuration in a type we want. + rawConfig, err := config.NewRawConfig(d.Get("config").(map[string]interface{})) + if err != nil { + return fmt.Errorf("error initializing backend: %s", err) + } + + // Don't break people using the old _local syntax - but note warning above + if backend == "_local" { + log.Println(`[INFO] Switching old (unsupported) backend "_local" to "local"`) + backend = "local" + } + + // Create the client to access our remote state + log.Printf("[DEBUG] Initializing remote state backend: %s", backend) + f := backendinit.Backend(backend) + if f == nil { + return fmt.Errorf("Unknown backend type: %s", backend) + } + b := f() + + // Configure the backend + if err := b.Configure(terraform.NewResourceConfig(rawConfig)); err != nil { + return fmt.Errorf("error initializing backend: %s", err) + } + + // Get the state + env := d.Get("environment").(string) + state, err := b.State(env) + if err != nil { + return fmt.Errorf("error loading the remote state: %s", err) + } + if err := state.RefreshState(); err != nil { + return err + } + + d.SetId(time.Now().UTC().String()) + + outputMap := make(map[string]interface{}) + + remoteState := state.State() + if remoteState.Empty() { + log.Println("[DEBUG] empty remote state") + return nil + } + + for key, val := range remoteState.RootModule().Outputs { + outputMap[key] = val.Value + } + + mappedOutputs := remoteStateFlatten(outputMap) + + for key, val := range mappedOutputs { + d.UnsafeSetFieldRaw(key, val) + } + return nil +} diff --git a/terraform/data_source_state_test.go b/terraform/data_source_state_test.go new file mode 100644 index 000000000..9a58b154f --- /dev/null +++ b/terraform/data_source_state_test.go @@ -0,0 +1,111 @@ +package terraform + +import ( + "fmt" + "testing" + + backendinit "github.com/hashicorp/terraform/backend/init" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestState_basic(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccState_basic, + Check: resource.ComposeTestCheckFunc( + testAccCheckStateValue( + "data.terraform_remote_state.foo", "foo", "bar"), + ), + }, + }, + }) +} + +func TestState_backends(t *testing.T) { + backendinit.Set("_ds_test", backendinit.Backend("local")) + defer backendinit.Set("_ds_test", nil) + + resource.UnitTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccState_backend, + Check: resource.ComposeTestCheckFunc( + testAccCheckStateValue( + "data.terraform_remote_state.foo", "foo", "bar"), + ), + }, + }, + }) +} + +func TestState_complexOutputs(t *testing.T) { + resource.UnitTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccState_complexOutputs, + Check: resource.ComposeTestCheckFunc( + testAccCheckStateValue("terraform_remote_state.foo", "backend", "local"), + testAccCheckStateValue("terraform_remote_state.foo", "config.path", "./test-fixtures/complex_outputs.tfstate"), + testAccCheckStateValue("terraform_remote_state.foo", "computed_set.#", "2"), + testAccCheckStateValue("terraform_remote_state.foo", `map.%`, "2"), + testAccCheckStateValue("terraform_remote_state.foo", `map.key`, "test"), + ), + }, + }, + }) +} + +func testAccCheckStateValue(id, name, value string) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[id] + if !ok { + return fmt.Errorf("Not found: %s", id) + } + if rs.Primary.ID == "" { + return fmt.Errorf("No ID is set") + } + + v := rs.Primary.Attributes[name] + if v != value { + return fmt.Errorf( + "Value for %s is %s, not %s", name, v, value) + } + + return nil + } +} + +const testAccState_basic = ` +data "terraform_remote_state" "foo" { + backend = "local" + + config { + path = "./test-fixtures/basic.tfstate" + } +}` + +const testAccState_backend = ` +data "terraform_remote_state" "foo" { + backend = "_ds_test" + + config { + path = "./test-fixtures/basic.tfstate" + } +}` + +const testAccState_complexOutputs = ` +resource "terraform_remote_state" "foo" { + backend = "local" + + config { + path = "./test-fixtures/complex_outputs.tfstate" + } +}` diff --git a/terraform/flatten.go b/terraform/flatten.go new file mode 100644 index 000000000..4766a4f5e --- /dev/null +++ b/terraform/flatten.go @@ -0,0 +1,76 @@ +package terraform + +import ( + "fmt" + "reflect" +) + +// remoteStateFlatten takes a structure and turns into a flat map[string]string. +// +// Within the "thing" parameter, only primitive values are allowed. Structs are +// not supported. Therefore, it can only be slices, maps, primitives, and +// any combination of those together. +// +// The difference between this version and the version in package flatmap is that +// we add the count key for maps in this version, and return a normal +// map[string]string instead of a flatmap.Map +func remoteStateFlatten(thing map[string]interface{}) map[string]string { + result := make(map[string]string) + + for k, raw := range thing { + flatten(result, k, reflect.ValueOf(raw)) + } + + return result +} + +func flatten(result map[string]string, prefix string, v reflect.Value) { + if v.Kind() == reflect.Interface { + v = v.Elem() + } + + switch v.Kind() { + case reflect.Bool: + if v.Bool() { + result[prefix] = "true" + } else { + result[prefix] = "false" + } + case reflect.Int: + result[prefix] = fmt.Sprintf("%d", v.Int()) + case reflect.Map: + flattenMap(result, prefix, v) + case reflect.Slice: + flattenSlice(result, prefix, v) + case reflect.String: + result[prefix] = v.String() + default: + panic(fmt.Sprintf("Unknown: %s", v)) + } +} + +func flattenMap(result map[string]string, prefix string, v reflect.Value) { + mapKeys := v.MapKeys() + + result[fmt.Sprintf("%s.%%", prefix)] = fmt.Sprintf("%d", len(mapKeys)) + for _, k := range mapKeys { + if k.Kind() == reflect.Interface { + k = k.Elem() + } + + if k.Kind() != reflect.String { + panic(fmt.Sprintf("%s: map key is not string: %s", prefix, k)) + } + + flatten(result, fmt.Sprintf("%s.%s", prefix, k.String()), v.MapIndex(k)) + } +} + +func flattenSlice(result map[string]string, prefix string, v reflect.Value) { + prefix = prefix + "." + + result[prefix+"#"] = fmt.Sprintf("%d", v.Len()) + for i := 0; i < v.Len(); i++ { + flatten(result, fmt.Sprintf("%s%d", prefix, i), v.Index(i)) + } +} diff --git a/terraform/provider.go b/terraform/provider.go new file mode 100644 index 000000000..1bdf2c1d0 --- /dev/null +++ b/terraform/provider.go @@ -0,0 +1,21 @@ +package terraform + +import ( + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +// Provider returns a terraform.ResourceProvider. +func Provider() terraform.ResourceProvider { + return &schema.Provider{ + ResourcesMap: map[string]*schema.Resource{ + "terraform_remote_state": schema.DataSourceResourceShim( + "terraform_remote_state", + dataSourceRemoteState(), + ), + }, + DataSourcesMap: map[string]*schema.Resource{ + "terraform_remote_state": dataSourceRemoteState(), + }, + } +} diff --git a/terraform/provider_test.go b/terraform/provider_test.go new file mode 100644 index 000000000..65f3ce4ad --- /dev/null +++ b/terraform/provider_test.go @@ -0,0 +1,31 @@ +package terraform + +import ( + "testing" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/terraform" +) + +var testAccProviders map[string]terraform.ResourceProvider +var testAccProvider *schema.Provider + +func init() { + testAccProvider = Provider().(*schema.Provider) + testAccProviders = map[string]terraform.ResourceProvider{ + "terraform": testAccProvider, + } +} + +func TestProvider(t *testing.T) { + if err := Provider().(*schema.Provider).InternalValidate(); err != nil { + t.Fatalf("err: %s", err) + } +} + +func TestProvider_impl(t *testing.T) { + var _ terraform.ResourceProvider = Provider() +} + +func testAccPreCheck(t *testing.T) { +} diff --git a/terraform/test-fixtures/basic.tfstate b/terraform/test-fixtures/basic.tfstate new file mode 100644 index 000000000..a10b2b6b1 --- /dev/null +++ b/terraform/test-fixtures/basic.tfstate @@ -0,0 +1,7 @@ +{ + "version": 1, + "modules": [{ + "path": ["root"], + "outputs": { "foo": "bar" } + }] +} diff --git a/terraform/test-fixtures/complex_outputs.tfstate b/terraform/test-fixtures/complex_outputs.tfstate new file mode 100644 index 000000000..ab50e427f --- /dev/null +++ b/terraform/test-fixtures/complex_outputs.tfstate @@ -0,0 +1,88 @@ +{ + "version": 3, + "terraform_version": "0.7.0", + "serial": 3, + "modules": [ + { + "path": [ + "root" + ], + "outputs": { + "computed_map": { + "sensitive": false, + "type": "map", + "value": { + "key1": "value1" + } + }, + "computed_set": { + "sensitive": false, + "type": "list", + "value": [ + "setval1", + "setval2" + ] + }, + "map": { + "sensitive": false, + "type": "map", + "value": { + "key": "test", + "test": "test" + } + }, + "set": { + "sensitive": false, + "type": "list", + "value": [ + "test1", + "test2" + ] + } + }, + "resources": { + "test_resource.main": { + "type": "test_resource", + "primary": { + "id": "testId", + "attributes": { + "computed_list.#": "2", + "computed_list.0": "listval1", + "computed_list.1": "listval2", + "computed_map.%": "1", + "computed_map.key1": "value1", + "computed_read_only": "value_from_api", + "computed_read_only_force_new": "value_from_api", + "computed_set.#": "2", + "computed_set.2337322984": "setval1", + "computed_set.307881554": "setval2", + "id": "testId", + "list_of_map.#": "2", + "list_of_map.0.%": "2", + "list_of_map.0.key1": "value1", + "list_of_map.0.key2": "value2", + "list_of_map.1.%": "2", + "list_of_map.1.key3": "value3", + "list_of_map.1.key4": "value4", + "map.%": "2", + "map.key": "test", + "map.test": "test", + "map_that_look_like_set.%": "2", + "map_that_look_like_set.12352223": "hello", + "map_that_look_like_set.36234341": "world", + "optional_computed_map.%": "0", + "required": "Hello World", + "required_map.%": "3", + "required_map.key1": "value1", + "required_map.key2": "value2", + "required_map.key3": "value3", + "set.#": "2", + "set.2326977762": "test1", + "set.331058520": "test2" + } + } + } + } + } + ] +}