### Compile and Install Operator SDK from Source Source: https://sdk.operatorframework.io/docs/installation Clones the Operator SDK repository and builds the binary from the master branch using the Go toolchain. ```bash git clone https://github.com/operator-framework/operator-sdk cd operator-sdk git checkout master make install ``` -------------------------------- ### Migrate Makefile build dependencies to go install Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/v1.21.0 Replaces deprecated 'go get' tool installation patterns in the Makefile with 'go install' and explicit local binary management for kustomize, controller-gen, and envtest. ```makefile ##@ Build Dependencies ## Location to install dependencies to LOCALBIN ?= $(shell pwd)/bin $(LOCALBIN): mkdir -p $(LOCALBIN) ## Tool Binaries KUSTOMIZE ?= $(LOCALBIN)/kustomize CONTROLLER_GEN ?= $(LOCALBIN)/controller-gen ENVTEST ?= $(LOCALBIN)/setup-envtest ## Tool Versions KUSTOMIZE_VERSION ?= v3.8.7 CONTROLLER_TOOLS_VERSION ?= v0.8.0 KUSTOMIZE_INSTALL_SCRIPT ?= "https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh" .PHONY: kustomize kustomize: $(KUSTOMIZE) ## Download kustomize locally if necessary. $(KUSTOMIZE): $(LOCALBIN) curl -s $(KUSTOMIZE_INSTALL_SCRIPT) | bash -s -- $(subst v,,$(KUSTOMIZE_VERSION)) $(LOCALBIN) .PHONY: controller-gen controller-gen: $(CONTROLLER_GEN) ## Download controller-gen locally if necessary. $(CONTROLLER_GEN): $(LOCALBIN) GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-tools/cmd/controller-gen@$(CONTROLLER_TOOLS_VERSION) .PHONY: envtest envtest: $(ENVTEST) ## Download envtest-setup locally if necessary. $(ENVTEST): $(LOCALBIN) GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest ``` -------------------------------- ### Initialize Ansible Operator Project Source: https://sdk.operatorframework.io/docs/building-operators/ansible/quickstart Initializes a new Ansible-based operator project. Requires Go and Operator SDK to be installed. Creates a project directory and sets up the basic structure. ```bash mkdir memcached-operator cd memcached-operator operator-sdk init --domain example.com --plugins ansible ``` -------------------------------- ### Install psachecker Tool Source: https://sdk.operatorframework.io/docs/best-practices/pod-security-standards Steps to clone, build, and install the psachecker utility from source within a Golang environment. ```bash git clone git@github.com:stlaz/psachecker.git $GOPATH/src/github.com/stlaz/psachecker cd $GOPATH/src/github.com/stlaz/psachecker make build cp kubectl-psachecker $GOPATH/bin/ ``` -------------------------------- ### Install OLM Source: https://sdk.operatorframework.io/docs/building-operators/ansible/quickstart Installs the Operator Lifecycle Manager (OLM) into the Kubernetes cluster. This is a prerequisite for deploying operators using OLM. ```bash operator-sdk olm install ``` -------------------------------- ### Create Memcached API for Go Operator Source: https://sdk.operatorframework.io/docs/building-operators/golang/quickstart Creates a new API resource and its corresponding controller for a Go-based operator. This example defines a 'Memcached' resource in the 'cache' group with version 'v1alpha1'. ```bash operator-sdk create api --group cache --version v1alpha1 --kind Memcached --resource --controller ``` -------------------------------- ### Automate ENVTEST Version Discovery and Setup in Makefile Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/v1.40.0 This Makefile snippet shows how to automate the discovery of ENVTEST and Kubernetes API versions using `go list`. It also includes a new `setup-envtest` target to automatically install the necessary binaries, ensuring tests can run without manual intervention. This improves the test setup process for Go-based operators. ```makefile ENVTEST_VERSION := $(shell go list -m -f "{{ .Version }}" sigs.k8s.io/controller-runtime | awk -F'[v.]' '{printf "release-%d.%d", $$2, $$3}') ENVTEST_K8S_VERSION := $(shell go list -m -f "{{ .Version }}" k8s.io/api | awk -F'[v.]' '{printf "1.%d", $$3}') .PHONY: setup-envtest setup-envtest: @$(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path || { \ echo "Error setting up envtest"; exit 1; } ``` -------------------------------- ### Download and Verify Operator SDK Binary Source: https://sdk.operatorframework.io/docs/installation Downloads the specific platform binary from GitHub releases, verifies its integrity using GPG signatures and SHA256 checksums, and moves it to the system PATH. ```bash export ARCH=$(case $(uname -m) in x86_64) echo -n amd64 ;; aarch64) echo -n arm64 ;; *) echo -n $(uname -m) ;; esac) export OS=$(uname | awk '{print tolower($0)}') export OPERATOR_SDK_DL_URL=https://github.com/operator-framework/operator-sdk/releases/download/v1.42.0 curl -LO ${OPERATOR_SDK_DL_URL}/operator-sdk_${OS}_${ARCH} gpg --keyserver keyserver.ubuntu.com --recv-keys 052996E2A20B5C7E curl -LO ${OPERATOR_SDK_DL_URL}/checksums.txt curl -LO ${OPERATOR_SDK_DL_URL}/checksums.txt.asc gpg -u "Operator SDK (release) " --verify checksums.txt.asc grep operator-sdk_${OS}_${ARCH} checksums.txt | sha256sum -c - chmod +x operator-sdk_${OS}_${ARCH} && sudo mv operator-sdk_${OS}_${ARCH} /usr/local/bin/operator-sdk ``` -------------------------------- ### Controller Setup with Manager Source: https://sdk.operatorframework.io/docs/building-operators/golang/migration Go code snippet demonstrating how to set up a controller with the manager using controller-runtime. It specifies the primary resource to watch and other owned resources. ```go func (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&cachev1alpha1.Memcached{}). Owns(&appsv1.Deployment{}). Complete(r) } ``` -------------------------------- ### Run Go Operator Locally Source: https://sdk.operatorframework.io/docs/building-operators/golang/quickstart Installs necessary CRDs and runs the operator locally, outside the Kubernetes cluster. This is recommended for development and debugging purposes. ```bash make install run ``` -------------------------------- ### Install Go Tool using go-install-tool Macro Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/v1.36.0 This macro installs a specified Go package to a target binary path. It checks if the binary already exists and downloads/installs the package if not. Dependencies include the Go toolchain and a defined LOCALBIN environment variable. ```shell # $1 - target path with name of binary (ideally with version) # $2 - package url which can be installed # $3 - specific version of package define go-install-tool @[ -f $(1) ] || { \ set -e; \ package=$(2)@$(3) ;\ echo "Downloading $${package}" ;\ GOBIN=$(LOCALBIN) go install $${package} ;\ mv "$$(echo "$(1)" | sed "s/-$(3)$$)//")" $(1) ;\ } endef ``` -------------------------------- ### Run Operator Bundle with OLM Source: https://sdk.operatorframework.io/docs/building-operators/ansible/quickstart Deploys the operator to the Kubernetes cluster using its bundle image. This command assumes OLM is installed and the bundle image is accessible. ```bash operator-sdk run bundle example.com/memcached-operator-bundle:v0.0.1 ``` -------------------------------- ### Migrate CRUD operations to Controller-Runtime Client Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/v0.1.0-migration-guide Demonstrates the transition from legacy sdk.* client methods to the controller-runtime r.client.* API. These examples cover Create, Update, Delete, List, and Get operations using context-aware methods. ```go // Create err := r.client.Create(context.TODO(), dep) // Update err := r.client.Update(context.TODO(), dep) // Delete err := r.client.Delete(context.TODO(), dep) // List listOps := &client.ListOptions{Namespace: memcached.Namespace, LabelSelector: labelSelector} err := r.client.List(context.TODO(), listOps, podList) // Get err = r.client.Get(context.TODO(), types.NamespacedName{Name: name, Namespace: namespace}, dep) ``` -------------------------------- ### Example Memcached Resource YAML Source: https://sdk.operatorframework.io/docs/building-operators/ansible/reference/retroactively-owned-resources An abbreviated example of the YAML output for a Memcached resource. It shows essential metadata like name, namespace, and UID, which are crucial for setting up owner references. ```yaml apiVersion: cache.example.com/v1alpha1 kind: Memcached metadata: name: example-memcached namespace: default uid: 2a94ff2b-84e0-40ce-8b5e-2b7e4d2bc0e2 ``` -------------------------------- ### Operator Lifecycle Management Commands Source: https://sdk.operatorframework.io/docs/building-operators/helm/tutorial Commands to install OLM, generate operator bundles, and deploy the operator using bundle images. ```bash operator-sdk olm install make bundle bundle-build bundle-push operator-sdk run bundle example.com/nginx-operator-bundle:v0.0.1 ``` -------------------------------- ### Verify Manifest Security Policy Source: https://sdk.operatorframework.io/docs/best-practices/pod-security-standards Example command to inspect a deployment manifest using psachecker to ensure it meets restricted security requirements. ```bash kubectl-psachecker inspect-workloads -f test.yaml ``` -------------------------------- ### Register Custom Types in Go Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/v0.1.0-migration-guide Example of the init function required to register custom types with the Manager's scheme. ```go func init() { SchemeBuilder.Register(&Memcached{}, &MemcachedList{}) } ``` -------------------------------- ### Example usage of operator-sdk init Source: https://sdk.operatorframework.io/docs/cli/operator-sdk_init Demonstrates common initialization patterns, including specifying the plugin version, domain, copyright owner, and project version. ```bash # Initialize a new project with your domain and name in copyright operator-sdk init --plugins go/v4 --domain example.org --owner "Your name" # Initialize a new project defining a specific project version operator-sdk init --plugins go/v4 --project-version 3 ``` -------------------------------- ### Install Operator SDK via Homebrew Source: https://sdk.operatorframework.io/docs/installation Installs the Operator SDK CLI on macOS systems using the Homebrew package manager. ```bash brew install operator-sdk ``` -------------------------------- ### Update controller-gen installation logic Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/v1.28.0 Updates the Makefile to verify the controller-gen version before installation to ensure compatibility. ```makefile test -s $(LOCALBIN)/controller-gen && $(LOCALBIN)/controller-gen --version | grep -q $(CONTROLLER_TOOLS_VERSION) || \ GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-tools/cmd/controller-gen@$(CONTROLLER_TOOLS_VERSION) ``` -------------------------------- ### Initialize Go Operator Project Source: https://sdk.operatorframework.io/docs/building-operators/golang/quickstart Initializes a new Go-based operator project. It requires a domain and a repository path. For Apple Silicon, use the 'go/v4' plugin. ```bash mkdir memcached-operator cd memcached-operator operator-sdk init --domain example.com --repo github.com/example/memcached-operator # For Apple Silicon: operator-sdk init --domain example.com --repo github.com/example/memcached-operator --plugins=go/v4 ``` -------------------------------- ### Bundle and Deploy Go Operator with OLM Source: https://sdk.operatorframework.io/docs/building-operators/golang/quickstart Bundles the operator, builds and pushes the bundle image, and then runs the bundle. This process is for deploying operators managed by OLM. Ensure you are logged into your image registry. ```bash make bundle IMG="example.com/memcached-operator:v0.0.1" make bundle-build bundle-push BUNDLE_IMG="example.com/memcached-operator-bundle:v0.0.1" operator-sdk run bundle /memcached-operator-bundle:v0.0.1 ``` -------------------------------- ### Install Ansible and Kubernetes dependencies Source: https://sdk.operatorframework.io/docs/building-operators/ansible/development-tips Commands to install the required Ansible runtime, the Python Kubernetes client, and the necessary Ansible collections to support Kubernetes operations. ```bash sudo dnf install ansible pip3 install kubernetes ansible-galaxy collection install kubernetes.core ansible-galaxy collection install -r requirements.yml ``` -------------------------------- ### Kubernetes Custom Resource Definition (CRD) for Memcached Source: https://sdk.operatorframework.io/docs/building-operators/ansible/development-tips Example YAML definition for a Memcached custom resource, used to trigger Ansible Operator execution. ```yaml apiVersion: cache.example.com/v1alpha1 kind: Memcached metadata: name: "memcached-sample" ``` ```yaml apiVersion: cache.example.com/v1alpha1 kind: Memcached metadata: name: memcached-sample spec: state: absent ``` ```yaml apiVersion: "cache.example.com/v1alpha1" kind: "Memcached" metadata: name: "example-memcached" annotations: "ansible.sdk.operatorframework.io/verbosity": "4" spec: size: 4 ``` -------------------------------- ### Create Sample Custom Resource Source: https://sdk.operatorframework.io/docs/building-operators/helm/quickstart Applies a sample custom resource definition to the Kubernetes cluster. This allows testing the operator's functionality by creating an instance of the defined resource. ```bash $kubectl apply -f config/samples/demo_v1alpha1_nginx.yaml nginx.demo.example.com/nginx-sample created ``` -------------------------------- ### Initialize New Go Operator Project Source: https://sdk.operatorframework.io/docs/building-operators/golang/tutorial Creates a new Go operator project using the operator-sdk CLI. It requires specifying a domain for API groups and a repository path for Go modules. Ensure Go modules are enabled by setting `GO111MODULE=on`. ```bash mkdir -p $HOME/projects/memcached-operator cd $HOME/projects/memcached-operator # we'll use a domain of example.com # so all API groups will be .example.com operator-sdk init --domain example.com --repo github.com/example/memcached-operator ``` -------------------------------- ### Create Subscription (YAML) Source: https://sdk.operatorframework.io/docs/olm-integration/tutorial-bundle Defines a Subscription resource for OLM, specifying the operator's channel, approval strategy, name, source, and starting CSV. This is used to install an operator bundle. ```yaml apiVersion: v1 items: - apiVersion: operators.coreos.com/v1alpha1 kind: Subscription metadata: name: etcd namespace: default spec: channel: "stable" installPlanApproval: Manual name: etcd source: etcdoperator sourceNamespace: default startingCSV: etcdoperator.v0.0.1 ``` -------------------------------- ### Setup Memcached Reconciler with Recorder Source: https://sdk.operatorframework.io/docs/building-operators/golang/tutorial Initializes the Memcached reconciler and sets up an event recorder for emitting events. This is done during the reconciler's initialization phase. ```go if err = (&controllers.MemcachedReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), Recorder: mgr.GetEventRecorderFor("memcached-controller"), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "Memcached") os.Exit(1) } ``` -------------------------------- ### Initialize Helm Operator Project Source: https://sdk.operatorframework.io/docs/building-operators/helm/quickstart Initializes a new project directory for a Helm-based operator. It requires the project name, a domain, and specifies the Helm plugin for the Operator SDK. ```bash mkdir nginx-operator cd nginx-operator operator-sdk init --domain example.com --plugins helm ``` -------------------------------- ### Create Memcached Custom Resource (OLM) Source: https://sdk.operatorframework.io/docs/building-operators/golang/quickstart Applies a sample Memcached custom resource definition to the cluster, allowing you to test the deployed operator. This assumes the OLM deployment is complete. ```bash kubectl apply -f config/samples/cache_v1alpha1_memcached.yaml ``` -------------------------------- ### Custom Resource Definition with Ansible Reconciliation Period Source: https://sdk.operatorframework.io/docs/building-operators/ansible/development-tips This example demonstrates a Kubernetes Custom Resource (CR) definition for a 'Memcached' resource. It includes an annotation `ansible.operator-sdk/reconcile-period` to specify the reconciliation interval for the operator. The `spec` field is where variables for Ansible are passed. ```yaml apiVersion: cache.example.com/v1alpha1 kind: Memcached metadata: name: example annotations: ansible.operator-sdk/reconcile-period: "30s" ``` -------------------------------- ### Bundle, Build, and Push Operator Bundle Source: https://sdk.operatorframework.io/docs/building-operators/golang/tutorial Makefile targets to create a bundle for the operator, build the bundle image, and push it to a container registry. ```bash make bundle bundle-build bundle-push ``` -------------------------------- ### Install Ansible Collections in Dockerfile Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/version-upgrade-guide This snippet shows how to add requirements.yml to a Dockerfile and install Ansible Galaxy collections. It ensures the collections are installed before proceeding with other build steps. ```dockerfile COPY requirements.yml ${HOME}/requirements.yml RUN ansible-galaxy collection install -r ${HOME}/requirements.yml \ && chmod -R ug+rwx ${HOME}/.ansible ``` -------------------------------- ### Install dependencies in Ansible Operator Dockerfile Source: https://sdk.operatorframework.io/docs/faqs Instructions for installing custom dependencies in an Ansible operator image. It demonstrates switching to the root user to perform installations and reverting to the non-privileged user. ```dockerfile USER 0 RUN yum -y install my-dependency RUN pip3 install my-python-dependency USER 1001 ``` -------------------------------- ### Update Controller-Runtime Client List Method Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/version-upgrade-guide Demonstrates the migration of the Client.List method signature to use variadic options instead of a pointer to ListOptions. ```go // Old signature usage listOpts := &client.ListOptions{} listOpts.InNamespace("namespace") err = r.client.List(context.TODO(), listOps, podList) // New signature usage listOpts := []client.ListOption{ client.InNamespace("namespace"), } err = r.client.List(context.TODO(), podList, listOpts...) ``` -------------------------------- ### Run Operator Bundle via OLM Source: https://sdk.operatorframework.io/docs/building-operators/helm/quickstart Runs the operator bundle using OLM. This command deploys the operator to the cluster and makes it available for managing custom resources. Requires the bundle image to be accessible. ```bash operator-sdk run bundle example.com/nginx-operator-bundle:v0.0.1 ``` -------------------------------- ### Manage OLM Installation with operator-sdk Source: https://sdk.operatorframework.io/docs/olm-integration/cli-overview Commands to manage an Operator Lifecycle Manager (OLM) installation within a Kubernetes cluster. These subcommands allow for installing, checking the status, and uninstalling specific versions of OLM. ```bash operator-sdk olm install operator-sdk olm status operator-sdk olm uninstall ``` -------------------------------- ### Update Golangci-lint Installation in Makefile (Go) Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/v1.38.0 Modifies the `Makefile` to correctly install `golangci-lint` using the `go-install-tool` function with the updated version variable. This ensures the linter is installed with the correct version specified in the Makefile. ```makefile - $(call go-install-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint,${GOLANGCI_LINT_VERSION}) + $(call go-install-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint,$(GOLANGCI_LINT_VERSION)) ``` -------------------------------- ### Bundle Operator and Push Bundle Image Source: https://sdk.operatorframework.io/docs/building-operators/helm/quickstart Creates an operator bundle, then builds and pushes the bundle image to a container registry. This is necessary for deploying operators via OLM. ```bash make bundle IMG="example.com/nginx-operator:v0.0.1" make bundle-build bundle-push IMG="example.com/nginx-operator:v0.0.1" ``` -------------------------------- ### Install Ansible Collections Source: https://sdk.operatorframework.io/docs/building-operators/ansible/testing-guide Installs the necessary Ansible collections specified in the requirements.yml file. This is a prerequisite for running Ansible-based operator tests. ```bash ansible-galaxy collection install -r requirements.yml ``` -------------------------------- ### Kuttl Test Suite Configuration Example Source: https://sdk.operatorframework.io/docs/testing-operators/scorecard/kuttl-tests An example of a kuttl TestSuite configuration file. It demonstrates settings like parallel execution, timeout, and control plane management, tailored for scorecard execution. ```yaml apiVersion: kudo.dev/v1beta1 kind: TestSuite parallel: 4 timeout: 120 startControlPlane: false ``` -------------------------------- ### Initialize Project with Kustomize Plugin Source: https://sdk.operatorframework.io/docs/contribution-guidelines/plugins Initializes a new operator project using the kustomize plugin, which is a common base for language-specific operator projects. This command sets up the basic project structure and configuration files. ```bash operator-sdk init --plugins=kustomize ``` -------------------------------- ### Implement Leader Election in Go Source: https://sdk.operatorframework.io/docs/building-operators/golang/migration Demonstrates how to manually implement leader election using the operator-lib leader package or by configuring the controller-runtime Manager options. ```go func main() { ctx := context.TODO() // Become the leader before proceeding err = leader.Become(ctx, "memcached-operator-lock") if err != nil { log.Error(err, "") os.Exit(1) } } ``` ```go func main() { mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, MetricsBindAddress: metricsAddr, Port: 9443, HealthProbeBindAddress: probeAddr, LeaderElection: enableLeaderElection, LeaderElectionID: "86f835c3.example.com", }) } ``` -------------------------------- ### Bundle Operator and Push Bundle Image Source: https://sdk.operatorframework.io/docs/building-operators/ansible/quickstart Creates a bundle for the operator, then builds and pushes the bundle image to a container registry. This prepares the operator for deployment via OLM. ```bash make bundle IMG="example.com/memcached-operator:v0.0.1" make bundle-build bundle-push ``` -------------------------------- ### Refactor Envtest Installation Logic in Makefile (Go) Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/v1.38.0 Updates the Envtest installation logic in the `Makefile` to handle file renaming and symbolic linking more robustly. This change ensures that the correct Envtest binary is consistently available, even after potential renames during download or extraction. ```makefile - @[ -f $(1) ] || { \ + @[ -f "$(1)-$(3)" ] || { \ echo "Downloading $${package}" ; + rm -f $(1) || true ; - mv "$$(echo "$(1)" | sed "s/-$(3)$$//")" $(1) ; - } + mv $(1) $(1)-$(3) ; + } ; + ln -sf $(1)-$(3) $(1) ``` -------------------------------- ### Inline Bundle and Catalog Image Deployment Source: https://sdk.operatorframework.io/docs/olm-integration/tutorial-bundle Combines the bundle and catalog image build and push operations into a single command. Assumes IMAGE_TAG_BASE is pre-configured. This streamlines the deployment process for both bundle and catalog images. ```makefile make bundle-build bundle-push catalog-build catalog-push ``` -------------------------------- ### Define RBAC Rules for Metrics and Finalizers Source: https://sdk.operatorframework.io/docs/building-operators/helm/migration Example configuration for RBAC rules in role.yaml, specifically for monitoring ServiceMonitors and managing deployment finalizers. ```yaml - apiGroups: - monitoring.coreos.com resources: - servicemonitors verbs: - get - create - apiGroups: - apps resourceNames: - nginx-operator resources: - deployments/finalizers verbs: - update ``` -------------------------------- ### Comprehensive CRD Definition with Go Markers Source: https://sdk.operatorframework.io/docs/building-operators/golang/references/markers This comprehensive Go example demonstrates inferring `path`, `description`, `displayName`, and `x-descriptors` for both `specDescriptors` and `statusDescriptors`. It also shows how to define multiple `resources` entries for a CRD. ```go // Represents a cluster of Memcached apps //+operator-sdk:csv:customresourcedefinitions:displayName="Memcached App",resources={{Pod,v1,memcached-runner},{Deployment,v1,memcached-deployment}} type Memcached struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec MemcachedSpec `json:"spec,omitempty"` Status MemcachedStatus `json:"status,omitempty" } type MemcachedSpec struct { Pods MemcachedPods `json:"pods"` } type MemcachedStatus struct { Pods MemcachedPods `json:"podStatuses"` //+operator-sdk:csv:customresourcedefinitions:type=status,displayName="Pod Count",xDescriptors="urn:alm:descriptor:com.tectonic.ui:podCount" PodCount int `json:"podCount"` } type MemcachedPods struct { // Size is the size of the memcached deployment. //+operator-sdk:csv:customresourcedefinitions:type=spec //+operator-sdk:csv:customresourcedefinitions:type=status Size int32 `json:"size"` } ``` -------------------------------- ### Define RBAC Rules for Metrics and Finalizers Source: https://sdk.operatorframework.io/docs/building-operators/ansible/migration Example RBAC rules for managing ServiceMonitors and deployment finalizers, which should be included in config/rbac/role.yaml if required by the operator. ```yaml - apiGroups: - monitoring.coreos.com resources: - servicemonitors verbs: - get - create - apiGroups: - apps resourceNames: - memcached-operator resources: - deployments/finalizers verbs: - update ``` -------------------------------- ### Update watches.yaml Configuration Source: https://sdk.operatorframework.io/docs/building-operators/ansible/migration Configures the watches.yaml file to map resources to roles. Includes an example of updating the reconcilePeriod from an integer to a duration string. ```yaml --- # Use the 'create api' subcommand to add watches to this file. - version: v1alpha1 group: cache.example.com kind: Memcached role: memcached reconcilePeriod: 3600s #+kubebuilder:scaffold:watch ``` -------------------------------- ### Deploy Operator to Kubernetes Cluster Source: https://sdk.operatorframework.io/docs/building-operators/golang/tutorial Command to deploy the operator as a Deployment within a Kubernetes cluster. This also installs the necessary RBAC manifests. ```bash make deploy ``` -------------------------------- ### Configure Pruning Library in Go Source: https://sdk.operatorframework.io/docs/best-practices/resource-pruning Example of configuring the pruning library in Go. It sets up logging, dry-run mode, Kubernetes clientset, label selectors, target resources and namespaces, and the pruning strategy. It also shows how to define a pre-delete hook. ```go cfg := Config{ Log: logf.Log.WithName("prune"), DryRun: false, Clientset: client, LabelSelector: "app=churro", Resources: []schema.GroupVersionKind{ {Group: "", Version: "", Kind: PodKind}, }, Namespaces: []string{"default"}, Strategy: StrategyConfig{ Mode: MaxCountStrategy, MaxCountSetting: 1, }, PreDeleteHook: myhook, } ``` -------------------------------- ### Migrate Admission API imports Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/v1.28.0 Updates Go imports from admission/v1beta1 to admission/v1 for gov4alpha scaffolds. ```go admissionv1 "k8s.io/api/admission/v1" ``` -------------------------------- ### Update Makefile build target Source: https://sdk.operatorframework.io/docs/upgrading-sdk-version/v1.28.0 Updates the Makefile build target to include the manifests generation step. ```makefile build: manifests generate fmt vet ## Build manager binary. ``` -------------------------------- ### Create Release Branch Source: https://sdk.operatorframework.io/docs/contribution-guidelines/releasing Commands to initialize a new release branch from the master branch. This ensures the release process starts from the latest stable code. ```bash git checkout master git fetch upstream master git pull master git checkout -b v1.3.x git push upstream v1.3.x ``` -------------------------------- ### Define Resources Watched by Memcached Controller Source: https://sdk.operatorframework.io/docs/building-operators/golang/tutorial Configures the controller to watch Memcached custom resources and own Deployments. This setup is performed in the `SetupWithManager` function. ```go import ( ... appsv1 "k8s.io/api/apps/v1" ... ) func (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&cachev1alpha1.Memcached{}). Owns(&appsv1.Deployment{}). Complete(r) } ```