-
Notifications
You must be signed in to change notification settings - Fork 24
/
provide.go
81 lines (68 loc) · 1.97 KB
/
provide.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
72
73
74
75
76
77
78
79
80
81
package secretmanager
import (
"context"
"fmt"
"os"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
agentinfo "github.com/fluxninja/aperture/v2/pkg/agent-info"
"github.com/fluxninja/aperture/v2/pkg/utils"
"go.uber.org/fx"
"golang.org/x/oauth2/google"
)
// Module is a fx module that provides secret manager instance.
func Module() fx.Option {
return fx.Options(
fx.Provide(
provideSecretManagerClient,
),
)
}
// SecretManagerClientIn holds parameters for provideSecretManagerClient.
type SecretManagerClientIn struct {
fx.In
Shutdowner fx.Shutdowner
Lifecycle fx.Lifecycle
InstallationModeConfig *agentinfo.InstallationModeConfig `optional:"true"`
}
// SecretManagerClient is a wrapper around secretmanager.Client.
type SecretManagerClient struct {
Client *secretmanager.Client
GCPProjectID string
ProjectID string
}
func provideSecretManagerClient(in SecretManagerClientIn) (*SecretManagerClient, error) {
if in.InstallationModeConfig == nil || in.InstallationModeConfig.InstallationMode != utils.InstallationModeCloudAgent {
return nil, nil
}
ctx, cancel := context.WithCancel(context.Background())
client, err := secretmanager.NewClient(ctx)
if err != nil {
defer cancel()
return nil, fmt.Errorf("failed to create secretmanager client: %v", err)
}
creds, err := google.FindDefaultCredentials(ctx)
if err != nil || creds.ProjectID == "" {
defer cancel()
return nil, fmt.Errorf("failed to get default credentials: %v", err)
}
projectID := os.Getenv("PROJECT_ID")
if projectID == "" {
defer cancel()
return nil, fmt.Errorf("PROJECT_ID environment variable is not set")
}
secretManagerClient := &SecretManagerClient{
Client: client,
GCPProjectID: creds.ProjectID,
ProjectID: projectID,
}
in.Lifecycle.Append(fx.Hook{
OnStart: func(context.Context) error {
return nil
},
OnStop: func(context.Context) error {
cancel()
return client.Close()
},
})
return secretManagerClient, nil
}