Skip to content

Instantly share code, notes, and snippets.

@jeesmon
Created February 23, 2022 21:34
Show Gist options
  • Save jeesmon/53419573d2c14bb1bee7ca85a96a5e45 to your computer and use it in GitHub Desktop.
Save jeesmon/53419573d2c14bb1bee7ca85a96a5e45 to your computer and use it in GitHub Desktop.

If you are creating a standalone go library for your operator and have types that are used in your operator CRD spec/status, you will see that you need code-generation to generate DeepCopy and DeepCopyInto methods for your types. For API types in your operator, make generate will do that for you automatically using controller-tools. But for your library project that is not using controller-tools, you can do the same code generation using github.com/kubernetes/code-generator.

An example is here: https://github.com/jeesmon/operator-utils/blob/main/Makefile#L14-L20

Steps:

  • Add deepcopy-gen markers for your types

ex:

https://github.com/jeesmon/operator-utils/blob/main/status/doc.go#L1-L3

https://github.com/jeesmon/operator-utils/blob/main/status/status.go#L25

  • Install deepcopy-gen from code-generator project
go install k8s.io/code-generator/cmd/deepcopy-gen@v0.24.0-alpha.3
  • Generate deepcoy file

ex:

deepcopy-gen -i github.com/jeesmon/operator-utils/status -h hack/boilerplate.go.txt --trim-path-prefix github.com/jeesmon/operator-utils --output-base . --output-package github.com/jeesmon/operator-utils/status -O zz_deepcopy

Above command will create a zz_deepcopy.go file with DeepCopy* methods

ex: https://github.com/jeesmon/operator-utils/blob/main/status/zz_deepcopy.go

  • Makefile example

https://github.com/jeesmon/operator-utils/blob/main/Makefile#L14-L20

More on code generation:

https://cloud.redhat.com/blog/kubernetes-deep-dive-code-generation-customresources

https://github.com/kubernetes/code-generator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment