github.com/ns1/terraform@v0.7.10-0.20161109153551-8949419bef40/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 datacenter, ok := conf["datacenter"]; ok && datacenter != "" {
    28  		config.Datacenter = datacenter
    29  	}
    30  	if auth, ok := conf["http_auth"]; ok && auth != "" {
    31  		var username, password string
    32  		if strings.Contains(auth, ":") {
    33  			split := strings.SplitN(auth, ":", 2)
    34  			username = split[0]
    35  			password = split[1]
    36  		} else {
    37  			username = auth
    38  		}
    39  		config.HttpAuth = &consulapi.HttpBasicAuth{
    40  			Username: username,
    41  			Password: password,
    42  		}
    43  	}
    44  
    45  	client, err := consulapi.NewClient(config)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	return &ConsulClient{
    51  		Client: client,
    52  		Path:   path,
    53  	}, nil
    54  }
    55  
    56  // ConsulClient is a remote client that stores data in Consul.
    57  type ConsulClient struct {
    58  	Client *consulapi.Client
    59  	Path   string
    60  }
    61  
    62  func (c *ConsulClient) Get() (*Payload, error) {
    63  	pair, _, err := c.Client.KV().Get(c.Path, nil)
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  	if pair == nil {
    68  		return nil, nil
    69  	}
    70  
    71  	md5 := md5.Sum(pair.Value)
    72  	return &Payload{
    73  		Data: pair.Value,
    74  		MD5:  md5[:],
    75  	}, nil
    76  }
    77  
    78  func (c *ConsulClient) Put(data []byte) error {
    79  	kv := c.Client.KV()
    80  	_, err := kv.Put(&consulapi.KVPair{
    81  		Key:   c.Path,
    82  		Value: data,
    83  	}, nil)
    84  	return err
    85  }
    86  
    87  func (c *ConsulClient) Delete() error {
    88  	kv := c.Client.KV()
    89  	_, err := kv.Delete(c.Path, nil)
    90  	return err
    91  }