Chapter 5. Automating Code Generation

In this chapter you’ll learn how to use the Kubernetes code generators in Go projects to write custom resources in a natural way. Code generators are used a lot in the implementation of native Kubernetes resources, and we’ll use the very same generators here.

Why Code Generation

Go is a simple language by design. It lacks higher-level or even metaprogramming-like mechanisms to express algorithms on different data types in a generic (i.e., type-independent) way. The “Go way” is to use external code generation instead.

Very early in the Kubernetes development process, more and more code had to be rewritten as more resources were added to the system. Code generation made the maintenance of this code much easier. Very early on, the Gengo library was created, and eventually, based on Gengo, k8s.io/code-generator was developed as an externally usable collection of generators. We will use these generators in the following sections for CRs.

Calling the Generators

Usually, the code generators are called in mostly the same way in every controller project. Only packages, group names, and API versions differ. Calling the script k8s.io/code-generator/generate-groups.sh or a bash script like hack/update-codegen.sh is the easiest way to add code generation to CR Go types from the build system (see the book’s GitHub repository).

Note that some projects call the generator binaries directly due to very special requirements and often historic reasons. For ...

Get Programming Kubernetes now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.