opentofu/builtin/providers/consul/data_source_consul_keys.go
Martin Atkins 19d0b42911 provider/consul: consul_keys data source (#7678)
Previously the consul_keys resource did double-duty as both a reader and
writer of values from the Consul key/value store, but that made its
interface rather confusing and complex, as well as having all of the other
general problems associated with read-only resources.

Here we split the functionality such that reading is done with the
consul_keys data source while writing is done with the consul_keys
resource.

The old read behavior of the resource is still supported, but it's no
longer documented (except as a deprecation note) and will generate
deprecation warnings when used.

In future it should be possible to simplify the consul_keys resource by
removing all of the read support, but that is deferred for now to give
users a chance to gracefully migrate to the new data source.
2016-07-26 18:23:38 +01:00

97 lines
1.8 KiB
Go

package consul
import (
consulapi "github.com/hashicorp/consul/api"
"github.com/hashicorp/terraform/helper/schema"
)
func dataSourceConsulKeys() *schema.Resource {
return &schema.Resource{
Read: dataSourceConsulKeysRead,
Schema: map[string]*schema.Schema{
"datacenter": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"token": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"key": &schema.Schema{
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"path": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"default": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
},
},
"var": &schema.Schema{
Type: schema.TypeMap,
Computed: true,
},
},
}
}
func dataSourceConsulKeysRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*consulapi.Client)
kv := client.KV()
token := d.Get("token").(string)
dc, err := getDC(d, client)
if err != nil {
return err
}
keyClient := newKeyClient(kv, dc, token)
vars := make(map[string]string)
keys := d.Get("key").(*schema.Set).List()
for _, raw := range keys {
key, path, sub, err := parseKey(raw)
if err != nil {
return err
}
value, err := keyClient.Get(path)
if err != nil {
return err
}
value = attributeValue(sub, value)
vars[key] = value
}
if err := d.Set("var", vars); err != nil {
return err
}
// Store the datacenter on this resource, which can be helpful for reference
// in case it was read from the provider
d.Set("datacenter", dc)
d.SetId("-")
return nil
}