How to user code-generator

In this article, we will focus on how to use the K8s code-generator from scratch.

Let's assume we want to create CRD in group "foo.com", and there is a type called "HelloType" with a "message" field in the spec:

# Definition
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:  
  name: hellotypes.foo.com
spec:  
  group: foo.com  
  version: v1
  scope: Namespaced  
  names:    
    kind: HelloType   
    shortNames: ht
    plural: hellotypes
    singular: hellotype
# HelloType
---
apiVersion: foo.com/v1
kind: HelloType 
metadata: 
  name: superman-hello
spec:
  message: hello world

There are two steps to generate the CRD resource code:

  1. Write the type definition code with code generator tags

  2. Run run the generator to create the client codes which include: clientset, informers, listers for your customer resource

Write type definition code

  • cd $GOPATH/src

  • mkdir -p github.com/superman/demo

  • cd $GOPATH/src/github.com/superman/demo

  • Create the skeleton files as below under $GOPATH/src/github.com/superman/demo

doc.go

This file provide controls of the global tags that will apply to every type in the same version with default setting.

The tags compose of two parts, the function name and the value to pass in normally. For example in+k8s:deepcopy-gen=package, deepcopy-gen is the function to call for generating the deep copies codes for types. packagedenotes applying the function to the whole v1 package in this case.

types.go

+genclient means generating API client for the type.

+k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Objectmeans when generating deepcopy for the type, use runtime.Object interface.

+optional indicates the field is optional. The data can be empty for the field.

register.go

The register.go file contains the functions registering the new types we just created to the schema so the API server can recognize them.

Run code-generator to create client codes

The usage of generate-groups.sh. More details could be found here.

After above steps, you will see the following file structure:

References:

Last updated

Was this helpful?