2

I am creating a tool that will create kubernetes object using a yaml file. I am writing it in golang. The tool would like to achieve same behaviour as kubectl apply -f test.yaml

Know Nothing
  • 1,121
  • 2
  • 10
  • 21
  • [kubectl is implemented in Go](https://github.com/kubernetes/kubectl). Did you read the kubectl source code? – Chin Huang Jul 30 '19 at 21:05

2 Answers2

1

Basically, the fastest is to use an existing library like the official go client.

In essence kubectl also uses client-go so you can also follow its source code as a guideline.

You can also use k8s which is another K8s go client.

Rico
  • 58,485
  • 12
  • 111
  • 141
0

kubectl source code is hard to understand, especially when it involved many non-fixed object type to create, how to parse yaml to go object ( I got this working, but needs manual case switch to convert to real go type, which is a single type).

here's the secret create code, is there something general create that I can pass a list of different object? or better, just plain yaml string?

    secretClient := client.CoreV1().Secrets("default")

    result, err := secretClient.Create(secret)

link: https://sourcegraph.com/github.com/kubernetes/kubectl@master/-/blob/pkg/cmd/apply/apply.go#L328:22&tab=def

func (o *ApplyOptions) GetObjects() ([]*resource.Info, error) {
    var err error = nil
    if !o.objectsCached {
        // include the uninitialized objects by default if --prune is true
        // unless explicitly set --include-uninitialized=false
        r := o.Builder.
            Unstructured().
            Schema(o.Validator).
            ContinueOnError().
            NamespaceParam(o.Namespace).DefaultNamespace().
            FilenameParam(o.EnforceNamespace, &o.DeleteOptions.FilenameOptions).
            LabelSelectorParam(o.Selector).
            Flatten().
            Do()
        o.objects, err = r.Infos()
        o.objectsCached = true
    }
    return o.objects, err
}

Lost for r.Infos, not sure where it defined.

Chinglin Wen
  • 149
  • 1
  • 3