Skip to content

Commit df2ce58

Browse files
Specialized client for interacting with Consul keys
This deals with some of the quirks of interacting with the Consul API, with the goal of making the consul_keys resource implementation, and later the consul_keys data source, less noisy to read.
1 parent 99ddea5 commit df2ce58

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package consul
2+
3+
import (
4+
"fmt"
5+
"log"
6+
7+
consulapi "github.com/hashicorp/consul/api"
8+
)
9+
10+
// keyClient is a wrapper around the upstream Consul client that is
11+
// specialized for Terraform's manipulations of the key/value store.
12+
type keyClient struct {
13+
client *consulapi.KV
14+
qOpts *consulapi.QueryOptions
15+
wOpts *consulapi.WriteOptions
16+
}
17+
18+
func newKeyClient(realClient *consulapi.KV, dc, token string) *keyClient {
19+
qOpts := &consulapi.QueryOptions{Datacenter: dc, Token: token}
20+
wOpts := &consulapi.WriteOptions{Datacenter: dc, Token: token}
21+
22+
return &keyClient{
23+
client: realClient,
24+
qOpts: qOpts,
25+
wOpts: wOpts,
26+
}
27+
}
28+
29+
func (c *keyClient) Get(path string) (string, error) {
30+
log.Printf(
31+
"[DEBUG] Reading key '%s' in %s",
32+
path, c.qOpts.Datacenter,
33+
)
34+
pair, _, err := c.client.Get(path, c.qOpts)
35+
if err != nil {
36+
return "", fmt.Errorf("Failed to read Consul key '%s': %s", path, err)
37+
}
38+
value := ""
39+
if pair != nil {
40+
value = string(pair.Value)
41+
}
42+
return value, nil
43+
}
44+
45+
func (c *keyClient) Put(path, value string) error {
46+
log.Printf(
47+
"[DEBUG] Setting key '%s' to '%v' in %s",
48+
path, value, c.wOpts.Datacenter,
49+
)
50+
pair := consulapi.KVPair{Key: path, Value: []byte(value)}
51+
if _, err := c.client.Put(&pair, c.wOpts); err != nil {
52+
return fmt.Errorf("Failed to write Consul key '%s': %s", path, err)
53+
}
54+
return nil
55+
}
56+
57+
func (c *keyClient) Delete(path string) error {
58+
log.Printf(
59+
"[DEBUG] Deleting key '%s' in %s",
60+
path, c.wOpts.Datacenter,
61+
)
62+
if _, err := c.client.Delete(path, c.wOpts); err != nil {
63+
return fmt.Errorf("Failed to delete Consul key '%s': %s", path, err)
64+
}
65+
return nil
66+
}

0 commit comments

Comments
 (0)