kubernetes / kubernetes/kubectl

Cobra command Kubectl Create does not return error to be handled

Open
#1,615 11 comments 0 reactions 1 assignee Claimed by @ogormans-deptstack View on GitHub
kind/bug priority/backlog triage/accepted
Dominant language
Go
Stars
3.3k
Forks
1k
PR merge metrics
No merged PRs in 30d

Description

**What happened**:

I'm writing a function to basically do `kubectl create -k /path`. However, If the manifests there have already been created, I don't want my program to exit, but just ignore it.

This is a quick snippet:

```
func createKustomization(kustomization string, kubeconfig string) error {
klog.Infof("Using create policy with kustomization at %s", kustomization)

cmds := &cobra.Command{
Use: "kubectl",
Short: "kubectl",
}
persistFlags := cmds.PersistentFlags()
persistFlags.SetNormalizeFunc(cliflag.WarnWordSepNormalizeFunc)
persistFlags.SetNormalizeFunc(cliflag.WordSepNormalizeFunc)

kubeConfigFlags := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()
kubeConfigFlags.KubeConfig = &kubeconfig
kubeConfigFlags.AddFlags(persistFlags)

matchVersionKubeConfigFlags := cmdutil.NewMatchVersionFlags(kubeConfigFlags)
matchVersionKubeConfigFlags.AddFlags(persistFlags)

f := cmdutil.NewFactory(matchVersionKubeConfigFlags)
ioStreams := genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}
createCmd := create.NewCmdCreate(f, ioStreams)
createCmd.SetArgs([]string{"-k", kustomization})
createCmd.SetOut(ioStreams.Out)
createCmd.SetErr(ioStreams.ErrOut)
createCmd.SetIn(ioStreams.In)

klog.Infof("Executing create command")
createCmd.SilenceUsage = true
err := createCmd.Execute()
if err != nil {
klog.Infof("Creating kustomization failed: %s", err)
return nil
}

klog.Infof("Kustomization applied successfully")
return nil

}
```

createCmd.Execute() just throws an error, but It never gets into `klog.Infof("Creating kustomization failed: %s", err)`

Am I doing something wrong?

**What you expected to happen**:

To return an error so I can handle it.

**Anything else we need to know?**:

**Environment**:
Library: k8s.io/kubectl v0.30.2
- Kubernetes client and server versions (use `kubectl version`):
- Cloud provider or hardware configuration:
- OS (e.g: `cat /etc/os-release`):

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.