I need to add kubectl apply
functionality to my application.
I've looked through kubectl go-client
, it has no provisions for the apply command.
kubectl
in my go-application?k8s.io/kubernetes
package to emulate an kubectl apply
command?Questions and clarifications if needed, will be given.
kubectl
is supposed to be used from command line onlyos.system
in python , similar will exist in golang import "os/exec
", but this approach is dirtyThis can be done by created and adding a plugin to kubectl.
You can write a plugin in any programming language or script that allows you to write command-line commands.
There is no plugin installation or pre-loading required. Plugin executables receive the inherited environment from the
kubectl
binary. A plugin determines which command path it wishes to implement based on its name. For example, a plugin wanting to provide a new commandkubectl foo
, would simply be namedkubectl-foo
, and live somewhere in the user’s PATH.
Example plugin can look as follows:
#!/bin/bash
# optional argument handling
if [[ "$1" == "version" ]]
then
echo "1.0.0"
exit 0
fi
# optional argument handling
if [[ "$1" == "config" ]]
then
echo $KUBECONFIG
exit 0
fi
echo "I am a plugin named kubectl-foo"
After that you just make it executable chmod +x ./kubectl-foo
and move it for in your path mv ./kubectl-foo /usr/local/bin
.
Now you should be able to call it by kubectl foo
:
$ kubectl foo
I am a plugin named kubectl-foo
All args and flags are passed as-is to the executable:
$ kubectl foo version
1.0.0
You can read more about the kubectl plugins inside Kubernetes Extend kubectl with plugins documentation.
- Can I create an instance of kubectl in my application?
You can wrap the kubectl
command in your application and start it in a new child-process, like you would do via a shell-script. See the exec
package in go for more information: https://golang.org/pkg/os/exec/
This works pretty good for us and kubectl usually has the -o
-Parameter that lets you control the output format, so you get machine readable text back.
There are already some open-source projects that use this approach:
- If not 1, can I use the k8s.io/kubernetes package to emulate an kubectl apply command?
Have you found https://github.com/kubernetes/kubernetes/blob/master/pkg/kubectl/cmd/apply/apply.go while searching in kubectl-source code? Take a look at the run-function:
func (o *ApplyOptions) Run() error { ... r := o.Builder. Unstructured(). Schema(o.Validator). ContinueOnError(). NamespaceParam(o.Namespace).DefaultNamespace(). FilenameParam(o.EnforceNamespace, &o.DeleteOptions.FilenameOptions). LabelSelectorParam(o.Selector). IncludeUninitialized(o.ShouldIncludeUninitialized). Flatten(). Do() ... err = r.Visit(func(info *resource.Info, err error) error { ...
It is not very good readable it guess but this is what kubectl apply
does. Maybe one possible way of whould be to debug the code and see what is does further more.