/
remote_tfe.go
66 lines (56 loc) · 1.6 KB
/
remote_tfe.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package tfstate
import (
"context"
"io"
"net/http"
"os"
tfe "github.com/hashicorp/go-tfe"
"github.com/pkg/errors"
)
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 {
return nil, errors.Errorf("failed to parse workspaces")
}
name, prefix := *strpe(workspaces["name"]), *strpe(workspaces["prefix"])
if name != "" {
return readTFE(ctx, hostname, organization, name, token)
}
if prefix != "" {
return readTFE(ctx, hostname, organization, prefix+ws, token)
}
return nil, errors.Errorf("workspaces requires either name or prefix")
}
func readTFE(ctx context.Context, hostname string, organization string, ws string, token string) (io.ReadCloser, error) {
var address string
address = tfe.DefaultAddress
if hostname != "" {
address = "https://" + hostname
}
var client *tfe.Client
client, err := tfe.NewClient(&tfe.Config{
Address: address,
Token: token,
})
if err != nil {
return nil, err
}
workspace, err := client.Workspaces.Read(ctx, organization, ws)
if err != nil {
return nil, err
}
state, err := client.StateVersions.ReadCurrent(ctx, workspace.ID)
if err != nil {
return nil, err
}
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)
}