Skip to content

How to Create the Skeleton of an Operator

Cesar Celis edited this page Aug 27, 2024 · 19 revisions

Objective:

To create the skeleton of an operator

Diagram:

Screenshot 2024-08-26 at 11 15 56 AM

Recommendation:

Use chatgpt to get the steps and explore things further in a quick way, remember chatgpt and AI is a tool to help us be better! So use it well and use it wize with love!

Steps:

  • Prepare an empty folder to work with:
cd ~
rm -rf ~/tmp
cd ~
mkdir ~/tmp
cd ~/tmp
  • Initialize the operator
operator-sdk init --domain example.com --repo github.com/my-org/my-operator
  • Create the API:
operator-sdk create api --group apps --version v1alpha1 --kind MyApp
  • In the controller, get the app instance & print the message from the custom resource:

  • File:

subl /Users/cniackz/tmp/internal/controller/myapp_controller.go
func (r *MyAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {

    ...

    log := log.FromContext(ctx)

    // Fetch the MyApp instance
    var myapp appsv1alpha1.MyApp
    if err := r.Get(ctx, req.NamespacedName, &myapp); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }

    // Print the message from the Custom Resource
    log.Info("Received MyResource", "message", myapp.Spec.Message)

    ...
  • In the types file, add the message to the struct
subl /Users/cniackz/tmp/api/v1alpha1/myapp_types.go
type MyAppSpec struct {
	// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
	// Important: Run "make" to regenerate code after modifying this file

	// Foo is an example field of MyApp. Edit myapp_types.go to remove/update
	Foo string `json:"foo,omitempty"`

	Message string `json:"message,omitempty"`
}
  • Then make and generate the files:
make generate
make manifests
  • Build the image:
make docker-build IMG=radical-123
kind load docker-image docker.io/library/radical-123
createcluster
Clone this wiki locally