github.com/i0n/terraform@v0.4.3-0.20150506151324-010a39a58ec1/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  	if scheme, ok := conf["scheme"]; ok && scheme != "" {
    24  		config.Scheme = scheme
    25  	}
    26  
    27  	client, err := consulapi.NewClient(config)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  
    32  	return &ConsulClient{
    33  		Client: client,
    34  		Path:   path,
    35  	}, nil
    36  }
    37  
    38  // ConsulClient is a remote client that stores data in Consul.
    39  type ConsulClient struct {
    40  	Client *consulapi.Client
    41  	Path   string
    42  }
    43  
    44  func (c *ConsulClient) Get() (*Payload, error) {
    45  	pair, _, err := c.Client.KV().Get(c.Path, nil)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	if pair == nil {
    50  		return nil, nil
    51  	}
    52  
    53  	md5 := md5.Sum(pair.Value)
    54  	return &Payload{
    55  		Data: pair.Value,
    56  		MD5:  md5[:],
    57  	}, nil
    58  }
    59  
    60  func (c *ConsulClient) Put(data []byte) error {
    61  	kv := c.Client.KV()
    62  	_, err := kv.Put(&consulapi.KVPair{
    63  		Key:   c.Path,
    64  		Value: data,
    65  	}, nil)
    66  	return err
    67  }
    68  
    69  func (c *ConsulClient) Delete() error {
    70  	kv := c.Client.KV()
    71  	_, err := kv.Delete(c.Path, nil)
    72  	return err
    73  }