github.com/richardbowden/terraform@v0.6.12-0.20160901200758-30ea22c25211/builtin/providers/terraform/data_source_state.go (about) 1 package terraform 2 3 import ( 4 "log" 5 "time" 6 7 "github.com/hashicorp/terraform/helper/schema" 8 "github.com/hashicorp/terraform/state/remote" 9 ) 10 11 func dataSourceRemoteState() *schema.Resource { 12 return &schema.Resource{ 13 Read: dataSourceRemoteStateRead, 14 15 Schema: map[string]*schema.Schema{ 16 "backend": { 17 Type: schema.TypeString, 18 Required: true, 19 }, 20 21 "config": { 22 Type: schema.TypeMap, 23 Optional: true, 24 }, 25 26 "__has_dynamic_attributes": { 27 Type: schema.TypeString, 28 Optional: true, 29 }, 30 }, 31 } 32 } 33 34 func dataSourceRemoteStateRead(d *schema.ResourceData, meta interface{}) error { 35 backend := d.Get("backend").(string) 36 config := make(map[string]string) 37 for k, v := range d.Get("config").(map[string]interface{}) { 38 config[k] = v.(string) 39 } 40 41 // Create the client to access our remote state 42 log.Printf("[DEBUG] Initializing remote state client: %s", backend) 43 client, err := remote.NewClient(backend, config) 44 if err != nil { 45 return err 46 } 47 48 // Create the remote state itself and refresh it in order to load the state 49 log.Printf("[DEBUG] Loading remote state...") 50 state := &remote.State{Client: client} 51 if err := state.RefreshState(); err != nil { 52 return err 53 } 54 55 d.SetId(time.Now().UTC().String()) 56 57 outputMap := make(map[string]interface{}) 58 59 remoteState := state.State() 60 if remoteState.Empty() { 61 log.Println("[DEBUG] empty remote state") 62 return nil 63 } 64 65 for key, val := range remoteState.RootModule().Outputs { 66 outputMap[key] = val.Value 67 } 68 69 mappedOutputs := remoteStateFlatten(outputMap) 70 71 for key, val := range mappedOutputs { 72 d.UnsafeSetFieldRaw(key, val) 73 } 74 return nil 75 }