forked from tuenti/secrets-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
164 lines (143 loc) · 6.43 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package main
import (
"context"
"flag"
"fmt"
"os"
"strings"
"time"
secretsmanagerv1alpha1 "github.com/tuenti/secrets-manager/api/v1alpha1"
"github.com/tuenti/secrets-manager/backend"
"github.com/tuenti/secrets-manager/controllers"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
// +kubebuilder:scaffold:imports
)
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
corev1.AddToScheme(scheme)
secretsmanagerv1alpha1.AddToScheme(scheme)
// +kubebuilder:scaffold:scheme
}
// To be filled from build ldflags
var version string
func main() {
var metricsAddr string
var controllerName string
var enableLeaderElection bool
var enableDebugLog bool
var versionFlag bool
var reconcilePeriod time.Duration
var selectedBackend string
var watchNamespaces string
var excludeNamespaces string
var mgr ctrl.Manager
var namespaceList []string
backendCfg := backend.Config{}
flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&controllerName, "controller-name", "SecretDefinition", "If running secrets manager in multiple namespaces, set the controller name to something unique avoid 'duplicate metrics collector registration attempted' errors.")
flag.BoolVar(&enableLeaderElection, "enable-leader-election", false,
"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.")
flag.StringVar(&selectedBackend, "backend", "vault", "Selected backend. Only vault supported")
flag.BoolVar(&enableDebugLog, "enable-debug-log", false, "Enable this to get more logs verbosity and debug messages.")
flag.BoolVar(&versionFlag, "version", false, "Display Secret Manager version")
flag.DurationVar(&reconcilePeriod, "reconcile-period", 5*time.Second, "How often the controller will re-queue secretdefinition events")
flag.DurationVar(&backendCfg.BackendTimeout, "config.backend-timeout", 5*time.Second, "Backend connection timeout")
flag.StringVar(&backendCfg.VaultURL, "vault.url", "https://127.0.0.1:8200", "Vault address. VAULT_ADDR environment would take precedence.")
flag.StringVar(&backendCfg.VaultAuthMethod, "vault.auth-method", "approle", "Vault authentication method. Supported: approle, kubernetes.")
flag.StringVar(&backendCfg.VaultRoleID, "vault.role-id", "", "Vault approle role id. VAULT_ROLE_ID environment would take precedence.")
flag.StringVar(&backendCfg.VaultSecretID, "vault.secret-id", "", "Vault approle secret id. VAULT_SECRET_ID environment would take precedence.")
flag.StringVar(&backendCfg.VaultKubernetesRole, "vault.kubernetes-role", "", "Vault kubernetes role name.")
flag.Int64Var(&backendCfg.VaultMaxTokenTTL, "vault.max-token-ttl", 300, "Max seconds to consider a token expired.")
flag.DurationVar(&backendCfg.VaultTokenPollingPeriod, "vault.token-polling-period", 15*time.Second, "Polling interval to check token expiration time.")
flag.IntVar(&backendCfg.VaultRenewTTLIncrement, "vault.renew-ttl-increment", 600, "TTL time for renewed token.")
flag.StringVar(&backendCfg.VaultEngine, "vault.engine", "kv2", "Vault secret engine. Only KV version 1 and 2 supported")
flag.StringVar(&backendCfg.VaultApprolePath, "vault.approle-path", "approle", "Vault approle login path")
flag.StringVar(&backendCfg.VaultKubernetesPath, "vault.kubernetes-path", "kubernetes", "Vault kubernetes login path")
flag.StringVar(&watchNamespaces, "watch-namespaces", "", "Comma separated list of namespaces that secrets-manager will watch for SecretDefinitions. By default all namespaces are watched.")
flag.StringVar(&excludeNamespaces, "exclude-namespaces", "", "Comma separated list of namespaces that secrets-manager will not watch for SecretDefinitions. By default all namespaces are watched.")
flag.Parse()
if versionFlag {
fmt.Printf("Secrets Manager %s\n", version)
os.Exit(0)
}
logger := zap.Logger(enableDebugLog).WithName("backend")
if os.Getenv("VAULT_ADDR") != "" {
backendCfg.VaultURL = os.Getenv("VAULT_ADDR")
}
if os.Getenv("VAULT_ROLE_ID") != "" {
backendCfg.VaultRoleID = os.Getenv("VAULT_ROLE_ID")
}
if os.Getenv("VAULT_SECRET_ID") != "" {
backendCfg.VaultSecretID = os.Getenv("VAULT_SECRET_ID")
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
backendClient, err := backend.NewBackendClient(ctx, selectedBackend, logger, backendCfg)
if err != nil {
logger.Error(err, "could not build backend client")
os.Exit(1)
}
ctrl.SetLogger(zap.Logger(enableDebugLog))
nsSlice := func(ns string) []string {
trimmed := strings.Trim(strings.TrimSpace(ns), "\"")
return strings.Split(trimmed, ",")
}
excludeNs := make(map[string]bool)
if len(excludeNamespaces) > 0 {
for _, ns := range nsSlice(excludeNamespaces) {
excludeNs[ns] = true
}
}
if len(strings.TrimSpace(watchNamespaces)) > 0 {
logger.Info("setting restricted namespace list for controller")
namespaceList = nsSlice(watchNamespaces)
logger.Info("watching namespaces: " + watchNamespaces)
mgr, err = ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
LeaderElection: enableLeaderElection,
NewCache: cache.MultiNamespacedCacheBuilder(namespaceList),
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
} else {
mgr, err = ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
LeaderElection: enableLeaderElection,
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
}
err = (&controllers.SecretDefinitionReconciler{
Backend: *backendClient,
Client: mgr.GetClient(),
APIReader: mgr.GetAPIReader(),
Log: ctrl.Log.WithName("controllers").WithName(controllerName),
Ctx: ctx,
ReconciliationPeriod: reconcilePeriod,
ExcludeNamespaces: excludeNs,
}).SetupWithManager(mgr, controllerName)
if err != nil {
setupLog.Error(err, "unable to create controller", "controller", controllerName)
os.Exit(1)
}
// +kubebuilder:scaffold:builder
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}