-
Notifications
You must be signed in to change notification settings - Fork 787
/
vault_selector.go
84 lines (72 loc) · 2.36 KB
/
vault_selector.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
package vault
import (
"errors"
"fmt"
"github.com/jenkins-x/jx/v2/pkg/vault"
"github.com/banzaicloud/bank-vaults/operator/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/v2/pkg/util"
"k8s.io/client-go/kubernetes"
)
// Selector is an interface for selecting a vault from the installed ones on the platform
// It should pick the most logical one, or give the user a way of picking a vault if there are multiple installed
type Selector interface {
GetVault(name string, namespace string, useIngressURL bool) (*vault.Vault, error)
}
type vaultSelector struct {
vaultOperatorClient versioned.Interface
kubeClient kubernetes.Interface
Handles util.IOFileHandles
}
// NewVaultSelector creates a new vault selector
func NewVaultSelector(o OptionsInterface) (Selector, error) {
operator, err := o.VaultOperatorClient()
if err != nil {
return nil, err
}
kubeClient, _, err := o.KubeClientAndNamespace()
if err != nil {
return nil, err
}
v := &vaultSelector{
vaultOperatorClient: operator,
kubeClient: kubeClient,
Handles: o.GetIOFileHandles(),
}
return v, nil
}
// GetVault retrieve the given vault by name
func (v *vaultSelector) GetVault(name string, namespace string, useIngressURL bool) (*vault.Vault, error) {
vaults, err := GetVaults(v.kubeClient, v.vaultOperatorClient, namespace, useIngressURL)
if err != nil {
return nil, err
}
if name != "" {
// Return the vault that the user wanted (or an error if it doesn't exist)
for _, v := range vaults {
if v.Name == name {
return v, nil
}
}
return nil, errors.New(fmt.Sprintf("vault '%s' not found in namespace '%s'", name, namespace))
}
if len(vaults) == 0 {
return nil, errors.New(fmt.Sprintf("no vaults found in namespace '%s'", namespace))
}
if len(vaults) > 1 { // Get the user to select the vault from the list
return v.selectVault(vaults)
}
// If there is only one vault, return that one
return vaults[0], nil
}
func (v *vaultSelector) selectVault(vaults []*vault.Vault) (*vault.Vault, error) {
vaultMap, vaultNames := make(map[string]*vault.Vault, len(vaults)), make([]string, len(vaults))
for i, vault := range vaults {
vaultMap[vault.Name] = vault
vaultNames[i] = vault.Name
}
vaultName, err := util.PickName(vaultNames, "Select Vault:", "", v.Handles)
if err != nil {
return nil, err
}
return vaultMap[vaultName], nil
}