From e3b20c350898bfa2524e6f07a9e4d4d0f2ae6368 Mon Sep 17 00:00:00 2001 From: Ben Slusky Date: Thu, 19 Jan 2017 21:01:38 -0500 Subject: [PATCH] Basic authentication for HTTP remote state backend --- state/remote/http.go | 38 ++++++++++++++++--- website/source/docs/state/remote/http.html.md | 2 + 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/state/remote/http.go b/state/remote/http.go index ff8fdaa5f..3ffac59dd 100644 --- a/state/remote/http.go +++ b/state/remote/http.go @@ -44,20 +44,40 @@ func httpFactory(conf map[string]string) (Client, error) { } } - return &HTTPClient{ + ret := &HTTPClient{ URL: url, Client: client, - }, nil + } + if username, ok := conf["username"]; ok && username != "" { + ret.Username = username + } + if password, ok := conf["password"]; ok && password != "" { + ret.Password = password + } + return ret, nil } // HTTPClient is a remote client that stores data in Consul or HTTP REST. type HTTPClient struct { - URL *url.URL - Client *http.Client + URL *url.URL + Client *http.Client + Username string + Password string } func (c *HTTPClient) Get() (*Payload, error) { - resp, err := c.Client.Get(c.URL.String()) + req, err := http.NewRequest("GET", c.URL.String(), nil) + if err != nil { + return nil, err + } + + // Prepare the request + if c.Username != "" { + req.SetBasicAuth(c.Username, c.Password) + } + + // Make the request + resp, err := c.Client.Do(req) if err != nil { return nil, err } @@ -141,6 +161,9 @@ func (c *HTTPClient) Put(data []byte) error { req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-MD5", b64) req.ContentLength = int64(len(data)) + if c.Username != "" { + req.SetBasicAuth(c.Username, c.Password) + } // Make the request resp, err := c.Client.Do(req) @@ -164,6 +187,11 @@ func (c *HTTPClient) Delete() error { return fmt.Errorf("Failed to make HTTP request: %s", err) } + // Prepare the request + if c.Username != "" { + req.SetBasicAuth(c.Username, c.Password) + } + // Make the request resp, err := c.Client.Do(req) if err != nil { diff --git a/website/source/docs/state/remote/http.html.md b/website/source/docs/state/remote/http.html.md index de23b5f5c..9c03185b9 100644 --- a/website/source/docs/state/remote/http.html.md +++ b/website/source/docs/state/remote/http.html.md @@ -36,5 +36,7 @@ data "terraform_remote_state" "foo" { The following configuration options are supported: * `address` - (Required) The address of the REST endpoint + * `username` - (Optional) The username for HTTP basic authentication + * `password` - (Optional) The password for HTTP basic authentication * `skip_cert_verification` - (Optional) Whether to skip TLS verification. Defaults to `false`.