github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/consul/key_client.go (about) 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) GetUnderPrefix(pathPrefix string) (map[string]string, error) { 46 log.Printf( 47 "[DEBUG] Listing keys under '%s' in %s", 48 pathPrefix, c.qOpts.Datacenter, 49 ) 50 pairs, _, err := c.client.List(pathPrefix, c.qOpts) 51 if err != nil { 52 return nil, fmt.Errorf( 53 "Failed to list Consul keys under prefix '%s': %s", pathPrefix, err, 54 ) 55 } 56 value := map[string]string{} 57 for _, pair := range pairs { 58 subKey := pair.Key[len(pathPrefix):] 59 value[subKey] = string(pair.Value) 60 } 61 return value, nil 62 } 63 64 func (c *keyClient) Put(path, value string) error { 65 log.Printf( 66 "[DEBUG] Setting key '%s' to '%v' in %s", 67 path, value, c.wOpts.Datacenter, 68 ) 69 pair := consulapi.KVPair{Key: path, Value: []byte(value)} 70 if _, err := c.client.Put(&pair, c.wOpts); err != nil { 71 return fmt.Errorf("Failed to write Consul key '%s': %s", path, err) 72 } 73 return nil 74 } 75 76 func (c *keyClient) Delete(path string) error { 77 log.Printf( 78 "[DEBUG] Deleting key '%s' in %s", 79 path, c.wOpts.Datacenter, 80 ) 81 if _, err := c.client.Delete(path, c.wOpts); err != nil { 82 return fmt.Errorf("Failed to delete Consul key '%s': %s", path, err) 83 } 84 return nil 85 } 86 87 func (c *keyClient) DeleteUnderPrefix(pathPrefix string) error { 88 log.Printf( 89 "[DEBUG] Deleting all keys under prefix '%s' in %s", 90 pathPrefix, c.wOpts.Datacenter, 91 ) 92 if _, err := c.client.DeleteTree(pathPrefix, c.wOpts); err != nil { 93 return fmt.Errorf("Failed to delete Consul keys under '%s': %s", pathPrefix, err) 94 } 95 return nil 96 }