diff --git a/tfstate/lookup.go b/tfstate/lookup.go index 0ff8836..a8875ae 100644 --- a/tfstate/lookup.go +++ b/tfstate/lookup.go @@ -187,7 +187,7 @@ func ReadURL(ctx context.Context, loc string) (*TFState, error) { src, err = os.Open(u.Path) case "remote": split := strings.Split(u.Path, "/") - src, err = readTFE(ctx, u.Host, split[1], split[2], "") + src, err = readTFE(ctx, u.Host, split[1], split[2], os.Getenv("TFE_TOKEN")) case "": return ReadFile(ctx, u.Path) default: diff --git a/tfstate/remote_http.go b/tfstate/remote_http.go index 63a00f4..c44fba8 100644 --- a/tfstate/remote_http.go +++ b/tfstate/remote_http.go @@ -11,6 +11,13 @@ func readHTTP(ctx context.Context, u string) (io.ReadCloser, error) { if err != nil { return nil, err } + return readHTTPWithRequest(ctx, req) +} + +func readHTTPWithRequest(ctx context.Context, req *http.Request) (io.ReadCloser, error) { + if c := req.Context(); c != ctx { + req = req.WithContext(ctx) + } resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err diff --git a/tfstate/remote_tfe.go b/tfstate/remote_tfe.go index f779f6f..7d9816a 100644 --- a/tfstate/remote_tfe.go +++ b/tfstate/remote_tfe.go @@ -3,6 +3,8 @@ package tfstate import ( "context" "io" + "net/http" + "os" tfe "github.com/hashicorp/go-tfe" "github.com/pkg/errors" @@ -10,6 +12,9 @@ import ( func readTFEState(ctx context.Context, config map[string]interface{}, ws string) (io.ReadCloser, error) { hostname, organization, token := *strpe(config["hostname"]), *strp(config["organization"]), *strpe(config["token"]) + if token == "" { + token = os.Getenv("TFE_TOKEN") + } workspaces, ok := config["workspaces"].(map[string]interface{}) if !ok { @@ -35,18 +40,11 @@ func readTFE(ctx context.Context, hostname string, organization string, ws strin address = "https://" + hostname } - var err error var client *tfe.Client - if token != "" { - client, err = tfe.NewClient(&tfe.Config{ - Address: address, - Token: token, - }) - } else { - client, err = tfe.NewClient(&tfe.Config{ - Address: address, - }) - } + client, err := tfe.NewClient(&tfe.Config{ + Address: address, + Token: token, + }) if err != nil { return nil, err } @@ -59,6 +57,10 @@ func readTFE(ctx context.Context, hostname string, organization string, ws strin if err != nil { return nil, err } - - return readHTTP(ctx, state.DownloadURL) + req, err := http.NewRequest(http.MethodGet, state.DownloadURL, nil) + if err != nil { + return nil, err + } + req.Header.Add("Authorization", "Bearer "+token) + return readHTTPWithRequest(ctx, req) }