make ConfigMap collector namespace-optional (#1212)

* try to load default namespace from kubectl current context

* use  ns from kubectl context when no ns is given in the spec

* remove test prints

* Update pkg/collect/configmap.go

Co-authored-by: Diamon Wiggins <38189728+diamonwiggins@users.noreply.github.com>

---------

Co-authored-by: Diamon Wiggins <38189728+diamonwiggins@users.noreply.github.com>
This commit is contained in:
ada mancini
2023-06-13 13:12:17 -04:00
committed by GitHub
parent a5628874b0
commit 03c53cabd6
2 changed files with 36 additions and 1 deletions

View File

@@ -10,11 +10,13 @@ import (
"github.com/pkg/errors"
troubleshootv1beta2 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta2"
"github.com/replicatedhq/troubleshoot/pkg/k8sutil"
corev1 "k8s.io/api/core/v1"
kuberneteserrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
)
type ConfigMapOutput struct {
@@ -49,8 +51,20 @@ func (c *CollectConfigMap) Collect(progressChan chan<- interface{}) (CollectorRe
output := NewResult()
configMaps := []corev1.ConfigMap{}
namespace := c.Collector.Namespace
if c.Collector.Name != "" {
configMap, err := c.Client.CoreV1().ConfigMaps(c.Collector.Namespace).Get(c.Context, c.Collector.Name, metav1.GetOptions{})
if namespace == "" {
kubeconfig := k8sutil.GetKubeconfig()
ns, _, err := kubeconfig.Namespace()
klog.V(2).Infof("no namespace was set for configmap '%s': using namespace '%s' from current kubeconfig context", c.Collector.Name, ns)
if err != nil {
return nil, errors.Wrapf(err, "a namespace was not specified for configmap '%s' and could not be discovered from kubeconfig", c.Collector.Name)
}
namespace = ns
}
klog.V(1).Infof("looking for configmap '%s' in namespace '%s'", c.Collector.Name, namespace)
configMap, err := c.Client.CoreV1().ConfigMaps(namespace).Get(c.Context, c.Collector.Name, metav1.GetOptions{})
if err != nil {
if kuberneteserrors.IsNotFound(err) {
filePath, encoded, err := configMapToOutput(c.Collector, nil, c.Collector.Name)

21
testdata/supportbundle/configmaps.yaml vendored Normal file
View File

@@ -0,0 +1,21 @@
apiVersion: troubleshoot.sh/v1beta2
kind: SupportBundle
metadata:
name: example-collect-all-configmap-data
spec:
collectors:
- configMap:
name: kube-root-ca.crt
# expected in default namespace
- configMap:
name: cluster-info
# missing namespace parameter
- configMap:
name: does-not-exist
- configMap:
selector:
- app=kube-proxy
# only selector set
- configMap:
name: coredns
namespace: kube-system