-
Notifications
You must be signed in to change notification settings - Fork 26
/
data_current_space.go
71 lines (58 loc) · 2.19 KB
/
data_current_space.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
67
68
69
70
71
package spacelift
import (
"context"
"path"
"strings"
"github.com/dgrijalva/jwt-go/v4"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/pkg/errors"
"github.com/spacelift-io/terraform-provider-spacelift/spacelift/internal"
"github.com/spacelift-io/terraform-provider-spacelift/spacelift/internal/structs"
)
func dataCurrentSpace() *schema.Resource {
return &schema.Resource{
Description: "" +
"`spacelift_current_space` is a data source that provides information " +
"about the space that an administrative stack is in if the run is executed within " +
"Spacelift by a stack or module. This makes it easier to create resources " +
"within the same space.",
ReadContext: dataCurrentSpaceRead,
}
}
func dataCurrentSpaceRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var claims jwt.StandardClaims
_, _, err := (&jwt.Parser{}).ParseUnverified(meta.(*internal.Client).Token, &claims)
if err != nil {
// Don't care about validation errors, we don't actually validate those
// tokens, we only parse them.
var unverifiable *jwt.UnverfiableTokenError
if !errors.As(err, &unverifiable) {
return diag.Errorf("could not parse client token: %v", err)
}
}
if issuer := claims.Issuer; issuer != "spacelift" {
return diag.Errorf("unexpected token issuer %s, is this a Spacelift run?", issuer)
}
stackID, _ := path.Split(claims.Subject)
var query struct {
Stack *structs.Stack `graphql:"stack(id: $id)"`
Module *structs.Module `graphql:"module(id: $id)"`
}
variables := map[string]interface{}{"id": toID(strings.TrimRight(stackID, "/"))}
if err := meta.(*internal.Client).Query(ctx, "StackRead", &query, variables); err != nil {
if strings.Contains(err.Error(), "denied") {
return diag.Errorf("could not query for stack: %v, is this stack administrative?", err)
}
return diag.Errorf("could not query for stack: %v", err)
}
if stack := query.Stack; stack != nil {
d.SetId(stack.Space)
return nil
}
if module := query.Module; module != nil {
d.SetId(module.Space)
return nil
}
return diag.Errorf("could not find stack or module with ID %s", stackID)
}