github.com/pmcatominey/terraform@v0.7.0-rc2.0.20160708105029-1401a52a5cc5/state/remote/consul.go (about) 1 package remote 2 3 import ( 4 "crypto/md5" 5 "fmt" 6 "strings" 7 8 consulapi "github.com/hashicorp/consul/api" 9 ) 10 11 func consulFactory(conf map[string]string) (Client, error) { 12 path, ok := conf["path"] 13 if !ok { 14 return nil, fmt.Errorf("missing 'path' configuration") 15 } 16 17 config := consulapi.DefaultConfig() 18 if token, ok := conf["access_token"]; ok && token != "" { 19 config.Token = token 20 } 21 if addr, ok := conf["address"]; ok && addr != "" { 22 config.Address = addr 23 } 24 if scheme, ok := conf["scheme"]; ok && scheme != "" { 25 config.Scheme = scheme 26 } 27 if auth, ok := conf["http_auth"]; ok && auth != "" { 28 var username, password string 29 if strings.Contains(auth, ":") { 30 split := strings.SplitN(auth, ":", 2) 31 username = split[0] 32 password = split[1] 33 } else { 34 username = auth 35 } 36 config.HttpAuth = &consulapi.HttpBasicAuth{ 37 Username: username, 38 Password: password, 39 } 40 } 41 42 client, err := consulapi.NewClient(config) 43 if err != nil { 44 return nil, err 45 } 46 47 return &ConsulClient{ 48 Client: client, 49 Path: path, 50 }, nil 51 } 52 53 // ConsulClient is a remote client that stores data in Consul. 54 type ConsulClient struct { 55 Client *consulapi.Client 56 Path string 57 } 58 59 func (c *ConsulClient) Get() (*Payload, error) { 60 pair, _, err := c.Client.KV().Get(c.Path, nil) 61 if err != nil { 62 return nil, err 63 } 64 if pair == nil { 65 return nil, nil 66 } 67 68 md5 := md5.Sum(pair.Value) 69 return &Payload{ 70 Data: pair.Value, 71 MD5: md5[:], 72 }, nil 73 } 74 75 func (c *ConsulClient) Put(data []byte) error { 76 kv := c.Client.KV() 77 _, err := kv.Put(&consulapi.KVPair{ 78 Key: c.Path, 79 Value: data, 80 }, nil) 81 return err 82 } 83 84 func (c *ConsulClient) Delete() error { 85 kv := c.Client.KV() 86 _, err := kv.Delete(c.Path, nil) 87 return err 88 }