get

package
v1.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2026 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var GetAllCmd = &cobra.Command{
	Use:     "all",
	Aliases: []string{"a"},
	Args:    cobra.NoArgs,
	Short:   "Get all k8s resources",
	Long: `This command does what 'kubectl get all' is supposed to do:
It gets ALL k8s resources.

Use the --scope flag to control if you want to get namespace- or cluster-scoped resources (or both).

Examples:

	> kpu get all
	Lists all namespace-scoped resources in the default namespace.

	> kpu get all --scope cluster
	Lists all cluster-scoped resources.
`,
	Run: func(cmd *cobra.Command, args []string) {
		ValidateGetAllCommand()

		k, err := utils.LoadKubeconfigWithImpersonation(k8sOptions.KubeconfigPath, k8sOptions.ImpersonationConfig)
		if err != nil {
			utils.Fatal(1, "error loading kubeconfig: %s", err.Error())
		}

		objects := utils.NewUnstructuredList()
		var errs []error
		objects.Items, errs = k.GetAllResources(cmd.Context(), scope, k8sOptions)

		if !suppressWarnings && len(errs) > 0 {
			for _, e := range errs {
				fmt.Fprintf(os.Stderr, "warning: %s\n", e.Error())
			}
		}

		if !showManagedFields && output != utils.OUTPUT_TEXT {

			for i := range objects.Items {
				obj := &objects.Items[i]
				obj.SetManagedFields(nil)
			}
		}

		printUnstructuredObjects(output, objects)
	},
}

GetAllCmd represents the 'get all' command

View Source
var GetCmd = &cobra.Command{
	Use:     "get",
	Aliases: []string{"g"},
	Short:   "Get k8s resources",
	Long:    `A collection of enhanced 'kubectl get' commands.`,
	GroupID: cmdgroups.ClusterInteraction,
}

GetCmd represents the get command

View Source
var GetPermissionsCmd = &cobra.Command{
	Use:     "permissions",
	Aliases: []string{"permission", "perms", "perm", "p"},
	Args:    cobra.NoArgs,
	Short:   "Get the permissions of the current user",
	Long: `Get the permissions of the current user.

This command uses the SelfSubjectRulesReview API to determine the permissions of the current user and prints them.

Examples:

	> kpu get permissions
	Returns all permissions the current user has for the default namespace, formatted as a table.

	> kpu get permissions -A -o json
	Returns all permissions the current user has for all namespaces, formatted as JSON.

	> kpu get permissions -n foo --as my-user
	Returns all permissions the user 'my-user' has for the namespace 'foo', formatted as a table.
`,
	Run: func(cmd *cobra.Command, args []string) {
		k, err := utils.LoadKubeconfigWithImpersonation(k8sOptions.KubeconfigPath, k8sOptions.ImpersonationConfig)
		if err != nil {
			utils.Fatal(1, "error loading kubeconfig: %s", err.Error())
		}

		ssrr := &authzv1.SelfSubjectRulesReview{
			Spec: authzv1.SelfSubjectRulesReviewSpec{},
		}
		if k8sOptions.AllNamespaces {
			ssrr.Spec.Namespace = "*"
		} else if k8sOptions.Namespace != "" {
			ssrr.Spec.Namespace = k8sOptions.Namespace
		} else {
			ssrr.Spec.Namespace = k.DefaultNamespace
		}
		namespace := ssrr.Spec.Namespace
		ssrr.SetName("kpu-get-permissions")
		if err := k.Create(cmd.Context(), ssrr); err != nil {
			utils.Fatal(1, "error creating SelfSubjectRulesReview: %s", err.Error())
		}

		switch output {
		case utils.OUTPUT_TEXT:
			if ssrr.Status.EvaluationError != "" {
				cmd.Printf("Error evaluating permissions: %s\n", ssrr.Status.EvaluationError)
			}
			cmd.Print("Permissions for resources in ")
			if namespace == "*" {
				cmd.Print("all namespaces")
			} else {
				cmd.Printf("namespace '%s'", namespace)
			}
			if ssrr.Status.Incomplete {
				cmd.Print(" [INCOMPLETE]")
			}
			cmd.Println(":")
			resPerms := dedimensionalizeResourceRules(ssrr.Status.ResourceRules)
			t := utils.NewOutputTable[resourcePermission]()
			t.WithColumn("API Group", func(obj resourcePermission) string { return obj.APIGroup })
			t.WithColumn("Resource", func(obj resourcePermission) string { return obj.Resource })
			t.WithColumn("Verbs", func(obj resourcePermission) string { return strings.Join(obj.Verbs, ", ") })
			t.WithColumn("Resource Names", func(obj resourcePermission) string { return shortenTo(strings.Join(obj.ResourceNames, ", "), 100) })
			t.WithData(resPerms...)
			cmd.Print(t.String())
		case utils.OUTPUT_JSON:
			data, err := json.MarshalIndent(ssrr, "", "  ")
			if err != nil {
				utils.Fatal(1, "error converting SelfSubjectRulesReview to json: %s", err.Error())
			}
			cmd.Println(string(data))
		case utils.OUTPUT_YAML:
			data, err := yaml.Marshal(ssrr)
			if err != nil {
				utils.Fatal(1, "error converting SelfSubjectRulesReview to yaml: %s", err.Error())
			}
			cmd.Println(string(data))
		}
	},
}

GetPermissionsCmd represents the 'get permissions' command

