Grzegorz Burzyński

Using custom markers with elastic/crd-ref-docs

Context

In projects I work on, we used to manually maintain our Kubernetes Custom Resource Definitions (CRDs) API references. It changed once we employed elastic/crd-ref-docs tool that helped us generate those from source code.

Recently, a need to attach some custom data points to API packages/types/fields emerged as we wanted to filter some types out from the reference. It turned out, the tool already provided such an ability using the custom markers feature.

I tried it out with types and fields, and it worked like a charm. I was able to access the markers’ values in templates and customize those according to our needs. It didn’t work with packages, though, so I contributed a PR that fixed that as well.

Using custom markers

To use a custom marker, you must first add it to your config.yaml (the one that is passed to crd-ref-docs). It can be done as follows:

processor:
  customMarkers:
    - name: "apireference:exclude"
      target: "type"
    - name: "apireference:exclude"
      target: "field"

⚠️ Please note you have to add a customMarkers list entry per (name, target) tuple, even if the name is the same for all targets.

Having those in place, you can annotate types and fields in your API package.

// TypeToBeExcluded is a type that won't be included in the generated API reference.
// +apireference:exclude
type TypeToBeExcluded struct {}

type TypeWithFieldsToBeExcluded struct {
    // FieldToBeExcluded is a field that won't be included in the generated API reference.
    // +apireference:exclude
    FieldToBeExcluded string

    // FieldToBeIncluded is a field that will be included in the generated API reference.
    FieldToBeIncluded string
}

To make the custom markers actually affect the generated reference, you have to modify the templates used by crd-ref-docs. You can access the marker values in the templates and make decisions based on those like below where I skip rendering fields with apireference:exclude marker:

{{ range $type.Members -}}
{{ if not (index .Markers "apireference:kgo:exclude") -}}
| `{{ .Name  }}` _{{ markdownRenderType .Type }}_ | {{ template "type_members" . }} |
{{ end -}}
{{ end -}}

For reference, here are PRs where I used custom markers: