Read environment variables for VAULT_HTTP_ADDR and VAULT_TOKEN

This commit is contained in:
Seth Vargo
2015-04-23 11:43:20 -04:00
parent 747529b140
commit aa94080ad8
2 changed files with 42 additions and 2 deletions

View File

@@ -6,6 +6,7 @@ import (
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
"net/url" "net/url"
"os"
"time" "time"
vaultHttp "github.com/hashicorp/vault/http" vaultHttp "github.com/hashicorp/vault/http"
@@ -39,6 +40,10 @@ func DefaultConfig() *Config {
HttpClient: &http.Client{}, HttpClient: &http.Client{},
} }
if addr := os.Getenv("VAULT_HTTP_ADDR"); addr != "" {
config.Address = addr
}
return config return config
} }
@@ -75,10 +80,16 @@ func NewClient(c *Config) (*Client, error) {
return errRedirect return errRedirect
} }
return &Client{ client := &Client{
addr: u, addr: u,
config: c, config: c,
}, nil }
if token := os.Getenv("VAULT_TOKEN"); token != "" {
client.SetToken(token)
}
return client, nil
} }
// Token returns the access token being used by this client. It will // Token returns the access token being used by this client. It will

View File

@@ -4,12 +4,41 @@ import (
"bytes" "bytes"
"io" "io"
"net/http" "net/http"
"os"
"testing" "testing"
"time" "time"
vaultHttp "github.com/hashicorp/vault/http" vaultHttp "github.com/hashicorp/vault/http"
) )
func init() {
// Ensure our special envvars are not present
os.Setenv("VAULT_HTTP_ADDR", "")
os.Setenv("VAULT_TOKEN", "")
}
func TestDefaultConfig_envvar(t *testing.T) {
os.Setenv("VAULT_HTTP_ADDR", "https://vault.mycompany.com")
defer os.Setenv("VAULT_HTTP_ADDR", "")
config := DefaultConfig()
if config.Address != "https://vault.mycompany.com" {
t.Fatalf("bad: %s", config.Address)
}
os.Setenv("VAULT_TOKEN", "testing")
defer os.Setenv("VAULT_TOKEN", "")
client, err := NewClient(config)
if err != nil {
t.Fatalf("err: %s", err)
}
if token := client.Token(); token != "testing" {
t.Fatalf("bad: %s", token)
}
}
func TestClientToken(t *testing.T) { func TestClientToken(t *testing.T) {
tokenValue := "foo" tokenValue := "foo"
handler := func(w http.ResponseWriter, req *http.Request) { handler := func(w http.ResponseWriter, req *http.Request) {