### Build and install the example Source: https://github.com/flant/shell-operator/blob/main/examples/206-mutating-webhook/README.md Builds the Docker image and deploys the example using Helm. ```bash docker build -t localhost:5000/shell-operator:example-206 . docker push localhost:5000/shell-operator:example-206 helm upgrade --install \ --namespace example-206 \ --create-namespace \ example-206 . ``` -------------------------------- ### Build and Install Example Source: https://github.com/flant/shell-operator/blob/main/examples/204-validating-webhook/README.md Builds a Docker image for the shell-operator and installs the example using Helm 3. Ensure you have a local Docker registry configured. ```shell docker build -t localhost:5000/shell-operator:example-204 . docker push localhost:5000/shell-operator:example-204 helm upgrade --install \ --namespace example-204 \ --create-namespace \ example-204 . ``` -------------------------------- ### Build and install the conversion example Source: https://github.com/flant/shell-operator/blob/main/examples/210-conversion-webhook/README.md Build the Docker image and deploy the example using Helm. ```bash docker build -t localhost:5000/shell-operator:example-210 . docker push localhost:5000/shell-operator:example-210 helm upgrade --install \ --namespace example-210 \ --create-namespace \ example-210 . ``` -------------------------------- ### Build and install the example Source: https://github.com/flant/shell-operator/blob/main/examples/220-execution-rate/README.md Commands to build the Docker image and deploy the shell-operator example using Helm. ```bash docker build -t localhost:5000/shell-operator:example-220 . docker push localhost:5000/shell-operator:example-220 helm upgrade --install \ --namespace example-220 \ --create-namespace \ example-220 . ``` -------------------------------- ### Cleanup example resources Source: https://github.com/flant/shell-operator/blob/main/examples/210-conversion-webhook/README.md Remove the Helm release, namespace, and CRD created during the example. ```bash helm delete --namespace=example-210 example-210 kubectl delete ns example-210 kubectl delete crd crontabs.stable.example.com ``` -------------------------------- ### Example hook2.sh metrics Source: https://github.com/flant/shell-operator/blob/main/docs/src/metrics/METRICS_FROM_HOOKS.md Example of exporting metrics from a second hook script. ```sh echo '{"group":"hook2", "name":"hook_metric","action":"add", "value":1, "labels":{"kind":"configmap"}}' >> $METRICS_PATH echo '{"group":"hook2", "name":"hook_metric","action":"add", "value":1, "labels":{"kind":"secret"}}' >> $METRICS_PATH echo '{"group":"hook2", "name":"hook2_special_metric", "action":"set", "value":42}' >> $METRICS_PATH echo '{"name":"common_metric", "action":"set", "value":200, "labels":{"source":"source2"}}' >> $METRICS_PATH ``` -------------------------------- ### Install Helm Chart Source: https://github.com/flant/shell-operator/blob/main/examples/201-install-with-helm-chart/README.md Install the shell-operator Helm chart into the 'example-helm' namespace. This command deploys the shell-operator and configures it to monitor resources. ```bash helm install . --namespace example-helm --name example-helm ``` -------------------------------- ### Example hook1.sh metrics Source: https://github.com/flant/shell-operator/blob/main/docs/src/metrics/METRICS_FROM_HOOKS.md Example of exporting multiple grouped and ungrouped metrics from a hook script. ```sh echo '{"group":"hook1", "name":"hook_metric", "action":"add", "value":1, "labels":{"kind":"pod"}}' >> $METRICS_PATH echo '{"group":"hook1", "name":"hook_metric", "action":"add", "value":1, "labels":{"kind":"replicaset"}}' >> $METRICS_PATH echo '{"group":"hook1", "name":"hook_metric", "action":"add", "value":1, "labels":{"kind":"deployment"}}' >> $METRICS_PATH echo '{"group":"hook1", "name":"hook1_special_metric", "action":"set", "value":12, "labels":{"label1":"value1"}}' >> $METRICS_PATH echo '{"group":"hook1", "name":"common_metric", "action":"set", "value":300, "labels":{"source":"source3"}}' >> $METRICS_PATH echo '{"name":"common_metric", "action":"set", "value":100, "labels":{"source":"source1"}}' >> $METRICS_PATH ``` -------------------------------- ### Example Hook Configuration Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md This example demonstrates a hook configuration that triggers on label changes of Pods. It specifies the kind of resource to monitor, the events that should trigger the hook, label and namespace selectors, a jqFilter for metadata labels, and allows failures. ```yaml configVersion: v1 kubernetes: # Trigger on labels changes of Pods with myLabel:myLabelValue in any namespace - name: "label-changes-of-mylabel-pods" kind: pod executeHookOnEvent: ["Modified"] labelSelector: matchLabels: myLabel: "myLabelValue" namespace: nameSelector: ["default"] jqFilter: .metadata.labels allowFailure: true includeSnapshotsFrom: ["label-changes-of-mylabel-pods"] ``` -------------------------------- ### onStartup Binding Context Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md This is the binding context provided to a hook configured to run on startup. ```yaml configVersion: v1 onStartup: 1 ``` ```json [{"binding": "onStartup"}] ``` -------------------------------- ### Cleanup example resources Source: https://github.com/flant/shell-operator/blob/main/examples/206-mutating-webhook/README.md Removes the Helm release, namespace, and webhook configuration. ```bash helm delete --namespace=example-206 example-206 kubectl delete ns example-206 kubectl delete mutatingwebhookconfiguration/example-206 ``` -------------------------------- ### Example CronTab Conversion Source: https://github.com/flant/shell-operator/blob/main/docs/src/BINDING_CONVERSION.md Shows an example of a converted CronTab object from v1alpha1 to v1beta1. ```yaml "apiVersion": "stable.example.com/v1beta1", "kind": "CronTab", "metadata": { "name": "crontab-v1alpha1", "namespace": "example-210", ... }, "spec": { "cron": [ "*", "*", "*", "*", "*/5" ], "imageName": [ "repo.example.com/my-awesome-cron-image:v1" ] } } ``` -------------------------------- ### Example CRD Conversion Configuration Source: https://github.com/flant/shell-operator/blob/main/docs/src/BINDING_CONVERSION.md An example configuration for kubernetesCustomResourceConversion, detailing multiple conversion paths for a CRD. This setup enables the operator to convert resources between various specified versions. ```yaml configVersion: v1 kubernetesCustomResourceConversion: - name: conversions crdName: crontabs.stable.example.com conversions: - fromVersion: unstable.crontab.io/v1beta1 toVersion: stable.example.com/v1beta1 - fromVersion: stable.example.com/v1beta1 toVersion: stable.example.com/v1beta2 - fromVersion: v1beta2 toVersion: v1 ``` -------------------------------- ### YAML Hook Configuration Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md This is an example of a hook configuration in YAML format. It specifies event bindings for startup, schedules, Kubernetes events, validating webhooks, and custom resource conversion. ```yaml configVersion: v1 onStartup: ORDER, schedule: - {SCHEDULE_PARAMETERS} - {SCHEDULE_PARAMETERS} kubernetes: - {KUBERNETES_PARAMETERS} - {KUBERNETES_PARAMETERS} kubernetesValidating: - {VALIDATING_PARAMETERS} - {VALIDATING_PARAMETERS} kubernetesCustomResourceConversion: - {CONVERSION_PARAMETERS} - {CONVERSION_PARAMETERS} settings: SETTINGS_PARAMETERS ``` -------------------------------- ### Snapshot Structure Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Illustrates the structure of a snapshot, including the Kubernetes object and its jqFilter result. ```yaml [ { "binding": ..., "snapshots": { "binding-name-1": [ { "object": { "kind": "Pod", "metadata": { "name": "etcd-...", "namespace": "kube-system", ... }, }, "filterResult": { ... }, }, ... ] }}] ``` -------------------------------- ### Conversion Response Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/BINDING_CONVERSION.md A minimal example of the response format expected from a kubernetesCustomResourceConversion hook. The hook should output converted objects to the path specified by the CONVERSION_RESPONSE_PATH environment variable. ```bash cat <$CONVERSION_RESPONSE_PATH {"convertedObjects": [{ ``` -------------------------------- ### Start Shell-operator Locally with Kind Source: https://github.com/flant/shell-operator/blob/main/docs/src/RUNNING.md This snippet demonstrates how to start the shell-operator locally using a kind cluster. It specifies the directory for hooks and temporary files, and enables colored log output. ```shell # Start local cluster kind create cluster # Start Shell-operator from outside the cluster shell-operator start --hooks-dir $(pwd)/hooks --tmp-dir $(pwd)/tmp --log-type color ``` -------------------------------- ### Snapshot Binding Configuration Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Demonstrates a binding configuration using `includeSnapshotsFrom` to fetch Pod labels and ConfigMap content for hook execution. ```yaml configVersion: v1 schedule: - name: periodic-checking crontab: "0 */3 * * *" includeSnapshotsFrom: ["monitor-pods", "configmap-content"] kubernetes: - name: configmap-content kind: ConfigMap nameSelector: matchNames: - "settings-for-my-hook" executeHookOnSynchronization: false executeHookOnEvent: [] - name: monitor-pods kind: Pod jqFilter: '.metadata.labels' includeSnapshotsFrom: ["configmap-content"] ``` -------------------------------- ### Shell Operator Start with Environment Variable Source: https://github.com/flant/shell-operator/blob/main/pkg/app/README.md Demonstrates starting the shell-operator when only an environment variable is set. The environment variable value is used as the configuration. ```bash export SHELL_OPERATOR_LISTEN_PORT=8080 shell-operator start # → cfg.App.ListenPort = "8080" ``` -------------------------------- ### JSON Hook Configuration Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md This is an example of a hook configuration in JSON format. It mirrors the YAML structure, defining bindings for various event types and settings. ```json { "configVersion": "v1", "onStartup": STARTUP_ORDER, "schedule": [ {SCHEDULE_PARAMETERS}, {SCHEDULE_PARAMETERS} ], "kubernetes": [ {KUBERNETES_PARAMETERS}, {KUBERNETES_PARAMETERS} ], "kubernetesValidating": [ {VALIDATING_PARAMETERS}, {VALIDATING_PARAMETERS} ], "kubernetesMutating": [ {MUTATING_PARAMETERS}, {MUTATING_PARAMETERS} ], "kubernetesCustomResourceConversion": [ {CONVERSION_PARAMETERS}, {CONVERSION_PARAMETERS} ], "settings": {SETTINGS_PARAMETERS} } ``` -------------------------------- ### Cleanup Kubernetes Resources and Image Source: https://github.com/flant/shell-operator/blob/main/examples/002-startup-python/README.md Deletes the Kubernetes namespace created for the example and removes the locally built Docker image. Run this after you are finished with the example. ```bash $ kubectl delete ns/example-startup-python $ docker rmi registry.mycompany.com/shell-operator:startup-python ``` -------------------------------- ### Example Validating Webhook Configuration Source: https://github.com/flant/shell-operator/blob/main/docs/src/BINDING_VALIDATING.md A minimal example of a kubernetesValidating binding configuration that triggers on CronTab object creation. ```yaml configVersion: v1 kubernetesValidating: - name: private-repo-policy.example.com rules: - apiGroups: ["stable.example.com"] apiVersions: ["v1"] operations: ["CREATE"] resources: ["crontabs"] scope: "Namespaced" ``` -------------------------------- ### Group Binding Context Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Example of a binding context for grouped bindings, showing snapshots for 'monitor-pods' and 'configmap-content'. The 'binding' field reflects the original binding name. ```yaml [ { "binding": "monitor-pods", "type": "Group", "snapshots": { "monitor-pods": [ { "object": { "kind": "Pod", "metadata": { "name": "etcd-...", "namespace": "kube-system", "..." : "..." } }, "filterResult": { "..." }, }, "..." ], "configmap-content": [ { "object": { "kind": "ConfigMap", "metadata": { "name": "etcd-...", "namespace": "kube-system", "..." : "..." } }, "filterResult": { "..." }, }, "..." ] } } ] ``` -------------------------------- ### Observe Hook Output in Logs Source: https://github.com/flant/shell-operator/blob/main/docs/src/QUICK_START.md Example log output from the shell-operator showing that the hook detected and logged a new Pod. ```plain ... INFO[0027] queue task HookRun:main operator.component=handleEvents queue=main INFO[0030] Execute hook binding=kubernetes hook=pods-hook.sh operator.component=taskRunner queue=main task=HookRun INFO[0030] Pod 'kubernetes-dashboard-775dd7f59c-hr7kj' added binding=kubernetes hook=pods-hook.sh output=stdout queue=main task=HookRun INFO[0030] Hook executed successfully binding=kubernetes hook=pods-hook.sh operator.component=taskRunner queue=main task=HookRun ... ``` -------------------------------- ### Shell Operator Start with CLI Flag Source: https://github.com/flant/shell-operator/blob/main/pkg/app/README.md Demonstrates starting the shell-operator when only a CLI flag is provided. The CLI flag value overrides any default. ```bash shell-operator start --listen-port=3000 # → cfg.App.ListenPort = "3000" ``` -------------------------------- ### Cleanup Resources Source: https://github.com/flant/shell-operator/blob/main/examples/102-monitor-namespaces/README.md Delete the Kubernetes namespace used for the example and remove the locally built Docker image. This ensures no lingering resources are left after the demonstration. ```bash $ kubectl delete ns/example-monitor-namespaces $ docker rmi registry.mycompany.com/shell-operator:monitor-namespaces ``` -------------------------------- ### Shell Operator Start with Env and CLI Flag Source: https://github.com/flant/shell-operator/blob/main/pkg/app/README.md Demonstrates starting the shell-operator when both an environment variable and a CLI flag are set. The CLI flag takes precedence. ```bash export SHELL_OPERATOR_LISTEN_PORT=8080 shell-operator start --listen-port=3000 # → cfg.App.ListenPort = "3000" ← CLI wins ``` -------------------------------- ### Cleanup Resources Source: https://github.com/flant/shell-operator/blob/main/examples/204-validating-webhook/README.md Removes the deployed example resources, including the Helm release, namespace, and the validating webhook configuration. ```shell helm delete --namespace=example-204 example-204 kubectl delete ns example-204 kubectl delete validatingwebhookconfiguration/example-204 ``` -------------------------------- ### Shell Operator Start with Default Value Source: https://github.com/flant/shell-operator/blob/main/pkg/app/README.md Demonstrates starting the shell-operator when neither an environment variable nor a CLI flag is provided. The hardcoded default value is used. ```bash shell-operator start # → cfg.App.ListenPort = "9115" ← hardcoded default ``` -------------------------------- ### Binding Context Snapshot Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/BINDING_VALIDATING.md Illustrates the structure of the binding context received by a kubernetesValidating hook, including the binding name, type, and snapshots. ```yaml [{ # Name as defined in binding configuration. "binding": "my-crd-validator.example.com", # Validating to distinguish from other events. "type": "Validating", # Snapshots as defined by includeSnapshotsFrom or group. "snapshots": { ... } }] ``` -------------------------------- ### Allow AdmissionReview Response with Warnings (Kubernetes 1.19+) Source: https://github.com/flant/shell-operator/blob/main/docs/src/BINDING_VALIDATING.md This example demonstrates how to allow an AdmissionReview request while also providing warnings to the user. This feature requires Kubernetes 1.19 or later. ```shell cat < $VALIDATING_RESPONSE_PATH {"allowed": true, "warnings":["It might be risky because it is Tuesday", "It might be risky because your name starts with A"]} EOF ``` -------------------------------- ### Build and Push Docker Image Source: https://github.com/flant/shell-operator/blob/main/examples/003-common-library/README.md Builds a shell-operator Docker image with custom scripts and pushes it to a registry. Ensure you have Docker installed and are logged into your registry. ```bash $ docker build -t "registry.mycompany.com/shell-operator:common-library" . $ docker push registry.mycompany.com/shell-operator:common-library ``` -------------------------------- ### Kubernetes Synchronization Binding Context Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md During startup, a hook monitoring Kubernetes objects receives a 'Synchronization' type binding context containing a list of existing objects. ```yaml configVersion: v1 kubernetes: - kind: Pod ``` ```json [ { "binding": "kubernetes", "type": "Synchronization", "objects": [ { "object": { "kind": "Pod", "metadata":{ "name":"etcd-...", "namespace":"kube-system", ... }, } }, { "object": { "kind": "Pod", "metadata": { "name": "kube-proxy-...", "namespace": "kube-system", ... }, } }, ... ] } ] ``` -------------------------------- ### Cleanup Shell-Operator Resources Source: https://github.com/flant/shell-operator/blob/main/examples/001-startup-shell/README.md Remove the created namespace and the custom Docker image. This ensures a clean state after the example. ```bash kubectl delete ns/example-startup-shell docker rmi registry.mycompany.com/shell-operator:startup-shell ``` -------------------------------- ### Kind Field Examples Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Illustrates different valid ways to specify the 'kind' field for monitoring Kubernetes resources, including case-insensitive names, plural forms, and short names. ```text "kind": "DaemonSet" "kind": "Daemonset" "kind": "daemonsets" "kind": "DaemonSets" "kind": "ds" ``` -------------------------------- ### Group Binding Configuration Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Configuration for a hook that uses grouped bindings to monitor Pod labels, ConfigMap data, and execute on a schedule. All bindings share the 'pods' group. ```yaml configVersion: v1 schedule: - name: periodic-checking crontab: "0 */3 * * *" group: "pods" kubernetes: - name: monitor-pods apiVersion: v1 kind: Pod jqFilter: '.metadata.labels' group: "pods" - name: configmap-content apiVersion: v1 kind: ConfigMap nameSelector: matchNames: ["settings-for-my-hook"] jqFilter: '.data' group: "pods" ``` -------------------------------- ### Schedule Binding Context Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md This is the binding context provided to a hook configured with a schedule binding. It includes the binding name and type. ```yaml configVersion: v1 schedule: - name: incremental crontab: "0 2 */3 * * *" allowFailure: true ``` ```json [{ "binding": "incremental", "type":"Schedule"}] ``` -------------------------------- ### Schedule Binding Context with Snapshots Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Example of a binding context for a schedule binding that includes snapshots from 'monitor-pods' and 'configmap-content'. This context is provided when a hook is executed on a schedule. ```yaml [ { "binding": "periodic-checking", "type": "Schedule", "snapshots": { "monitor-pods": [ { "object": { "kind": "Pod", "metadata": { "name": "etcd-...", "namespace": "kube-system", "...": "..." } }, "filterResult": { "..." } }, "..." ], "configmap-content": [ { "object": { "kind": "ConfigMap", "metadata": {"name": "settings-for-my-hook", "..." }, "data": {"field1": "..." } } } ] } } ] ``` -------------------------------- ### Build and Push Shell-Operator Image Source: https://github.com/flant/shell-operator/blob/main/examples/002-startup-python/README.md Builds a Docker image for shell-operator with custom scripts and pushes it to a registry. Ensure you have Docker installed and configured. ```bash $ docker build -t "registry.mycompany.com/shell-operator:startup-python" . $ docker push registry.mycompany.com/shell-operator:startup-python ``` -------------------------------- ### Build and Push Shell-Operator Image Source: https://github.com/flant/shell-operator/blob/main/examples/105-crd-simple/README.md Build a Docker image for Shell-Operator with a custom script and push it to a registry. This is the first step in deploying the crd-simple example. ```shell docker build -t "registry.mycompany.com/shell-operator:crd-simple" . docker push registry.mycompany.com/shell-operator:crd-simple ``` -------------------------------- ### Clean Up Kubernetes Resources Source: https://github.com/flant/shell-operator/blob/main/docs/src/QUICK_START.md These commands remove the namespace, cluster role, and cluster role binding created for the shell-operator example. ```sh kubectl delete ns example-monitor-pods kubectl delete clusterrole monitor-pods kubectl delete clusterrolebinding monitor-pods ``` -------------------------------- ### Configure Helm Tiller Source: https://github.com/flant/shell-operator/blob/main/examples/201-install-with-helm-chart/README.md Before installing the Helm chart, Tiller needs to be configured with a ServiceAccount that has cluster-admin privileges to manage releases across different namespaces. ```bash kubectl create serviceaccount tiller --namespace kube-system kubectl create clusterrolebinding tiller --clusterrole=cluster-admin --serviceaccount=kube-system:tiller helm init --service-account tiller ``` -------------------------------- ### Initialize Binding Context Controller Source: https://github.com/flant/shell-operator/blob/main/test/hook/context/README.md Creates a new instance of the binding context controller using the provided configuration and initial state. ```go c := context.NewBindingContextController(config, initialState) ``` -------------------------------- ### Deploy Shell-Operator with Startup Hook Source: https://github.com/flant/shell-operator/blob/main/examples/001-startup-shell/README.md Create a namespace and apply the shell-operator deployment manifest. Ensure the image tag matches the one built previously. ```bash kubectl create ns example-startup-shell kubectl -n example-startup-shell apply -f shell-operator-pod.yaml ``` -------------------------------- ### Run Controller for Initial Context Source: https://github.com/flant/shell-operator/blob/main/test/hook/context/README.md Executes the controller to generate the initial binding context. ```go contexts, err := c.Run() if err != nil { return err } testContexts(contexts) ``` -------------------------------- ### Deploy shell-operator manifests Source: https://github.com/flant/shell-operator/blob/main/examples/101-monitor-pods/README.md Creates the namespace and applies the RBAC and Pod configuration files. ```bash $ kubectl create ns example-monitor-pods $ kubectl -n example-monitor-pods apply -f shell-operator-rbac.yaml $ kubectl -n example-monitor-pods apply -f shell-operator-pod.yaml ``` -------------------------------- ### Applying Config to Legacy Globals Source: https://github.com/flant/shell-operator/blob/main/pkg/app/README.md Shows how to force an externally supplied configuration into legacy global variables, specifically for debug sub-commands that bypass the standard startup path. This ensures the global state reflects the custom configuration. ```go cfg := shapp.NewConfig() cfg.Debug.UnixSocket = "/run/myapp/debug.socket" shapp.ApplyConfig(cfg) // DebugUnixSocket now equals cfg.Debug.UnixSocket ``` -------------------------------- ### Verify Hook Execution via Logs Source: https://github.com/flant/shell-operator/blob/main/examples/230-configmap-python/README.md Command to inspect the shell-operator pod logs to confirm the ON_STARTUP hook execution. ```bash $ kubectl -n example-startup-python logs -f po/shell-operator ... INFO : Running hook '00-hook.py' binding 'ON_STARTUP' ... OnStartup Python powered hook ... ``` -------------------------------- ### Apply Kubernetes Manifests Source: https://github.com/flant/shell-operator/blob/main/examples/102-monitor-namespaces/README.md Apply the necessary Kubernetes manifests, including RBAC and the shell-operator deployment, to the specified namespace. Ensure the namespace 'example-monitor-namespaces' exists. ```bash $ kubectl create ns example-monitor-namespaces $ kubectl -n example-monitor-namespaces apply -f shell-operator-rbac.yaml $ kubectl -n example-monitor-namespaces apply -f shell-operator-pod.yaml ``` -------------------------------- ### jqFilter for Array Result Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Example of a `jqFilter` that returns the `filterResult` as an array. ```json "filterResult": [ "node-01", { "app": "proxy", "pod-template-hash": "cfdbfcbb8" } ] ``` -------------------------------- ### Shell-Operator Conversion Webhook Server Options Source: https://github.com/flant/shell-operator/blob/main/docs/src/BINDING_CONVERSION.md Lists command-line options and corresponding environment variables for setting up TLS certificates and service name for the conversion webhook server. ```bash --conversion-webhook-service-name="shell-operator-conversion-svc" A name of a service for clientConfig in CRD. Can be set with $CONVERSION_WEBHOOK_SERVICE_NAME. --conversion-webhook-server-cert="/conversion-certs/tls.crt" A path to a server certificate for clientConfig in CRD. Can be set with $CONVERSION_WEBHOOK_SERVER_CERT. --conversion-webhook-server-key="/conversion-certs/tls.key" A path to a server private key for clientConfig in CRD. Can be set with $CONVERSION_WEBHOOK_SERVER_KEY. --conversion-webhook-ca="/conversion-certs/ca.crt" A path to a ca certificate for clientConfig in CRD. Can be set with $CONVERSION_WEBHOOK_CA. --conversion-webhook-client-ca=CONVERSION-WEBHOOK-CLIENT-CA ... A path to a server certificate for CRD.spec.conversion.webhook. Can be set with $CONVERSION_WEBHOOK_CLIENT_CA. ``` -------------------------------- ### onStartup Binding Configuration Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Use this binding type to execute a hook at Shell-operator's startup. The ORDER parameter specifies the execution sequence. ```yaml configVersion: v1 onStartup: ORDER ``` -------------------------------- ### Apply Shell-Operator Pod Manifest Source: https://github.com/flant/shell-operator/blob/main/docs/src/QUICK_START.md Applies the Pod manifest to the Kubernetes cluster to start the shell-operator. ```sh kubectl -n example-monitor-pods apply -f shell-operator-pod.yaml ``` -------------------------------- ### Deploy shell-operator Manifests Source: https://github.com/flant/shell-operator/blob/main/examples/104-secret-copier/README.md Create the dedicated namespace and apply the RBAC and pod configuration files. ```sh kubectl create ns secret-copier && kubectl -n secret-copier apply -f shell-operator-rbac.yaml && kubectl -n secret-copier apply -f shell-operator-pod.yaml ``` -------------------------------- ### Running configuration tests Source: https://github.com/flant/shell-operator/blob/main/pkg/app/README.md Execute the configuration tests using `go test`. This command runs tests for flag binding, environment variable parsing, CLI flag behavior, and environment variable overrides. ```bash go test ./pkg/app/ -v -run 'TestBindFlags|TestParseEnv|TestCLIFlag|TestEnvOverrides' ``` -------------------------------- ### Clean Up Resources Source: https://github.com/flant/shell-operator/blob/main/examples/003-common-library/README.md Removes the deployed shell-operator namespace and deletes the Docker image. This ensures a clean state after the example. ```bash $ kubectl delete ns/example-common-library $ docker rmi registry.mycompany.com/shell-operator:common-library ``` -------------------------------- ### Build and Push Docker Image Source: https://github.com/flant/shell-operator/blob/main/examples/106-monitor-events/README.md Build a Docker image for shell-operator with a custom script and push it to a registry. ```bash docker build -t "registry.mycompany.com/shell-operator:monitor-events" . docker push registry.mycompany.com/shell-operator:monitor-events ``` -------------------------------- ### View Shell-Operator Logs Source: https://github.com/flant/shell-operator/blob/main/examples/201-install-with-helm-chart/README.md Check the logs of the shell-operator deployment in the 'example-helm' namespace to confirm that the hook was executed after the 'foobar' namespace was created. ```bash kubectl -n example-helm logs deploy/shell-operator ``` -------------------------------- ### Verify Python Hook Execution Source: https://github.com/flant/shell-operator/blob/main/examples/002-startup-python/README.md Streams the logs of the shell-operator pod to verify that the '00-hook.py' was executed. This command should be run after the operator has started. ```bash $ kubectl -n example-startup-python logs -f po/shell-operator ...INFO : Running hook '00-hook.py' binding 'ON_STARTUP' ... OnStartup Python powered hook ... ``` -------------------------------- ### Disable Full Object Dumps in Snapshots Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Example configuration to disable full object dumps in synchronization binding contexts when using snapshots. ```yaml kubernetes: - name: pods kinds: Pod keepFullObjectsInMemory: false ``` -------------------------------- ### Select Default Namespace Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md To monitor events from the 'default' namespace, explicitly define `namespace.nameSelector`. ```yaml namespace: nameSelector: ["default"] ``` -------------------------------- ### Upgrade Helm Release Source: https://github.com/flant/shell-operator/blob/main/examples/201-install-with-helm-chart/README.md Upgrade the existing Helm release 'example-helm' to apply changes to the hook files. The deployment annotation with the hook file checksum ensures that changes are picked up. ```bash helm upgrade example-helm . --namespace example-helm ``` -------------------------------- ### Apply Kubernetes manifests Source: https://github.com/flant/shell-operator/blob/main/examples/200-advanced/README.md Creates a namespace and applies the RBAC and deployment configurations for shell-operator. ```bash $ kubectl create ns example-advanced $ kubectl -n example-advanced apply -f shell-operator-rbac.yaml $ kubectl -n example-advanced apply -f shell-operator-deploy.yaml ``` -------------------------------- ### Build and Push shell-operator Image Source: https://github.com/flant/shell-operator/blob/main/examples/104-secret-copier/README.md Build the container image and push it to a private registry before deployment. ```sh docker build -t "registry.mycompany.com/shell-operator:secret-copier" . && docker push registry.mycompany.com/shell-operator:secret-copier ``` -------------------------------- ### AdmissionReview Object Structure Source: https://github.com/flant/shell-operator/blob/main/docs/src/BINDING_VALIDATING.md This is an example of the AdmissionReview object structure received by a validating webhook. It contains details about the request, including the user, operation, and the object being modified. ```yaml review: apiVersion: admission.k8s.io/v1 kind: AdmissionReview request: # Random uid uniquely identifying this admission call uid: "705ab4f5-6393-11e8-b7cc-42010a800002" # Fully-qualified group/version/kind of the incoming object kind: {"group":"autoscaling","version":"v1","kind":"Scale"} # Fully-qualified group/version/kind of the resource being modified resource: {"group":"apps","version":"v1","resource":"deployments"} # subresource, if the request is to a subresource subResource: "scale" # Fully-qualified group/version/kind of the incoming object in the original request to the API server. # This only differs from `kind` if the webhook specified `matchPolicy: Equivalent` and the # original request to the API server was converted to a version the webhook registered for. requestKind: {"group":"autoscaling","version":"v1","kind":"Scale"} # Fully-qualified group/version/kind of the resource being modified in the original request to the API server. # This only differs from `resource` if the webhook specified `matchPolicy: Equivalent` and the # original request to the API server was converted to a version the webhook registered for. requestResource: {"group":"apps","version":"v1","resource":"deployments"} # subresource, if the request is to a subresource # This only differs from `subResource` if the webhook specified `matchPolicy: Equivalent` and the # original request to the API server was converted to a version the webhook registered for. requestSubResource: "scale" # Name of the resource being modified name: "my-deployment" # Namespace of the resource being modified, if the resource is namespaced (or is a Namespace object) namespace: "my-namespace" # operation can be CREATE, UPDATE, DELETE, or CONNECT operation: "UPDATE" userInfo: # Username of the authenticated user making the request to the API server username: "admin" # UID of the authenticated user making the request to the API server uid: "014fbff9a07c" # Group memberships of the authenticated user making the request to the API server groups: ["system:authenticated","my-admin-group"] # Arbitrary extra info associated with the user making the request to the API server. # This is populated by the API server authentication layer and should be included # if any SubjectAccessReview checks are performed by the webhook. extra: some-key: ["some-value1", "some-value2"] # object is the new object being admitted. # It is null for DELETE operations. object: {"apiVersion":"autoscaling/v1","kind":"Scale",...} # oldObject is the existing object. # It is null for CREATE and CONNECT operations. oldObject: {"apiVersion":"autoscaling/v1","kind":"Scale",...} # options contains the options for the operation being admitted, like meta.k8s.io/v1 CreateOptions, UpdateOptions, or DeleteOptions. # It is null for CONNECT operations. options: {"apiVersion":"meta.k8s.io/v1","kind":"UpdateOptions",...} # dryRun indicates the API request is running in dry run mode and will not be persisted. # Webhooks with side effects should avoid actuating those side effects when dryRun is true. # See http://k8s.io/docs/reference/using-api/api-concepts/#make-a-dry-run-request for more details. dryRun: false ``` -------------------------------- ### Select Pods by Status Phase using fieldSelector Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Example of how to use a fieldSelector to filter Pods based on their 'status.phase' field. This configuration is used within a Kubernetes resource definition. ```yaml kind: Pod fieldSelector: matchExpressions: - field: "status.phase" operator: Equals value: Running ``` -------------------------------- ### Handling Slice Fields with pflag Source: https://github.com/flant/shell-operator/blob/main/pkg/app/README.md Demonstrates a pattern for handling slice fields like ClientCA when using pflag. It involves saving environment values, binding a separate CLI-only slice, and a post-parse fixup to prioritize CLI input or fall back to environment values. ```go envClientCA := cfg.Admission.ClientCA // save env value var cliClientCA []string f.StringArrayVar(&cliClientCA, "validating-webhook-client-ca", nil, "...") // post-parse fixup: if len(cliClientCA) > 0 { cfg.Admission.ClientCA = cliClientCA } else { cfg.Admission.ClientCA = envClientCA } ``` -------------------------------- ### Apply Kubernetes Manifests Source: https://github.com/flant/shell-operator/blob/main/examples/105-crd-simple/README.md Apply the necessary Kubernetes manifests, including RBAC, the custom resource definition, and the Shell-Operator pod configuration. Ensure the namespace is created first. ```shell kubectl create ns example-crd-simple kubectl -n example-crd-simple apply -f shell-operator-rbac.yaml kubectl -n example-crd-simple apply -f crd-simple.yaml kubectl -n example-crd-simple apply -f shell-operator-pod.yaml ``` -------------------------------- ### Kubernetes Event Binding Context Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md When a Kubernetes object event occurs (e.g., Pod added), the hook receives an 'Event' type binding context with details about the event and the object. ```yaml configVersion: v1 kubernetes: - kind: Pod ``` ```json [ { "binding": "kubernetes", "type": "Event", "watchEvent": "Added", "object": { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "pod-321d12", "namespace": "default", ... }, "spec": { ... }, ... } } ] ``` -------------------------------- ### Build and Push Shell-Operator Image Source: https://github.com/flant/shell-operator/blob/main/examples/001-startup-shell/README.md Build a Docker image with custom scripts and push it to a registry. This is the first step in deploying a custom shell-operator. ```bash docker build -t "registry.mycompany.com/shell-operator:startup-shell" . docker push registry.mycompany.com/shell-operator:startup-shell ``` -------------------------------- ### User Error Message Example Source: https://github.com/flant/shell-operator/blob/main/docs/src/BINDING_VALIDATING.md This illustrates the error message a user would see when an admission webhook denies their request. The message includes the webhook name and the reason provided in the response. ```text Error from server: admission webhook "policy.example.com" denied the request: You cannot do this because it is Tuesday and your name starts with A ``` -------------------------------- ### Embedding Shell-Operator as a Go Library Source: https://github.com/flant/shell-operator/blob/main/pkg/app/README.md Illustrates the typical flow for embedding shell-operator within another binary. It shows how to build a custom *app.Config and then assemble the shell-operator engine using this configuration. ```go import ( shell_operator "github.com/flant/shell-operator/pkg/shell-operator" shapp "github.com/flant/shell-operator/pkg/app" ) // 1. Build the config from whatever sources you have. cfg := shapp.NewConfig() // start from hardcoded defaults cfg.App.ListenAddress = myapp.ListenAddress cfg.App.ListenPort = myapp.ListenPort cfg.Kube.Context = myapp.KubeContext cfg.Kube.Config = myapp.KubeConfig cfg.Kube.ClientQPS = myapp.KubeClientQPS cfg.Kube.ClientBurst = myapp.KubeClientBurst cfg.ObjectPatcher.KubeClientQPS = myapp.ObjectPatcherKubeClientQPS cfg.ObjectPatcher.KubeClientBurst = myapp.ObjectPatcherKubeClientBurst cfg.ObjectPatcher.KubeClientTimeout = myapp.ObjectPatcherKubeClientTimeout cfg.Log.Level = myapp.LogLevel // 2. Construct the engine and assemble its common parts from the config. so := shell_operator.NewShellOperator(ctx, ms, hms, shell_operator.WithLogger(logger.Named("shell-operator")), ) err := so.AssembleCommonOperatorFromConfig(cfg, []string{ "module", "hook", "binding", "queue", "kind", }) ``` -------------------------------- ### Cleanup Kubernetes Resources and Image Source: https://github.com/flant/shell-operator/blob/main/examples/105-crd-simple/README.md Remove all created Kubernetes resources, including cluster roles, namespaces, and CRDs, and delete the Docker image. This command sequence cleans up the environment after running the example. ```shell kubectl delete clusterrolebinding/crd-simple kubectl delete clusterrole/crd-simple kubectl delete ns/example-crd-simple kubectl delete crd/crontabs.stable.example.com docker rmi registry.mycompany.com/shell-operator:crd-simple ``` -------------------------------- ### Create Valid CronTab Source: https://github.com/flant/shell-operator/blob/main/examples/204-validating-webhook/README.md Creates a valid CronTab resource that adheres to the policy, allowing images only from 'repo.example.com'. ```shell $ kubectl -n example-204 apply -f crontab-valid.yaml crontab.stable.example.com/crontab-valid created $ kubectl -n example-204 get crontab NAME AGE crontab-valid 9s ``` -------------------------------- ### Apply Kubernetes Manifests Source: https://github.com/flant/shell-operator/blob/main/examples/106-monitor-events/README.md Apply necessary Kubernetes manifests including RBAC and the shell-operator pod definition. ```bash kubectl create ns example-monitor-events kubectl -n example-monitor-events apply -f shell-operator-rbac.yaml kubectl -n example-monitor-events apply -f shell-operator-pod.yaml ``` -------------------------------- ### Build and Push Shell-Operator Image Source: https://github.com/flant/shell-operator/blob/main/examples/102-monitor-namespaces/README.md Build a Docker image for shell-operator with custom scripts and push it to a registry. This is the first step before deploying the operator. ```bash $ docker build -t "registry.mycompany.com/shell-operator:monitor-namespaces" . $ docker push registry.mycompany.com/shell-operator:monitor-namespaces ``` -------------------------------- ### Deploy shell-operator pod Source: https://github.com/flant/shell-operator/blob/main/examples/103-schedule/README.md Creates a dedicated namespace and applies the shell-operator pod configuration. ```bash $ kubectl create ns example-schedule $ kubectl -n example-schedule apply -f shell-operator-pod.yaml ``` -------------------------------- ### Use metric shortcuts Source: https://github.com/flant/shell-operator/blob/main/docs/src/metrics/METRICS_FROM_HOOKS.md Shortcut syntax for metric operations; note that this feature may be deprecated in future releases. ```json {"name":"metric_name","add":1,"labels":{"label1":"value1"}} ``` -------------------------------- ### Build shell-operator image with Docker Source: https://github.com/flant/shell-operator/blob/main/examples/202-repack-build/README.md Use this command to build the shell-operator image from the current directory. ```bash docker build . -t my-repo/shell-operator:latest ``` -------------------------------- ### Config Struct Definition Source: https://github.com/flant/shell-operator/blob/main/pkg/app/README.md Defines the main configuration structure with nested settings for different components, each with environment variable prefixes. ```go type Config struct { App AppSettings `envPrefix:"SHELL_OPERATOR_"` Kube KubeSettings `envPrefix:"KUBE_"` ObjectPatcher ObjectPatcherSettings `envPrefix:"OBJECT_PATCHER_"` Admission AdmissionSettings `envPrefix:"VALIDATING_WEBHOOK_"` Conversion ConversionSettings `envPrefix:"CONVERSION_WEBHOOK_"` Debug DebugSettings `envPrefix:"DEBUG_"` Log LogSettings `envPrefix:"LOG_"` } ``` -------------------------------- ### Define Hook Configuration Source: https://github.com/flant/shell-operator/blob/main/test/hook/context/README.md Defines the hook configuration in YAML format for the binding context controller. ```go config := ` configVersion: v1 schedule: - name: every_minute crontab: '* * * * *' includeSnapshotsFrom: - pod kubernetes: - apiVersion: v1 name: pod kind: Pod watchEvent: - Added - Modified - Deleted namespace: nameSelector: matchNames: - default` ``` -------------------------------- ### Cleanup Helm Release and Namespace Source: https://github.com/flant/shell-operator/blob/main/examples/201-install-with-helm-chart/README.md Remove the Helm release 'example-helm' and the associated Kubernetes namespace 'example-helm' to clean up the deployed resources. ```bash helm delete --purge example-helm kubectl delete ns/example-helm ``` -------------------------------- ### "Event" Binding Context with Snapshots Source: https://github.com/flant/shell-operator/blob/main/docs/src/HOOKS.md Illustrates the 'Event' binding context structure when snapshots are provided, including the watched object and snapshot data. ```yaml [ { "binding": "monitor-pods", "type": "Event", "watchEvent": "Added", "object": { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "pod-321d12", "namespace": "default", ... }, "spec": { ... }, ... }, "filterResult": { ... }, "snapshots": { "configmap-content": [ { "object": { "kind": "ConfigMap", "metadata": {"name": "settings-for-my-hook", ... }, "data": {"field1": ... } } } ] } } ] ``` -------------------------------- ### Define Initial and New States Source: https://github.com/flant/shell-operator/blob/main/test/hook/context/README.md Defines the Kubernetes object states for testing hook triggers. ```go initialState := ` --- apiVersion: v1 kind: Pod metadata: name: pod-0 --- apiVersion: v1 kind: Pod metadata: name: pod-1 ` ``` ```go newState := ` --- apiVersion: v1 kind: Pod metadata: name: pod-0 ` ``` -------------------------------- ### Create Kubernetes Object (YAML) Source: https://github.com/flant/shell-operator/blob/main/docs/src/KUBERNETES.md Use 'Create' to create a Kubernetes object. This operation will fail if the object already exists. The object can be defined directly in YAML. ```yaml operation: Create object: apiVersion: v1 kind: ConfigMap metadata: namespace: default name: testcm data: ... ``` -------------------------------- ### Create Kubernetes Object (Stringified JSON) Source: https://github.com/flant/shell-operator/blob/main/docs/src/KUBERNETES.md Use 'Create' to create a Kubernetes object. This operation will fail if the object already exists. The object can be provided as a stringified JSON within YAML. ```yaml operation: Create object: | {"apiVersion":"v1", "kind":"ConfigMap", "metadata":{"namespace":"default","name":"testcm"}, "data":{"foo": "bar"}} ``` -------------------------------- ### Generate Certificates Source: https://github.com/flant/shell-operator/blob/main/examples/204-validating-webhook/README.md Automates the generation of certificates required for the HTTP server used by the ValidatingWebhookConfiguration. Requires the cfssl utility. ```shell ./gen-certs.sh ``` -------------------------------- ### Allow AdmissionReview Response Source: https://github.com/flant/shell-operator/blob/main/docs/src/BINDING_VALIDATING.md This snippet shows how to construct a simple 'allowed' response for an AdmissionReview request. The response is written to a file, typically $VALIDATING_RESPONSE_PATH. ```shell cat < $VALIDATING_RESPONSE_PATH {"allowed": true} EOF ```