github.com/rstandt/terraform@v0.12.32-0.20230710220336-b1063613405c/backend/remote-state/etcdv2/client.go (about)

     1  package etcdv2
     2  
     3  import (
     4  	"context"
     5  	"crypto/md5"
     6  	"fmt"
     7  
     8  	etcdapi "github.com/coreos/etcd/client"
     9  	"github.com/hashicorp/terraform/state/remote"
    10  )
    11  
    12  // EtcdClient is a remote client that stores data in etcd.
    13  type EtcdClient struct {
    14  	Client etcdapi.Client
    15  	Path   string
    16  }
    17  
    18  func (c *EtcdClient) Get() (*remote.Payload, error) {
    19  	resp, err := etcdapi.NewKeysAPI(c.Client).Get(context.Background(), c.Path, &etcdapi.GetOptions{Quorum: true})
    20  	if err != nil {
    21  		if err, ok := err.(etcdapi.Error); ok && err.Code == etcdapi.ErrorCodeKeyNotFound {
    22  			return nil, nil
    23  		}
    24  		return nil, err
    25  	}
    26  	if resp.Node.Dir {
    27  		return nil, fmt.Errorf("path is a directory")
    28  	}
    29  
    30  	data := []byte(resp.Node.Value)
    31  	md5 := md5.Sum(data)
    32  	return &remote.Payload{
    33  		Data: data,
    34  		MD5:  md5[:],
    35  	}, nil
    36  }
    37  
    38  func (c *EtcdClient) Put(data []byte) error {
    39  	_, err := etcdapi.NewKeysAPI(c.Client).Set(context.Background(), c.Path, string(data), nil)
    40  	return err
    41  }
    42  
    43  func (c *EtcdClient) Delete() error {
    44  	_, err := etcdapi.NewKeysAPI(c.Client).Delete(context.Background(), c.Path, nil)
    45  	return err
    46  }