Single Group to Multi-Group

While KubeBuilder v2 will not scaffold out a project structure compatible with multiple API groups in the same repository by default, it’s possible to modify the default project structure to support it.

Let’s migrate the CronJob example.

Generally, we use the prefix for the API group as the directory name. We can check api/v1/groupversion_info.go to find that out:

// +groupName=batch.tutorial.kubebuilder.io
package v1

Then, we’ll rename api to apis to be more clear, and we’ll move our existing APIs into a new subdirectory, “batch”:

mkdir apis/batch
mv api/* apis/batch
# After ensuring that all was moved successfully remove the old directory `api/`
rm -rf api/ 

After moving the APIs to a new directory, the same needs to be applied to the controllers:

mkdir controllers/batch
mv controllers/* controllers/batch/

Next, we’ll need to update all the references to the old package name. For CronJob, that’ll be main.go and controllers/batch/cronjob_controller.go.

If you’ve added additional files to your project, you’ll need to track down imports there as well.

Finally, we’ll run the command which enable the multi-group layout in the project:

kubebuilder edit --multigroup=true

When the command kubebuilder edit --multigroup=true is executed it will add a new line to PROJECT that marks this a multi-group project:

version: "2"
domain: tutorial.kubebuilder.io
repo: tutorial.kubebuilder.io/project
multigroup: true

Note that this option indicates to KubeBuilder that this is a multi-group project.

In this way, if the project is not new and has previous APIs already implemented will be in the previous structure. Notice that with the multi-group project the Kind API’s files are created under apis/<group>/<version> instead of api/<version>. Also, note that the controllers will be created under pkg/controllers/<group> instead of pkg/controllers. That is the reason why we moved the previously generated APIs with the provided scripts in the previous steps. Remember to update the references afterwards.

The CronJob tutorial explains each of these changes in more detail (in the context of how they’re generated by KubeBuilder for single-group projects).