### Setup Controller with Manager Client Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/references/client.md Demonstrates how a controller's reconciler is set up with the Manager's client, which handles Create, Update, Delete, Get, and List operations. ```Go import ( appsv1 "k8s.io/api/apps/v1" ctrl "sigs.k8s.io/controller-runtime" cachev1alpha1 "github.com/example/memcached-operator/api/v1alpha1" ) func (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). // mgr's Client is passed to r. For(&cachev1alpha1.Memcached{}). Owns(&appsv1.Deployment{}). Complete(r) } type MemcachedReconciler struct { client.Client // Populated above from a manager.Manager. Log logr.Logger Scheme *runtime.Scheme } ``` -------------------------------- ### Basic Memcached Chart Installation Source: https://github.com/operator-framework/operator-sdk/blob/master/testdata/helm/memcached-operator/helm-charts/memcached/README.md A basic command to install the Memcached chart. This is a minimal example. ```bash $ helm install stable/memcached ``` -------------------------------- ### Get API Object Example Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/references/client.md Demonstrates how to retrieve a Kubernetes object using the client's Get method. Ensure the object key and target object are correctly specified. ```Go import ( "context" ctrl "sigs.k8s.io/controller-runtime" cachev1alpha1 "github.com/example/memcached-operator/api/v1alpha1" ) func (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { // ... memcached := &cachev1alpha1.Memcached{} err := r.Get(ctx, request.NamespacedName, memcached) // ... } ``` -------------------------------- ### Compile and Install Operator SDK from Master Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/installation/_index.md Clone the Operator SDK repository, checkout the master branch, and use 'make install' to compile and install from source. Ensure Go version 1.23 and GOPROXY are set correctly. ```sh git clone https://github.com/operator-framework/operator-sdk cd operator-sdk git checkout master make install ``` -------------------------------- ### Install Project via Bundle Source: https://github.com/operator-framework/operator-sdk/blob/master/testdata/go/v4/memcached-operator/README.md Installs the project by applying the generated 'install.yaml' file from a remote URL. This file contains all Kustomize-built resources. ```sh kubectl apply -f https://raw.githubusercontent.com//memcached-operator//dist/install.yaml ``` -------------------------------- ### Go Fake Client Example Source: https://github.com/operator-framework/operator-sdk/blob/master/proposals/qa-samples-proposal.md Example demonstrating how to create a fake client for testing Go operator controllers. This is essential for mocking dependencies and isolating the controller logic. ```go func NewFakeClientWithStatusMock(t *testing.T, statusMock *mock.MockStatusWriter) client.Client { ctrl := gomock.NewController(t) mockClient := mock.NewMockClient(ctrl) // Mock Status() to return our statusMock mockClient.EXPECT().Status().Return(statusMock).AnyTimes() return mockClient } ``` -------------------------------- ### Replace go get with go install in Makefile Targets Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/upgrading-sdk-version/v1.21.0.md For Go-based operators, update Makefile targets to use 'go install' instead of 'go get' for downloading build tools like controller-gen, kustomize, and setup-envtest. ```makefile CONTROLLER_GEN = $(shell pwd)/bin/controller-gen .PHONY: controller-gen controller-gen: ## Download controller-gen locally if necessary. $(call go-get-tool,$(CONTROLLER_GEN),sigs.k8s.io/controller-tools/cmd/controller-gen@v0.8.0) KUSTOMIZE = $(shell pwd)/bin/kustomize .PHONY: kustomize kustomize: ## Download kustomize locally if necessary. $(call go-get-tool,$(KUSTOMIZE),sigs.k8s.io/kustomize/kustomize/v3@v3.8.7) ENVTEST = $(shell pwd)/bin/setup-envtest .PHONY: envtest envtest: ## Download envtest-setup locally if necessary. $(call go-get-tool,$(ENVTEST),sigs.k8s.io/controller-runtime/tools/setup-envtest@latest) # go-get-tool will 'go get' any package $2 and install it to $1. PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST)))) define go-get-tool @[ -f $(1) ] || { \ set -e ;\ TMP_DIR=$$(mktemp -d) ;\ cd $$TMP_DIR ;\ go mod init tmp ;\ echo "Downloading $(2)" ; GOBIN=$(PROJECT_DIR)/bin go get $(2) ; rm -rf $$TMP_DIR ; } endef ``` ```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 ``` -------------------------------- ### Example watches.yaml Configuration Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/helm/reference/watches.md This example demonstrates a basic `watches.yaml` file configuration for a custom resource. It includes settings for image repository overrides, disabling dependent resource watching, label selectors, and the dry-run option. ```yaml # Use the 'create api' subcommand to add watches to this file. - group: foo.example.com version: v1alpha1 kind: Foo chart: helm-charts/foo overrideValues: image.repository: quay.io/mycustomrepo watchDependentResources: false selector: matchExpressions: - {key: testLabel, operator: Exists, values: []} dryRunOption: server ``` -------------------------------- ### Install Memcached Chart Source: https://github.com/operator-framework/operator-sdk/blob/master/testdata/helm/memcached-operator/helm-charts/memcached/README.md Installs the Memcached chart with the release name 'my-release' in the default configuration. ```bash $ helm install --name my-release stable/memcached ``` -------------------------------- ### Install Memcached Chart with Values File Source: https://github.com/operator-framework/operator-sdk/blob/master/testdata/helm/memcached-operator/helm-charts/memcached/README.md Installs the Memcached chart using a custom YAML values file. ```bash $ helm install --name my-release -f values.yaml stable/memcached ``` -------------------------------- ### Scorecard Configuration Example Source: https://github.com/operator-framework/operator-sdk/blob/master/proposals/improved-scorecard-config.md This example demonstrates the new structure for Scorecard configuration, including settings for output format and various plugin types (basic, OLM, and external). It shows how to specify CR manifests, timeouts, proxy settings, and external command details. ```yaml scorecard: output: json plugins: - name: Basic Tests basic: cr-manifest: - "deploy/crds/cache.example.com_v1alpha1_memcached_cr.yaml" - "deploy/crds/cache.example.com_v1alpha1_memcachedrs_cr.yaml" init-timeout: 60 csv-path: "deploy/olm-catalog/memcached-operator/0.0.3/memcached-operator.v0.0.3.clusterserviceversion.yaml" proxy-image: "scorecard-proxy" proxy-pull-policy: "Never" - name: OLM Tests olm: cr-manifest: - "deploy/crds/cache.example.com_v1alpha1_memcached_cr.yaml" - "deploy/crds/cache.example.com_v1alpha1_memcachedrs_cr.yaml" init-timeout: 60 csv-path: "deploy/olm-catalog/memcached-operator/0.0.3/memcached-operator.v0.0.3.clusterserviceversion.yaml" proxy-image: "scorecard-proxy" proxy-pull-policy: "Never" - name: Custom Test external: command: bin/my-test.sh - name: Custom Test v2 external: command: bin/my-test.sh args: ["--version=2"] - name: Custom Test Cluster 2 external: command: bin/my-test.sh env: - name: KUBECONFIG value: "~/.kube/config2` ``` -------------------------------- ### Example Local Image Architecture Inspection Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/advanced-topics/multi-arch.md This example demonstrates how to inspect a local image, such as `docker://alpine`, using `skopeo inspect` to retrieve its `Architecture` and `Os` details. ```json { "Name": "docker.io/library/alpine", ... "Architecture": "amd64", "Os": "linux", ... } ``` -------------------------------- ### Install Operator Bundle using Subscription Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/olm-integration/tutorial-bundle.md This command creates a Subscription resource to install an operator bundle, specifying the channel, approval strategy, and source details. ```bash oc create -f subscription.yaml ``` -------------------------------- ### Define go-install-tool in Makefile Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/upgrading-sdk-version/v1.36.0.md This Makefile snippet defines a helper function `go-install-tool` for installing Go tools. It ensures the tool exists at the specified path, downloading and installing it if necessary. ```makefile + $(GOLANGCI_LINT): $(LOCALBIN) $(call go-install-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint,${GOLANGCI_LINT_VERSION}) # go-install-tool will 'go install' any package with custom target and name of binary, if it doesn't exist # $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 ``` -------------------------------- ### Install OLM Bundle Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/olm-integration/quickstart-bundle.md Install the validated bundle onto your cluster using the 'operator-sdk run bundle' command. ```sh $ operator-sdk run bundle $BUNDLE_IMG ``` -------------------------------- ### Install psachecker Tool Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/best-practices/pod-security-standards.md Clones the psachecker repository, builds the tool, and copies the executable to the Go bin directory for use. ```sh 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/ ``` -------------------------------- ### Example: Re-scaffolding a project Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/cli/operator-sdk_alpha_generate.md Example of re-scaffolding a KubeBuilder project. The --input-dir flag specifies the project's current location, and --output-dir indicates where the new scaffolded project will be created. ```bash $ kubebuilder alpha generate --input-dir="./test" --output-dir="./my-output" ``` -------------------------------- ### Install Operator SDK Binary Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/installation/_index.md Make the downloaded binary executable and move it to a directory in your system's PATH for general use. ```sh chmod +x operator-sdk_${OS}_${ARCH} && sudo mv operator-sdk_${OS}_${ARCH} /usr/local/bin/operator-sdk ``` -------------------------------- ### Ansible Operator Watches Configuration Examples Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/ansible/reference/watches.md These examples demonstrate various configurations for the watches.yaml file, including mapping to roles, playbooks, managing status, and blacklisting resources. ```yaml --- # Simple example mapping Foo to the Foo role - version: v1alpha1 group: foo.example.com kind: Foo role: Foo ``` ```yaml # Simple example mapping Bar to a playbook - version: v1alpha1 group: bar.example.com kind: Bar playbook: playbook.yml ``` ```yaml # More complex example for our Baz kind # Here we will disable requeuing and be managing the CR status in the playbook, # and specify additional variables. - version: v1alpha1 group: baz.example.com kind: Baz playbook: baz.yml manageStatus: False vars: foo: bar ``` ```yaml # ConfigMaps owned by a Memcached CR will not be watched or cached. - version: v1alpha1 group: cache.example.com kind: Memcached role: /opt/ansible/roles/memcached blacklist: - group: "" version: v1 kind: ConfigMap ``` ```yaml # Example usage with a role from an installed Ansible collection - version: v1alpha1 group: bar.example.com kind: Bar role: myNamespace.myCollection.myRole ``` -------------------------------- ### Comprehensive Go Marker Example for CRDs Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/references/markers.md A detailed example demonstrating how to use Go markers to infer `path`, `description`, `displayName`, and `x-descriptors` for both `specDescriptors` and `statusDescriptors`. It also includes defining multiple `resources` entries. ```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"` } ``` ```yaml customresourcedefinitions: owned: - description: Represents a cluster of Memcached apps displayName: Memcached App kind: Memcached name: memcacheds.cache.example.com version: v1alpha1 resources: - kind: Deployment name: memcached-deployment version: v1 - kind: Pod name: memcached-runner version: v1 specDescriptors: - description: The desired number of member Pods for the deployment. displayName: Size path: pods.size statusDescriptors: - description: The desired number of member Pods for the deployment. displayName: Size path: podStatuses.size - displayName: Size path: podCount x-descriptors: - 'urn:alm:descriptor:com.tectonic.ui:podCount' ``` -------------------------------- ### Example Alpine Image Architectures Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/advanced-topics/multi-arch.md This example shows the JSON output from inspecting the Alpine Linux container image, illustrating support for both `linux/amd64` and `linux/arm64` architectures. ```json { "manifests": [ { "digest": "sha256:c0669ef34cdc14332c0f1ab0c2c01acb91d96014b172f1a76f3a39e63d1f0bda", "mediaType": "application/vnd.docker.distribution.manifest.v2+json", "platform": { "architecture": "amd64", "os": "linux" }, "size": 528 }, ... { "digest": "sha256:30e6d35703c578ee703230b9dc87ada2ba958c1928615ac8a674fcbb0f281", "mediaType": "application/vnd.docker.distribution.manifest.v2+json", "platform": { "architecture": "arm64", "os": "linux", "variant": "v8" }, "size": 528 }, ... ``` -------------------------------- ### Build Installer Bundle Source: https://github.com/operator-framework/operator-sdk/blob/master/testdata/go/v4/memcached-operator/README.md Builds an installer YAML file containing all necessary resources for the project, located in the dist directory. Requires the operator image to be built and published. ```sh make build-installer IMG=/memcached-operator:tag ``` -------------------------------- ### Go Unit Test Example Source: https://github.com/operator-framework/operator-sdk/blob/master/proposals/qa-samples-proposal.md Example of how to cover a Go operator controller with unit tests using the default Go testing library and the SDK's test-framework. Requires a fake client implementation for testing. ```go func TestControllerSuite(t *testing.T) { // Setup the Manager at the same time ctrl := gomock.NewController(t) defer ctrl.Finish() mockClient := mock.NewMockClient(ctrl) scheme := runtime.NewScheme() _ = AddToScheme(scheme) mgr, err := ctrl.NewManager(cfg, ctrl.Options{Scheme: scheme}) if err != nil { t := err t.Fatal(t) } // Set the mock client for the manager mgr.SetClient(mockClient) // Add the controller to the manager ctx := context.Background() instance := &cachev1alpha1.Memcached{ObjectMeta: metav1.ObjectMeta{Name: "memcached-sample"}} ctrl, err := controller.NewMemcachedReconciler(controller.MemcachedReconcilerConf{ Manager: mgr, Client: mockClient, Scheme: scheme, Log: ctrl.Log.WithName("controller") }) if err != nil { t := err t.Fatal(t) } // Start the controller go func() { ctrl.SetupWithManager(ctx, mgr) }() // Give the manager time to start time.Sleep(1 * time.Second) // Create a new Memcached object and expect the Reconcile and Store to be called memcached := &cachev1alpha1.Memcached{ObjectMeta: metav1.ObjectMeta{Name: "memcached-sample"}} ctrl.Reconcile(ctx, reconcile.Request{NamespacedName: types.NamespacedName{Name: "memcached-sample"}}) // Add more assertions here } ``` -------------------------------- ### Operator SDK Version Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/cli/operator-sdk.md Prints the installed version of the operator-sdk. ```bash operator-sdk version ``` -------------------------------- ### Makefile Run Target Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/references/logging.md Example `Makefile` snippet demonstrating how the `run` target accepts additional arguments via the `ARGS` variable. ```makefile # Run against the configured Kubernetes cluster in ~/.kube/config run: manifests generate fmt vet go run ./main.go $(ARGS) ``` -------------------------------- ### Get Help for Init Command Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/cli/operator-sdk.md Provides detailed help for the 'init' command, including specific plugin and project version configurations. ```bash operator-sdk init --help --plugins= [--project-version=] ``` -------------------------------- ### Configure Controller Setup with controller-runtime Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/migration.md This Go code demonstrates the modern way to set up a controller using controller-runtime's builder pattern. It specifies the primary resource to watch and any owned resources. ```go func (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&cachev1alpha1.Memcached{}). Owns(&appsv1.Deployment{}). Complete(r) } ``` -------------------------------- ### Initialize a New Project Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/cli/operator-sdk_init.md Initializes a new project with specified domain and owner for copyright information. Use this to set up a new Go-based operator project. ```bash operator-sdk init --plugins go/v4 --domain example.org --owner "Your name" ``` -------------------------------- ### Build and Serve Docs Locally Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/contribution-guidelines/documentation.md Run this command from the 'website/' directory to build and serve the documentation locally on 'localhost:1313'. Changes are reflected in real time. ```sh hugo server ``` -------------------------------- ### Initialize New v0.1.0 Project Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/upgrading-sdk-version/v0.1.0-migration-guide.md Steps to create a new Operator SDK v0.1.0 project and copy git history from an old project. ```sh # Ensure SDK version is v0.1.0 $ operator-sdk --version operator-sdk version 0.1.0 # Create new project $ cd $GOPATH/src/github.com/example/ $ mv memcached-operator old-memcached-operator $ operator-sdk new memcached-operator --skip-git-init $ ls memcached-operator old-memcached-operator # Copy over .git from old project $ cp -rf old-memcached-operator/.git memcached-operator/.git ``` -------------------------------- ### Add cluster setup for e2e tests in Makefile Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/upgrading-sdk-version/v1.41.0.md This Makefile snippet adds targets for setting up and cleaning up a Kind cluster for e2e tests. It checks if Kind is installed and if the cluster already exists before creating it. ```makefile KIND_CLUSTER ?= -test-e2e .PHONY: setup-test-e2e setup-test-e2e: ## Set up a Kind cluster for e2e tests if it does not exist @command -v $(KIND) >/dev/null 2>&1 || { \ echo "Kind is not installed. Please install Kind manually."; \ exit 1; \ } @case "$$($(KIND) get clusters)" in \ *"$(KIND_CLUSTER)"*) \ echo "Kind cluster '$(KIND_CLUSTER)' already exists. Skipping creation." ;; \ *) \ echo "Creating Kind cluster '$(KIND_CLUSTER)'..."; \ $(KIND) create cluster --name $(KIND_CLUSTER) ;; \ esac .PHONY: cleanup-test-e2e cleanup-test-e2e: $(KIND) delete cluster --name $(KIND_CLUSTER) ``` -------------------------------- ### Adjust Makefile for Controller-Gen Installation Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/upgrading-sdk-version/v1.28.0.md Update the `Makefile` to ensure `controller-gen` is installed correctly with the specified version, using a conditional check before installation. ```diff - `test -s $(LOCALBIN)/controller-gen || GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-tools/cmd/controller-gen@$(CONTROLLER_TOOLS_VERSION)` + 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) ``` -------------------------------- ### Install OLM Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/cli/operator-sdk_olm_install.md Use this command to install Operator Lifecycle Manager in your cluster. You can customize the installation using flags like `--timeout` and `--version`. ```bash operator-sdk olm install [flags] ``` -------------------------------- ### Install Kubernetes Collection Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/ansible/development-tips.md Installs the Kubernetes Collection from ansible-galaxy. ```sh ansible-galaxy collection install kubernetes.core ``` -------------------------------- ### Initialize New Ansible Project Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/ansible/migration.md Use this command to initialize a new Ansible operator project with the specified domain. Replace `example.com` with your project's domain. ```sh mkdir memcached-operator cd memcached-operator operator-sdk init --plugins=ansible --domain=example.com ``` -------------------------------- ### Install Ansible Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/ansible/development-tips.md Installs Ansible version 2.9+ on Fedora/Centos systems. ```sh sudo dnf install ansible ``` -------------------------------- ### Manage OLM Installation and Status Source: https://context7.com/operator-framework/operator-sdk/llms.txt Commands to check OLM status, install, and uninstall OLM. Use `--version` to specify a version and `--olm-namespace` for custom OLM installations. ```bash # Override version when auto-detect fails operator-sdk olm status --version 0.28.0 ``` ```bash # Uninstall OLM operator-sdk olm uninstall ``` ```bash # Uninstall a specific OLM version from a non-default namespace operator-sdk olm uninstall --version 0.28.0 --olm-namespace custom-olm ``` -------------------------------- ### Install OLM Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/ansible/quickstart.md Installs the Operator Lifecycle Manager (OLM) into your Kubernetes cluster. ```sh operator-sdk olm install ``` -------------------------------- ### Build and Run Bundle on Live Cluster Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/olm-integration/tutorial-package-manifests.md After preparing your bundle, build and push its image, then run the bundle on a live cluster to verify its functionality. ```sh $ make bundle bundle-build bundle-push $ operator-sdk run bundle quay.io/example/etcd-bundle:0.0.2 ``` -------------------------------- ### Update Travis CI Install Dependencies Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/upgrading-sdk-version/version-upgrade-guide.md Modify the 'install' section of your '.travis.yml' file to include the necessary lints for Molecule v3.0.2. This ensures that all required linting tools are installed during the CI process. ```yaml install: - pip3 install docker molecule openshift jmespath ``` ```yaml install: - pip3 install docker molecule ansible-lint yamllint flake8 openshift jmespath ``` -------------------------------- ### Install CRDs Source: https://github.com/operator-framework/operator-sdk/blob/master/testdata/go/v4/memcached-operator/README.md Installs the Custom Resource Definitions (CRDs) for the memcached-operator into the Kubernetes cluster. ```sh make install ``` -------------------------------- ### Custom Resource Example Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/ansible/development-tips.md This is an example of a Custom Resource (CR) definition for a Memcached resource. ```yaml apiVersion: "cache.example.com/v1alpha1" kind: "Memcached" metadata: name: "memcached-sample" spec: message: "Hello world 2" newParameter: "newParam" ``` -------------------------------- ### Initialize Helm Operator Project Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/helm/quickstart.md Initializes a new project directory for a Helm-based operator. Replace 'example.com' with your registry namespace. ```sh mkdir nginx-operator cd nginx-operator operator-sdk init --domain example.com --plugins helm ``` -------------------------------- ### Generate Bundles with Custom Build Command Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/cli/operator-sdk_pkgman-to-bundle.md This example shows how to generate bundles and build their images using a custom build command. It specifies the packagemanifests directory, the base image name, and the build command to be used. ```bash operator-sdk pkgman-to-bundle packagemanifests --image-tag-base quay.io/example/etcd --build-cmd "podman build -f bundle.Dockerfile . -t" ``` -------------------------------- ### OLM Install Command Options Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/cli/operator-sdk_olm_install.md These are the specific options available for the `operator-sdk olm install` command. The `--timeout` flag controls how long the command waits for completion, and `--version` specifies the OLM version to install. ```bash -h, --help help for install --timeout duration time to wait for the command to complete before failing (default 2m0s) --version string version of OLM resources to install (default "0.28.0") ``` -------------------------------- ### Install Operator Dependencies Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/ansible/development-tips.md Installs Ansible collections specified in the requirements.yml file, including kubernetes.core and operator_sdk.util. ```sh ansible-galaxy collection install -r requirements.yml ``` -------------------------------- ### Go Controller with Structured Logging Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/references/logging.md A Go controller example demonstrating how to obtain a logger from the context and use it for structured logging, including error logging with context. ```go package memcached import ( ctrllog "sigs.k8s.io/controller-runtime/pkg/log" ) // MemcachedReconciler reconciles a Memcached object type MemcachedReconciler struct { client.Client Log logr.Logger Scheme *runtime.Scheme } func (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { log := ctrllog.FromContext(ctx) // Fetch the Memcached instance memcached := &cachev1alpha1.Memcached{} err := r.Get(ctx, req.NamespacedName, memcached) if err != nil { if errors.IsNotFound(err) { // Request object not found, could have been deleted after reconcile request. // Owned objects are automatically garbage collected. For additional cleanup logic use finalizers. // Return and don't requeue log.Info("Memcached resource not found. Ignoring since object must be deleted") return ctrl.Result{}, nil } // Error reading the object - requeue the request. log.Error(err, "Failed to get Memcached") return ctrl.Result{}, err } // Check if the deployment already exists, if not create a new one found := &appsv1.Deployment{} err = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found) if err != nil && errors.IsNotFound(err) { // Define a new deployment dep := r.deploymentForMemcached(memcached) log.Info("Creating a new Deployment", "Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name) err = r.Create(ctx, dep) if err != nil { log.Error(err, "Failed to create new Deployment", "Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name) return ctrl.Result{}, err } // Deployment created successfully - return and requeue return ctrl.Result{Requeue: true}, nil } else if err != nil { log.Error(err, "Failed to get Deployment") return ctrl.Result{}, err } ... } ``` -------------------------------- ### List API Objects Example Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/references/client.md Shows how to list Kubernetes objects within a specific namespace and matching certain labels and fields using the client's List method. Options like InNamespace, MatchingLabels, and MatchingFields can be combined. ```Go import ( "context" "fmt" "k8s.io/api/core/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" ) func (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { // ... // Return all pods in the request namespace with a label of `instance=` // and phase `Running`. podList := &v1.PodList{} opts := []client.ListOption{ client.InNamespace(request.NamespacedName.Namespace), client.MatchingLabels{"instance": request.NamespacedName.Name}, client.MatchingFields{"status.phase": "Running"}, } err := r.List(ctx, podList, opts...) // ... } ``` -------------------------------- ### Install Operator SDK via Homebrew Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/installation/_index.md Use this command to install the Operator SDK CLI if you are using Homebrew on macOS. ```sh brew install operator-sdk ``` -------------------------------- ### Create API Object Example Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/references/client.md Illustrates how to create a new Kubernetes object in the cluster using the client's Create method. Ensure the object is properly defined before calling Create. ```Go import ( "context" "k8s.io/api/apps/v1" ctrl "sigs.k8s.io/controller-runtime" ) func (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { // ... dep := &v1.Deployment{ // Any cluster object you want to create. // ... } err := r.Create(ctx, dep) // ... } ``` -------------------------------- ### Install Python Kubernetes Client Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/ansible/development-tips.md Installs the Python Kubernetes client package required for Ansible's Kubernetes collection. ```sh pip3 install kubernetes ``` -------------------------------- ### Setup Memcached Controller with Primary and Owned Resources Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/tutorial.md Specify the primary resource to watch (Memcached) and owned resources (Deployments) in the controller's 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) } ``` -------------------------------- ### Install and Run Operator Locally Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/quickstart.md Installs necessary CRDs and runs the operator locally outside the cluster. Recommended for development only. ```sh make install run ``` -------------------------------- ### Install OLM Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/olm-integration/tutorial-bundle.md Install the latest version of OLM on your cluster if it is not already present. This command fetches and creates the necessary CRDs and resources. ```console $ operator-sdk olm install INFO[0000] Fetching CRDs for version "latest" INFO[0001] Fetching resources for version "latest" INFO[0007] Creating CRDs and resources INFO[0007] Creating CustomResourceDefinition "clusterserviceversions.operators.coreos.com" INFO[0007] Creating CustomResourceDefinition "installplans.operators.coreos.com" INFO[0007] Creating CustomResourceDefinition "subscriptions.operators.coreos.com" ... NAME NAMESPACE KIND STATUS clusterserviceversions.operators.coreos.com CustomResourceDefinition Installed installplans.operators.coreos.com CustomResourceDefinition Installed subscriptions.operators.coreos.com CustomResourceDefinition Installed catalogsources.operators.coreos.com CustomResourceDefinition Installed ... ``` -------------------------------- ### Initialize Project with Specific Version Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/cli/operator-sdk_init.md Initializes a new project and defines a specific project version. This is useful for managing project compatibility and features. ```bash operator-sdk init --plugins go/v4 --project-version 3 ``` -------------------------------- ### Install Prometheus Operator Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/migration.md If Prometheus is not installed, apply the `kube-prometheus` bundle to create the necessary `ServiceMonitor` API resource for exporting metrics. ```sh kubectl apply -f https://raw.githubusercontent.com/coreos/prometheus-operator/release-0.33/bundle.yaml ``` -------------------------------- ### Build and Push Bundle Image with `make bundle-build bundle-push` Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/olm-integration/tutorial-bundle.md Build and push your operator bundle image to a registry. Replace `/memcached-operator-bundle:v0.0.1` with your actual registry path and image tag. ```bash $ make bundle-build bundle-push BUNDLE_IMG=/memcached-operator-bundle:v0.0.1 ``` -------------------------------- ### Operator Lifecycle Workflow: Init, Create API, Build, Deploy, Test Source: https://context7.com/operator-framework/operator-sdk/llms.txt Scaffolds a new Go operator project, creates an API and controller, regenerates manifests, builds and pushes the operator image, and runs the operator locally. ```bash # 1. Scaffold a new Go operator project mkdir memcached-operator && cd memcached-operator operator-sdk init --domain example.com --repo github.com/example/memcached-operator # 2. Create an API + controller operator-sdk create api --group cache --version v1alpha1 --kind Memcached --resource --controller # 3. Regenerate CRD manifests after editing *_types.go make generate # updates zz_generated.deepcopy.go make manifests # updates config/crd/bases/*.yaml # 4. Build and push the operator image make docker-build docker-push IMG="example.com/memcached-operator:v0.0.1" # 5. Run locally for development (outside cluster, installs CRDs into cluster) make install run ``` ```bash # 6. Run via direct Kubernetes deployment (non-OLM) make deploy IMG="example.com/memcached-operator:v0.0.1" kubectl apply -f config/samples/cache_v1alpha1_memcached.yaml make undeploy ``` ```bash # 7. Package as OLM bundle operator-sdk olm install make bundle IMG="example.com/memcached-operator:v0.0.1" # ↑ Runs: controller-gen → generate kustomize manifests → generate bundle → bundle validate ``` ```bash # 8. Build and push the bundle image make bundle-build bundle-push BUNDLE_IMG="example.com/memcached-operator-bundle:v0.0.1" ``` ```bash # 9. Deploy via OLM for testing operator-sdk run bundle example.com/memcached-operator-bundle:v0.0.1 kubectl apply -f config/samples/cache_v1alpha1_memcached.yaml ``` ```bash # 10. Run scorecard tests operator-sdk scorecard ./bundle --namespace default --wait-time 60s ``` ```bash # 11. Upgrade to v0.0.2 make bundle IMG="example.com/memcached-operator:v0.0.2" ``` -------------------------------- ### Operator Registry Manifests Layout Example Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/upgrading-sdk-version/version-upgrade-guide.md Example directory structure for operator manifests in the operator-registry format, used by `operator-sdk olm-catalog gen-csv`. ```tree $ tree deploy/olm-catalog deploy/olm-catalog/ └── memcached-operator ├── 0.1.0 │   └── memcached-operator.v0.1.0.clusterserviceversion.yaml ├── 0.2.0 │   └── memcached-operator.v0.2.0.clusterserviceversion.yaml └── memcached-operator.package.yaml ``` -------------------------------- ### Initialize Project with Kustomize Plugin Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/contribution-guidelines/plugins.md Scaffolds a new operator project using the kustomize plugin. This is a common base for language-specific plugins. ```bash operator-sdk init --plugins=kustomize ``` -------------------------------- ### Grant RBAC Get Permissions for Non-Cacheable Resources Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/faqs/_index.md After disabling caching for a resource, ensure your operator has 'get' privileges for it by adding the appropriate RBAC directive. ```go //+kubebuilder:rbac:groups=image.openshift.io,resources=imagestreamtags,verbs=get ``` -------------------------------- ### Update Envtest Tool Installation Logic in Makefile Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/upgrading-sdk-version/v1.38.0.md Refactor the envtest tool installation logic in the Makefile to handle versioned binaries and create symbolic links. ```diff - @[ -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) ``` -------------------------------- ### Initialize Go Operator Project Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/quickstart.md Initializes a new Go-based operator project with the specified domain and repository. Use the `--plugins=go/v4` flag for Apple Silicon. ```sh mkdir memcached-operator cd memcached-operator operator-sdk init --domain example.com --repo github.com/example/memcached-operator ``` -------------------------------- ### Install and Run Ansible Operator Locally Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/ansible/development-tips.md Installs the operator's CRD and runs the ansible-operator binary locally. It uses watches.yaml and ~/.kube/config for cluster communication. ```bash $ make install run /home/user/memcached-operator/bin/kustomize build config/crd | kubectl apply -f - customresourcedefinition.apiextensions.k8s.io/memcacheds.cache.example.com created /home/user/go/bin/ansible-operator run {"level":"info","ts":1595899073.9861593,"logger":"cmd","msg":"Version","Go Version":"go1.13.12","GOOS":"linux","GOARCH":"amd64","ansible-operator":"v0.19.0+git"} {"level":"info","ts":1595899073.987384,"logger":"cmd","msg":"WATCH_NAMESPACE environment variable not set. Watching all namespaces.","Namespace":""} {"level":"info","ts":1595899074.9504397,"logger":"controller-runtime.metrics","msg":"metrics server is starting to listen","addr":":8080"} {"level":"info","ts":1595899074.9522583,"logger":"watches","msg":"Environment variable not set; using default value","envVar":"ANSIBLE_VERBOSITY_MEMCACHED_CACHE_EXAMPLE_COM","default":2} {"level":"info","ts":1595899074.9524004,"logger":"cmd","msg":"Environment variable not set; using default value","Namespace":"","envVar":"ANSIBLE_DEBUG_LOGS","ANSIBLE_DEBUG_LOGS":false} {"level":"info","ts":1595899074.9524298,"logger":"ansible-controller","msg":"Watching resource","Options.Group":"cache.example.com","Options.Version":"v1","Options.Kind":"Memcached"} ``` -------------------------------- ### Create Non-Default Client Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/references/client.md Shows how to create a custom client using controller-runtime's constructor, allowing for specific options like reading directly from the API server instead of the cache. ```Go import ( "sigs.k8s.io/controller-runtime/pkg/client/config" "sigs.k8s.io/controller-runtime/pkg/client" ) cfg, err := config.GetConfig() ... c, err := client.New(cfg, client.Options{}) ... ``` -------------------------------- ### Example Output with Custom Zap Logger Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/building-operators/golang/references/logging.md Demonstrates the output format when using a custom zap logger for both global and scoped loggers. ```console $ go run main.go ts=2020-04-30T20:35:59.551268Z level=info logger=global msg="Printing at INFO level" ts=2020-04-30T20:35:59.551314Z level=debug logger=global msg="Printing at DEBUG level" ts=2020-04-30T20:35:59.551318Z level=info logger=scoped msg="Printing at INFO level" ts=2020-04-30T20:35:59.55132Z level=debug logger=scoped msg="Printing at DEBUG level" ``` -------------------------------- ### Example Validation Output Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/advanced-topics/custom-bundle-validation.md This is an example of the output you might see when running the `operator-sdk bundle validate` command with a custom validator. It includes warnings and success messages. ```sh WARN[0000] Warning: Value sandbox-op.v0.0.1: owned CRD "sandboxes.sandbox.example.come" has an empty description INFO[0000] All validation tests have completed successfully ``` -------------------------------- ### Build and Run Basic Validator Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/advanced-topics/custom-bundle-validation.md Build the Go validator and run it to see its JSON output. This demonstrates the validator producing a successful `ManifestResult`. ```sh go build -o myvalidator/main myvalidator/main.go && ./myvalidator/main ``` ```json { "Name": "Always Green Example", "Errors": null, "Warnings": null } ``` -------------------------------- ### Update Dockerfile for Ansible Collection Installation Source: https://github.com/operator-framework/operator-sdk/blob/master/website/content/en/docs/upgrading-sdk-version/version-upgrade-guide.md Modify your build/Dockerfile to copy the requirements.yml file and install the specified Ansible collections. This ensures the collections are available during the build process. ```dockerfile COPY requirements.yml ${HOME}/requirements.yml RUN ansible-galaxy collection install -r ${HOME}/requirements.yml \ && chmod -R ug+rwx ${HOME}/.ansible ```