2015-03-12 00:17:47 +01:00
|
|
|
package terraform
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/hashicorp/terraform/helper/schema"
|
|
|
|
"github.com/hashicorp/terraform/state/remote"
|
|
|
|
)
|
|
|
|
|
2016-05-02 01:05:54 +02:00
|
|
|
func dataSourceRemoteState() *schema.Resource {
|
2015-03-12 00:17:47 +01:00
|
|
|
return &schema.Resource{
|
2016-05-02 01:05:54 +02:00
|
|
|
Read: dataSourceRemoteStateRead,
|
2015-03-12 00:17:47 +01:00
|
|
|
|
|
|
|
Schema: map[string]*schema.Schema{
|
2016-06-09 14:45:55 +02:00
|
|
|
"backend": {
|
2015-03-12 00:17:47 +01:00
|
|
|
Type: schema.TypeString,
|
|
|
|
Required: true,
|
|
|
|
},
|
|
|
|
|
2016-06-09 14:45:55 +02:00
|
|
|
"config": {
|
2015-03-12 00:17:47 +01:00
|
|
|
Type: schema.TypeMap,
|
|
|
|
Optional: true,
|
|
|
|
},
|
|
|
|
|
2016-06-09 14:45:55 +02:00
|
|
|
"__has_dynamic_attributes": {
|
|
|
|
Type: schema.TypeString,
|
|
|
|
Optional: true,
|
2015-03-12 00:17:47 +01:00
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-02 01:05:54 +02:00
|
|
|
func dataSourceRemoteStateRead(d *schema.ResourceData, meta interface{}) error {
|
2015-03-12 00:17:47 +01:00
|
|
|
backend := d.Get("backend").(string)
|
|
|
|
config := make(map[string]string)
|
|
|
|
for k, v := range d.Get("config").(map[string]interface{}) {
|
|
|
|
config[k] = v.(string)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the client to access our remote state
|
|
|
|
log.Printf("[DEBUG] Initializing remote state client: %s", backend)
|
|
|
|
client, err := remote.NewClient(backend, config)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the remote state itself and refresh it in order to load the state
|
|
|
|
log.Printf("[DEBUG] Loading remote state...")
|
|
|
|
state := &remote.State{Client: client}
|
|
|
|
if err := state.RefreshState(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-06-09 14:45:55 +02:00
|
|
|
d.SetId(time.Now().UTC().String())
|
|
|
|
|
|
|
|
outputMap := make(map[string]interface{})
|
|
|
|
for key, val := range state.State().RootModule().Outputs {
|
|
|
|
outputMap[key] = val.Value
|
2015-04-02 07:49:05 +02:00
|
|
|
}
|
|
|
|
|
2016-06-09 14:45:55 +02:00
|
|
|
mappedOutputs := remoteStateFlatten(outputMap)
|
|
|
|
|
|
|
|
for key, val := range mappedOutputs {
|
|
|
|
d.UnsafeSetFieldRaw(key, val)
|
|
|
|
}
|
2015-03-12 00:17:47 +01:00
|
|
|
return nil
|
|
|
|
}
|