github.com/erriapo/terraform@v0.6.12-0.20160203182612-0340ea72354f/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{username, password}
    37  	}
    38  
    39  	client, err := consulapi.NewClient(config)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	return &ConsulClient{
    45  		Client: client,
    46  		Path:   path,
    47  	}, nil
    48  }
    49  
    50  // ConsulClient is a remote client that stores data in Consul.
    51  type ConsulClient struct {
    52  	Client *consulapi.Client
    53  	Path   string
    54  }
    55  
    56  func (c *ConsulClient) Get() (*Payload, error) {
    57  	pair, _, err := c.Client.KV().Get(c.Path, nil)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	if pair == nil {
    62  		return nil, nil
    63  	}
    64  
    65  	md5 := md5.Sum(pair.Value)
    66  	return &Payload{
    67  		Data: pair.Value,
    68  		MD5:  md5[:],
    69  	}, nil
    70  }
    71  
    72  func (c *ConsulClient) Put(data []byte) error {
    73  	kv := c.Client.KV()
    74  	_, err := kv.Put(&consulapi.KVPair{
    75  		Key:   c.Path,
    76  		Value: data,
    77  	}, nil)
    78  	return err
    79  }
    80  
    81  func (c *ConsulClient) Delete() error {
    82  	kv := c.Client.KV()
    83  	_, err := kv.Delete(c.Path, nil)
    84  	return err
    85  }