<p>I need to add <code>kubectl apply</code> functionality to my application.</p>

<p>I've looked through <code>kubectl go-client</code>, it has no provisions for the apply command.</p>

<ol>
<li>Can I create an instance of <code>kubectl</code> in my go-application? </li>
<li>If not 1, can I use the <code>k8s.io/kubernetes</code> package to emulate an <code>kubectl apply</code> command?</li>
</ol>

<p>Questions and clarifications if needed, will be given.</p>

<blockquote>
  <ol>
  <li>Can I create an instance of kubectl in my application?</li>
  </ol>
</blockquote>

<p>You can wrap the <code>kubectl</code> command in your application and start it in a new child-process, like you would do via a shell-script. See the <code>exec</code> package in go for more information: <a href="https://golang.org/pkg/os/exec/" rel="nofollow noreferrer">https://golang.org/pkg/os/exec/</a></p>

<p>This works pretty good for us and kubectl usually has the <code>-o</code>-Parameter that lets you control the output format, so you get machine readable text back.</p>

<p>There are already some open-source projects that use this approach:</p>

<ul>
<li><a href="https://github.com/box/kube-applier" rel="nofollow noreferrer">https://github.com/box/kube-applier</a></li>
<li><a href="https://github.com/autoapply/autoapply" rel="nofollow noreferrer">https://github.com/autoapply/autoapply</a></li>
</ul>

<blockquote>
  <ol start="2">
  <li>If not 1, can I use the k8s.io/kubernetes package to emulate an kubectl apply command?</li>
  </ol>
</blockquote>

<p>Have you found <a href="https://github.com/kubernetes/kubernetes/blob/master/pkg/kubectl/cmd/apply/apply.go" rel="nofollow noreferrer">https://github.com/kubernetes/kubernetes/blob/master/pkg/kubectl/cmd/apply/apply.go</a> while searching in kubectl-source code?
Take a look at the run-function:</p>

<pre>
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 {
    ...
</pre>

<p>It is not very good readable it guess but this is what <code>kubectl apply</code> does.
Maybe one possible way of whould be to debug the code and see what is does further more.</p>
