This guide demonstrates how to generate CUE from Go types defined in some dependency of a Go module.

Initialize Go and CUE modules

1

Create a Go module, or use an existing one if that’s more suitable for your situation:

TERMINAL
$ go mod init go.example
...
2

Create a CUE module if you don’t already have one:

TERMINAL
$ cue mod init cue.example

Declare a Go dependency

If your Go doesn’t already depend on the module containing the Go types you’re interested in, add it as a dependency.

3

Create a Go file to signal the required package to the go command. Our example depends on a Kubernetes package:

deps.go
//go:build deps
// +build deps

package deps

import _ "k8s.io/api/apps/v1"
4

Add a dependency on a specific version of the target Go package, and tidy the main module:

TERMINAL
$ go get k8s.io/api/apps/v1@v0.23.4 # "@latest" would also work.
...
$ go mod tidy
...

Generate CUE from Go

5

Use the cue command to generate CUE from the target Go package:

TERMINAL
$ cue get go k8s.io/api/apps/v1
6

Inspect the CUE packages generated in cue.mod/gen:

TERMINAL
$ tree -d cue.mod/gen
cue.mod/gen
└── k8s.io
    ├── api
    │   ├── apps
    │   │   └── v1
    │   └── core
    │       └── v1
    └── apimachinery
        └── pkg
            ├── api
...

More CUE packages are generated than just the target. These are dependencies of the target package.

Test the generated CUE

7

Use the generated code in a CUE package:

example.cue
package example

import (
	core "k8s.io/api/core/v1"
	apps "k8s.io/api/apps/v1"
)

service: [string]:     core.#Service
deployment: [string]:  apps.#Deployment
daemonSet: [string]:   apps.#DaemonSet
statefulSet: [string]: apps.#StatefulSet
8

Export an empty configuration to confirm that everything works:

TERMINAL
$ cue export --out yaml
service: {}
deployment: {}
daemonSet: {}
statefulSet: {}
  • Issue #2865 tracks the plans for CUE to support finding well-known types (such as the Kubernetes example used above) at a well-known location, without having to import them manually.
  • How-to Guide: Generating CUE from local Go code