View Source
var GetResourceCmd = &cobra.Command{
	Use:     "resource",
	Aliases: []string{"res", "r"},
	Args:    cobra.MinimumNArgs(1),
	Short:   "Get the specified k8s resources",
	Long: `This is pretty similar to 'kubectl get' and mainly in here for debugging purposes.

Examples:

	> kpu get resource namespace foo -o yaml
	Returns the namespace 'foo' in yaml format.

	> kpu get resource pod,deployment -n foo -l example.org/mylabel
	Lists all pods and deployments in the namespace 'foo' with the label 'example.org/mylabel' (independent of the label value).
	`,
	Run: func(cmd *cobra.Command, args []string) {
		ValidateGetResourceCommand(args)

		resourceTypes := strings.Split(args[0], ",")
		var resourceNames []string
		if len(args) > 1 {
			resourceNames = []string{}
			for _, arg := range args[1:] {
				resourceNames = append(resourceNames, strings.Split(arg, ",")...)
			}
			resourceNames = slices.DeleteFunc(resourceNames, func(s string) bool { return s == "" })
		}

		k, err := utils.LoadKubeconfigWithImpersonation(k8sOptions.KubeconfigPath, k8sOptions.ImpersonationConfig)
		if err != nil {
			utils.Fatal(1, "error loading kubeconfig: %s", err.Error())
		}

		objects := utils.NewUnstructuredList()
		var errs []error
		objects.Items, errs = k.ListResources(cmd.Context(), resourceTypes, resourceNames, utils.SCOPE_ALL, k8sOptions)

		if err := errors.Join(errs...); err != nil {
			utils.Fatal(1, "error getting resources: %s", err.Error())
		}

		if !showManagedFields && output != utils.OUTPUT_TEXT {

			for i := range objects.Items {
				obj := &objects.Items[i]
				obj.SetManagedFields(nil)
			}
		}

		printUnstructuredObjects(output, objects)
	},
}

GetResourceCmd represents the 'get resource' command

View Source
var GetSecretCmd = &cobra.Command{
	Use:     "secret",
	Aliases: []string{"secrets", "sec", "s"},
	Args:    cobra.MinimumNArgs(0),
	Short:   "Get the specified secrets",
	Long: `Lists/gets secrets, but prints the plain-text 'stringData' field instead of the base64-encoded 'data' one.

Examples:

	> kpu get secret bar -n foo -o yaml
	Returns something like this:
		items:
		- apiVersion: v1
			kind: Secret
			metadata:
				creationTimestamp: "2024-07-12T15:35:30Z"
				name: bar
				namespace: foo
				resourceVersion: "2071574"
				uid: 74a0ef49-91d5-4391-b8f3-659d8fb443e2
			stringData:
				bar: baz
				foo: foobar
			type: Opaque
		metadata: {}
`,
	Run: func(cmd *cobra.Command, args []string) {
		ValidateGetSecretCommand(args)

		var resourceNames []string
		if len(args) > 0 {
			resourceNames = []string{}
			for _, arg := range args {
				resourceNames = append(resourceNames, strings.Split(arg, ",")...)
			}
			resourceNames = slices.DeleteFunc(resourceNames, func(s string) bool { return s == "" })
		}

		k, err := utils.LoadKubeconfigWithImpersonation(k8sOptions.KubeconfigPath, k8sOptions.ImpersonationConfig)
		if err != nil {
			utils.Fatal(1, "error loading kubeconfig: %s", err.Error())
		}

		objects := &corev1.SecretList{}
		if len(resourceNames) == 1 {
			sec := &corev1.Secret{}
			ns := k8sOptions.Namespace
			if ns == "" {
				ns = k.DefaultNamespace
			}
			if err := k.Get(cmd.Context(), types.NamespacedName{Name: resourceNames[0], Namespace: ns}, sec); err != nil {
				utils.Fatal(1, "error getting secret: %s", err.Error())
			}
			objects.Items = []corev1.Secret{*sec}
		} else {
			if err := k.List(cmd.Context(), objects, k.ConstructListOptions(k8sOptions)...); err != nil {
				utils.Fatal(1, "error listing secrets: %s", err.Error())
			}

			if len(resourceNames) > 0 {
				objects.Items = utils.FilterSlice(objects.Items, func(obj corev1.Secret) bool {
					return slices.Contains(resourceNames, obj.GetName())
				})
			}
		}

		for i := range objects.Items {
			obj := &objects.Items[i]
			if len(obj.Data) > 0 {
				obj.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret"))
				obj.StringData = make(map[string]string, len(obj.Data))
				for k, v := range obj.Data {
					obj.StringData[k] = string(v)
				}
				obj.Data = nil
			}
			if !showManagedFields && output != utils.OUTPUT_TEXT {

				obj.SetManagedFields(nil)
			}
		}

		switch output {
		case utils.OUTPUT_TEXT:
			t := utils.NewOutputTable[corev1.Secret]()
			if k8sOptions.AllNamespaces {
				t.WithColumn("namespace", func(obj corev1.Secret) string { return obj.GetNamespace() })
			}
			t.WithColumn("name", func(obj corev1.Secret) string { return obj.GetName() })
			t.WithData(objects.Items...)
			fmt.Print(t.String())
		case utils.OUTPUT_JSON:
			data, err := json.MarshalIndent(objects, "", "  ")
			if err != nil {
				utils.Fatal(1, "error converting objects to json: %s", err.Error())
			}
			fmt.Println(string(data))
		case utils.OUTPUT_YAML:
			data, err := yaml.Marshal(objects)
			if err != nil {
				utils.Fatal(1, "error converting objects to yaml: %s", err.Error())
			}
			fmt.Println(string(data))
		}
	},
}

GetSecretCmd represents the 'get secret' command

Functions

func ValidateGetAllCommand

func ValidateGetAllCommand()

func ValidateGetResourceCommand

func ValidateGetResourceCommand(args []string)

func ValidateGetSecretCommand

func ValidateGetSecretCommand(args []string)

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL