github.com/jgadling/terraform@v0.3.8-0.20150227214559-abd68c2c87bc/state/remote/consul.go (about)

     1  package remote
     2  
     3  import (
     4  	"crypto/md5"
     5  	"fmt"
     6  
     7  	consulapi "github.com/hashicorp/consul/api"
     8  )
     9  
    10  func consulFactory(conf map[string]string) (Client, error) {
    11  	path, ok := conf["path"]
    12  	if !ok {
    13  		return nil, fmt.Errorf("missing 'path' configuration")
    14  	}
    15  
    16  	config := consulapi.DefaultConfig()
    17  	if token, ok := conf["access_token"]; ok && token != "" {
    18  		config.Token = token
    19  	}
    20  	if addr, ok := conf["address"]; ok && addr != "" {
    21  		config.Address = addr
    22  	}
    23  
    24  	client, err := consulapi.NewClient(config)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  
    29  	return &ConsulClient{
    30  		Client: client,
    31  		Path:   path,
    32  	}, nil
    33  }
    34  
    35  // ConsulClient is a remote client that stores data in Consul.
    36  type ConsulClient struct {
    37  	Client *consulapi.Client
    38  	Path   string
    39  }
    40  
    41  func (c *ConsulClient) Get() (*Payload, error) {
    42  	pair, _, err := c.Client.KV().Get(c.Path, nil)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	if pair == nil {
    47  		return nil, nil
    48  	}
    49  
    50  	md5 := md5.Sum(pair.Value)
    51  	return &Payload{
    52  		Data: pair.Value,
    53  		MD5:  md5[:],
    54  	}, nil
    55  }
    56  
    57  func (c *ConsulClient) Put(data []byte) error {
    58  	kv := c.Client.KV()
    59  	_, err := kv.Put(&consulapi.KVPair{
    60  		Key:   c.Path,
    61  		Value: data,
    62  	}, nil)
    63  	return err
    64  }
    65  
    66  func (c *ConsulClient) Delete() error {
    67  	kv := c.Client.KV()
    68  	_, err := kv.Delete(c.Path, nil)
    69  	return err
    70  }