### Install gator from source Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Build and install the gator binary directly from the Gatekeeper repository. ```bash go install github.com/open-policy-agent/gatekeeper/v3/cmd/gator@master ``` -------------------------------- ### Install policies Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Install single or multiple policies, bundles, or perform dry-run installations. ```bash # Install a single policy (template only) gator policy install k8srequiredlabels # Install multiple policies gator policy install k8srequiredlabels k8scontainerlimits # Install a bundle (templates + constraints) gator policy install --bundle pod-security-baseline # Install with warn enforcement (for safe rollout) gator policy install --bundle pod-security-baseline --enforcement-action=warn # Preview changes without applying gator policy install --bundle pod-security-baseline --dry-run ``` -------------------------------- ### Install policies using gator policy Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Install individual policies or pre-configured bundles. ```bash # Template only gator policy install k8srequiredlabels # Bundle includes templates + constraints gator policy install --bundle pod-security-baseline ``` -------------------------------- ### Run gator verify commands Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Command line examples for executing test suites. ```bash gator verify suite.yaml ``` ```bash gator verify ./... ``` ```bash gator verify path/to/suites/... --run "disallowed" ``` -------------------------------- ### Install gator via Homebrew Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Install the gator CLI using the Homebrew package manager on macOS or Linux. ```bash brew install gator ``` -------------------------------- ### Declare an ExpansionTemplate in a Suite Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Example configuration for testing generated resources using an expansion template. ```yaml apiVersion: test.gatekeeper.sh/v1alpha1 kind: Suite tests: - name: expansion template: template.yaml constraint: constraint.yaml expansion: expansion.yaml cases: - name: example-expand object: deployment.yaml assertions: - violations: yes ``` -------------------------------- ### List installed policies Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator List policies currently installed in the cluster in table or JSON format. ```bash # Table output (default) gator policy list # JSON output gator policy list --output=json ``` -------------------------------- ### View Aggregated Kubernetes Event Example Source: https://open-policy-agent.github.io/gatekeeper/website/docs/customize-startup Example of an aggregated Kubernetes event output when multiple violations occur within a short interval. ```text 39s Warning FailedAdmission namespace/test (combined from similar events): Admission webhook "validation.gatekeeper.sh" denied request, Resource Namespace: , Constraint: ns-must-have-gk, Message: you must provide labels: {"gatekeeper"} ``` -------------------------------- ### Install Constraint via kubectl Source: https://open-policy-agent.github.io/gatekeeper/website/docs/howto Command to apply a Constraint from a remote URL. ```bash kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/demo/basic/constraints/all_ns_must_have_gatekeeper.yaml ``` -------------------------------- ### Define resources for expansion Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Example manifest containing an ExpansionTemplate, a Deployment, an Assign mutation, and a Namespace definition. ```yaml apiVersion: expansion.gatekeeper.sh/v1alpha1 kind: ExpansionTemplate metadata: name: expand-deployments spec: applyTo: - groups: [ "apps" ] kinds: [ "Deployment" ] versions: [ "v1" ] templateSource: "spec.template" generatedGVK: kind: "Pod" group: "" version: "v1" --- apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment namespace: my-ns labels: app: nginx spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80 args: - "/bin/sh" --- apiVersion: mutations.gatekeeper.sh/v1alpha1 kind: Assign metadata: name: always-pull-image spec: applyTo: - groups: [ "" ] kinds: [ "Pod" ] versions: [ "v1" ] location: "spec.containers[name: *].imagePullPolicy" parameters: assign: value: "Always" match: source: "Generated" scope: Namespaced kinds: - apiGroups: [ ] kinds: [ ] namespaceSelector: matchExpressions: - key: admission.gatekeeper.sh/ignore operator: DoesNotExist --- # notice this file is providing the non default namespace `my-ns` apiVersion: v1 kind: Namespace metadata: name: my-ns ``` -------------------------------- ### Test Manifests with Gator Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Examples of testing manifests against policies using various input methods. ```bash cat my-manifest.yaml | gator test --filename=template-and-constraints/ ``` ```bash gator test -f=my-manifest.yaml -f=templates-and-constraints/ ``` ```bash cat my-manifest.yaml | gator test --image=localhost:5000/gator/template-library:v1 \ --image=localhost:5000/gator/constraints:v1 ``` -------------------------------- ### Running gator sync test with file inputs Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Example command usage specifying multiple files and directories for validation. ```bash gator sync test --filename="template.yaml" –-filename="syncsets/" --filename="manifest.yaml" ``` -------------------------------- ### View make tilt output Source: https://open-policy-agent.github.io/gatekeeper/website/docs/developers Example output showing the build process and container execution steps triggered by make tilt. ```bash make tilt docker build . \ -t gatekeeper-tooling \ -f build/tooling/Dockerfile [+] Building 1.5s (10/10) FINISHED => [internal] load build definition from Dockerfile 0.2s => => transferring dockerfile: 35B 0.1s => [internal] load .dockerignore 0.2s => => transferring context: 34B 0.0s => [internal] load metadata for docker.io/library/golang:1.17 1.0s => [auth] library/golang:pull token for registry-1.docker.io 0.0s => [1/5] FROM docker.io/library/golang:1.17@sha256:bd9823cdad5700fb4abe983854488749421d5b4fc84154c30dae474100468b85 0.0s => CACHED [2/5] RUN GO111MODULE=on go install sigs.k8s.io/controller-tools/cmd/controller-gen@v0.8.0 0.0s => CACHED [3/5] RUN GO111MODULE=on go install k8s.io/code-generator/cmd/conversion-gen@release-1.22 0.0s => CACHED [4/5] RUN mkdir /gatekeeper 0.0s => CACHED [5/5] WORKDIR /gatekeeper 0.0s => exporting to image 0.2s => => exporting layers 0.0s => => writing image sha256:7d2fecb230986ffdd78932ad8ff13aa0968c9a9a98bec2fe8ecb21c6e683c730 0.0s => => naming to docker.io/library/gatekeeper-tooling 0.0s docker run -v /workspaces/gatekeeper:/gatekeeper gatekeeper-tooling controller-gen object:headerFile=./hack/boilerplate.go.txt paths="./apis/..." paths="./pkg/..." docker run -v /workspaces/gatekeeper:/gatekeeper gatekeeper-tooling conversion-gen \ --output-base=/gatekeeper \ --input-dirs=./apis/mutations/v1beta1,./apis/mutations/v1alpha1 \ --go-header-file=./hack/boilerplate.go.txt \ --output-file-base=zz_generated.conversion ``` -------------------------------- ### Upgrade installed policies Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Upgrade specific policies or all installed policies, with an option to preview changes. ```bash # Upgrade a specific policy gator policy upgrade k8srequiredlabels # Upgrade all installed policies gator policy upgrade --all # Preview upgrades gator policy upgrade --all --dry-run ``` -------------------------------- ### Illustrate Location Parsing Source: https://open-policy-agent.github.io/gatekeeper/website/docs/mutation Example YAML structure demonstrating how the location path maps to resource elements. ```yaml spec: containers: - name: foo imagePullPolicy: ``` -------------------------------- ### Install a ConstraintTemplate via kubectl Source: https://open-policy-agent.github.io/gatekeeper/website/docs/howto Applies a remote ConstraintTemplate manifest to the cluster. ```bash kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/demo/basic/templates/k8srequiredlabels_template.yaml ``` -------------------------------- ### Mutated Object Example Source: https://open-policy-agent.github.io/gatekeeper/website/docs/externaldata Example of the resulting object after applying external data mutation. ```yaml ... metadata: annotations: owner: admin@example.com ... ``` -------------------------------- ### Benchmark Output Example Source: https://open-policy-agent.github.io/gatekeeper/website/docs/help Sample output generated by benchstat after running performance benchmarks on a pull request. ```text name old time/op new time/op delta pkg:github.com/open-policy-agent/gatekeeper/v3/pkg/mutation goos:linux goarch:amd64 System_Mutate 1.48µs ± 5% 1.50µs ± 4% ~ (p=0.468 n=10+10) pkg:github.com/open-policy-agent/gatekeeper/v3/pkg/mutation/mutators/assign goos:linux goarch:amd64 AssignMutator_Mutate/always_mutate_1-depth 235ns ± 5% 234ns ± 5% ~ (p=0.726 n=10+10) AssignMutator_Mutate/always_mutate_2-depth 287ns ± 6% 279ns ± 5% ~ (p=0.190 n=10+10) AssignMutator_Mutate/always_mutate_5-depth 420ns ± 2% 416ns ± 3% ~ (p=0.297 n=9+9) AssignMutator_Mutate/always_mutate_10-depth 556ns ± 4% 570ns ± 6% ~ (p=0.123 n=10+10) AssignMutator_Mutate/always_mutate_20-depth 977ns ± 3% 992ns ± 2% ~ (p=0.063 n=10+10) AssignMutator_Mutate/never_mutate_1-depth 196ns ± 4% 197ns ± 6% ~ (p=0.724 n=10+10) AssignMutator_Mutate/never_mutate_2-depth 221ns ± 4% 222ns ± 4% ~ (p=0.971 n=10+10) AssignMutator_Mutate/never_mutate_5-depth 294ns ± 4% 296ns ± 4% ~ (p=0.436 n=10+10) AssignMutator_Mutate/never_mutate_10-depth 424ns ± 2% 425ns ± 3% ~ (p=0.905 n=9+10) AssignMutator_Mutate/never_mutate_20-depth 682ns ± 3% 680ns ± 5% ~ (p=0.859 n=9+10) pkg:github.com/open-policy-agent/gatekeeper/v3/pkg/mutation/mutators/assignimage goos:linux goarch:amd64 AssignImageMutator_Mutate/always_mutate_1-depth 579ns ± 7% 573ns ± 3% ~ (p=0.650 n=9+9) AssignImageMutator_Mutate/always_mutate_2-depth 625ns ± 5% 627ns ± 2% ~ (p=0.536 n=10+9) AssignImageMutator_Mutate/always_mutate_5-depth 758ns ± 5% 768ns ± 6% ~ (p=0.631 n=10+10) AssignImageMutator_Mutate/always_mutate_10-depth 1.06µs ± 8% 1.08µs ± 5% ~ (p=0.143 n=10+10) AssignImageMutator_Mutate/always_mutate_20-depth 1.38µs ± 3% 1.42µs ± 3% +2.80% (p=0.003 n=9+10) AssignImageMutator_Mutate/never_mutate_1-depth 237ns ± 3% 233ns ± 3% ~ (p=0.107 n=10+9) AssignImageMutator_Mutate/never_mutate_2-depth 266ns ± 4% 266ns ± 3% ~ (p=1.000 n=10+10) AssignImageMutator_Mutate/never_mutate_5-depth 336ns ± 6% 342ns ± 2% +1.85% (p=0.037 n=10+9) AssignImageMutator_Mutate/never_mutate_10-depth 463ns ± 3% 479ns ± 5% +3.53% (p=0.013 n=9+10) AssignImageMutator_Mutate/never_mutate_20-depth 727ns ± 3% 727ns ± 2% ~ (p=0.897 n=10+8) ... ``` -------------------------------- ### Define Connection Custom Resource Source: https://open-policy-agent.github.io/gatekeeper/website/docs/export-driver Example YAML configuration to establish a connection to a specific backend driver. ```yaml apiVersion: connection.gatekeeper.sh/v1alpha1 kind: Connection metadata: name: audit-connection namespace: gatekeeper-system spec: driver: "foo" config: key: value ``` -------------------------------- ### Install Gatekeeper with Helm for Disk Export Source: https://open-policy-agent.github.io/gatekeeper/website/docs/export Helm command to install Gatekeeper with violation export enabled and disk backend configured. ```bash helm upgrade --install gatekeeper gatekeeper/gatekeeper --namespace gatekeeper-system \ --set enableViolationExport=true \ --set audit.connection=audit-connection \ --set audit.channel=audit-channel \ --set audit.exportConnection.path=tmp/violations/topics \ --set audit.exportConnection.maxAuditResults=3 \ --set exportBackend=disk \ ``` -------------------------------- ### Running gator sync test with OCI artifacts Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Example command usage combining a local configuration file with an OCI artifact containing templates. ```bash gator sync test --filename="config.yaml" --image=localhost:5000/gator/template-library:v1 ``` -------------------------------- ### Enable TLS in Go Server Source: https://open-policy-agent.github.io/gatekeeper/website/docs/externaldata Example of enabling TLS in a Go HTTP server using the generated certificate and key. ```go server.ListenAndServeTLS("/etc/ssl/certs/server.crt", "/etc/ssl/certs/server.key") ``` -------------------------------- ### Deploy Gatekeeper via Helm Source: https://open-policy-agent.github.io/gatekeeper/website/docs/install Installs Gatekeeper using the official Helm chart. ```bash helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts helm install gatekeeper/gatekeeper --name-template=gatekeeper --namespace gatekeeper-system --create-namespace ``` -------------------------------- ### Admission Control Configuration Source: https://open-policy-agent.github.io/gatekeeper/website/docs/externaldata Example configuration file for the Kubernetes API server to enable webhook authentication. ```yaml apiVersion: apiserver.config.k8s.io/v1 kind: AdmissionConfiguration plugins: - name: ValidatingAdmissionWebhook configuration: apiVersion: apiserver.config.k8s.io/v1 kind: WebhookAdmissionConfiguration kubeConfigFile: "" - name: MutatingAdmissionWebhook configuration: apiVersion: apiserver.config.k8s.io/v1 kind: WebhookAdmissionConfiguration kubeConfigFile: "" ``` -------------------------------- ### Gator verify test configuration Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Example configuration for a gator test case using an AdmissionReview object. ```yaml - name: both-disallowed object: path/to/test_admission_review.yaml assertions: - violations: 1 ``` -------------------------------- ### Create a Deployment with Privileged Containers Source: https://open-policy-agent.github.io/gatekeeper/website/docs/workload-resources A Deployment example that violates the privileged container constraint but is not blocked at the Deployment level. ```yaml apiVersion: apps/v1 kind: Deployment metadata: labels: app: i-wont-be-blocked name: i-wont-be-blocked spec: replicas: 1 selector: matchLabels: app: i-wont-be-blocked template: metadata: labels: app: i-wont-be-blocked spec: containers: - image: nginx name: nginx securityContext: privileged: true ``` -------------------------------- ### Rego Policy for ConstraintTemplate Source: https://open-policy-agent.github.io/gatekeeper/website/docs/howto Example Rego code snippet showing how to access parameters via input.parameters. ```rego rego: | package k8srequiredlabels violation[{"msg": msg, "details": {"missing_labels": missing}}] { provided := {label | input.review.object.metadata.labels[label]} required := {label | label := input.parameters.labels[_]} missing := required - provided count(missing) > 0 msg := sprintf("you must provide labels: %v", [missing]) } ``` -------------------------------- ### Grant Cluster Admin Permissions Source: https://open-policy-agent.github.io/gatekeeper/website/docs/install Required for installation methods to ensure sufficient privileges. ```bash kubectl create clusterrolebinding cluster-admin-binding \ --clusterrole cluster-admin \ --user ``` -------------------------------- ### Define Provider Custom Resource Source: https://open-policy-agent.github.io/gatekeeper/website/docs/externaldata Example configuration for the Provider custom resource including the caBundle. ```yaml apiVersion: externaldata.gatekeeper.sh/v1beta1 kind: Provider metadata: name: my-provider spec: url: https://.:/ # URL to the external data source (e.g., https://my-provider.my-namespace:8090/validate) timeout: # timeout value in seconds (e.g., 1). this is the timeout on the Provider custom resource, not the provider implementation. caBundle: # base64 encoded CA certificate. ``` -------------------------------- ### Example unfulfilled requirements output Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator The error output format displayed to stderr when sync requirements are not met. ```text the following requirements were not met: templatename1: - extensions/v1beta1:Ingress - networking.k8s.io/v1beta1:Ingress OR networking.k8s.io/v1:Ingress templatename2: - apps/v1:Deployment templatename3: - /v1:Service ``` -------------------------------- ### View Connection status Source: https://open-policy-agent.github.io/gatekeeper/website/docs/export Example of the status sub-resource for a Connection, showing pod-specific connection state and error details. ```yaml apiVersion: connection.gatekeeper.sh/v1alpha1 kind: Connection metadata: name: audit-connection namespace: gatekeeper-system spec: driver: "dapr" config: component: "pubsub" status: byPod: ID: "pod-id" ConnectionUID: "connection-id" Active: {true | false} Errors: - Type: UpsertConnection Message: "Error message" - Type: Publish Message: "Error message" ``` -------------------------------- ### KubeConfig File for Webhook Source: https://open-policy-agent.github.io/gatekeeper/website/docs/externaldata Example KubeConfig file structure required for the API server to communicate with the webhook service. ```yaml apiVersion: v1 clusters: - cluster: certificate-authority-data: # same value as provided in gatekeeper webhook secret's clientca.crt server: https://..svc:443 name: contexts: - context: cluster: user: api-server name: current-context: kind: Config users: - name: api-server user: client-certificate-data: client-key-data: ``` -------------------------------- ### Setup Gatekeeper Namespace and Dapr Pubsub Source: https://open-policy-agent.github.io/gatekeeper/website/docs/export Creates the required namespace, migrates the Redis secret, and applies the Dapr pubsub component configuration. ```bash kubectl create namespace gatekeeper-system kubectl get secret redis --namespace=default -o yaml | sed 's/namespace: .*/namespace: gatekeeper-system/' | kubectl apply -f - kubectl apply -f - < has an invalid image repo , allowed repos are ["openpolicyagent"] pod/pause created ``` -------------------------------- ### ConstraintTemplate using Rego v1 syntax Source: https://open-policy-agent.github.io/gatekeeper/website/docs/constrainttemplates A complete example of a ConstraintTemplate implementing Rego v1 syntax to enforce required labels on Kubernetes objects. ```yaml apiVersion: templates.gatekeeper.sh/v1 kind: ConstraintTemplate metadata: name: k8srequiredlabels spec: crd: spec: names: kind: K8sRequiredLabels validation: # Schema for the `parameters` field openAPIV3Schema: type: object properties: message: type: string labels: type: array items: type: object properties: key: type: string allowedRegex: type: string targets: - target: admission.k8s.gatekeeper.sh code: - engine: Rego source: version: "v1" rego: | package k8srequiredlabels violation contains {"msg": msg, "details": {"missing_labels": missing}} if { provided := {label | input.review.object.metadata.labels[label]} required := {label | label := input.parameters.labels[_]} missing := required - provided count(missing) > 0 msg := sprintf("you must provide labels: %v", [missing]) } ``` -------------------------------- ### View Admission Review Stats Log Source: https://open-policy-agent.github.io/gatekeeper/website/docs/metrics Example JSON log output generated when --log-stats-admission is enabled, showing execution time and constraint counts. ```json { "level": "info", "ts": 1683692576.9093642, "logger": "webhook", "msg": "admission review request stats", "hookType": "validation", "process": "admission", "event_type": "review_response_stats", "resource_group": "", "resource_api_version": "v1", "resource_kind": "Namespace", "resource_namespace": "", "request_username": "kubernetes-admin", "execution_stats": [ { "scope": "template", "statsFor": "K8sRequiredLabels", "stats": [ { "name": "templateRunTimeNS", "value": 762561, "source": { "type": "engine", "value": "Rego" }, "description": "the number of nanoseconds it took to evaluate all constraints for a template" }, { "name": "constraintCount", "value": 1, "source": { "type": "engine", "value": "Rego" }, "description": "the number of constraints that were evaluated for the given constraint kind" } ], "labels": [ { "name": "TracingEnabled", "value": false }, { "name": "PrintEnabled", "value": false }, { "name": "target", "value": "admission.k8s.gatekeeper.sh" } ] } ] } ``` -------------------------------- ### Run the Tilt development environment Source: https://open-policy-agent.github.io/gatekeeper/website/docs/developers Execute the make command to initiate the Tilt development workflow. ```bash make tilt ``` -------------------------------- ### Apply Sample Policy Source: https://open-policy-agent.github.io/gatekeeper/website/docs/remote-cluster Deploys a template and constraint to the remote cluster for testing purposes. ```bash # Apply a template + constraint to the remote cluster kubectl --context apply -f \ https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/test/bats/tests/remote-cluster/k8srequiredlabels_template.yaml kubectl --context apply -f \ https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/test/bats/tests/remote-cluster/k8srequiredlabels_constraint.yaml ``` -------------------------------- ### Prepare Tilt Development Environment Source: https://open-policy-agent.github.io/gatekeeper/website/docs/developers Copies generated charts to the Tilt build directory and modifies security contexts to enable live updates. ```bash mkdir -p .tiltbuild/charts rm -rf .tiltbuild/charts/gatekeeper cp -R manifest_staging/charts/gatekeeper .tiltbuild/charts # disable some configs from the security context so we can perform live update sed -i "/readOnlyRootFilesystem: true/d" .tiltbuild/charts/gatekeeper/templates/*.yaml sed -i -e "/run.*: .*/d" .tiltbuild/charts/gatekeeper/templates/*.yaml tilt up ``` -------------------------------- ### Uninstall policies Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Remove installed policies from the cluster, with an option to preview the action. ```bash # Uninstall a policy gator policy uninstall k8srequiredlabels # Preview uninstall gator policy uninstall k8srequiredlabels --dry-run ``` -------------------------------- ### Build Manifests and Helm Charts Source: https://open-policy-agent.github.io/gatekeeper/website/docs/developers Cleans staging directories and uses Kustomize to build Gatekeeper manifests and Helm charts. ```bash rm -rf manifest_staging mkdir -p manifest_staging/deploy/experimental mkdir -p manifest_staging/charts/gatekeeper docker run --rm -v /workspaces/gatekeeper:/gatekeeper \ registry.k8s.io/kustomize/kustomize:v3.8.9 build \ /gatekeeper/config/default -o /gatekeeper/manifest_staging/deploy/gatekeeper.yaml docker run --rm -v /workspaces/gatekeeper:/gatekeeper \ registry.k8s.io/kustomize/kustomize:v3.8.9 build \ --load_restrictor LoadRestrictionsNone /gatekeeper/cmd/build/helmify | go run cmd/build/helmify/*.go ``` -------------------------------- ### Apply Config via kubectl Source: https://open-policy-agent.github.io/gatekeeper/website/docs/sync Command to apply a sample configuration file for data replication. ```bash kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/demo/basic/sync.yaml ``` -------------------------------- ### Declare Case assertions Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Examples of asserting violation expectations in a test case. ```yaml assertions: - violations: yes ``` ```yaml assertions: - violations: no ``` -------------------------------- ### Mutated Object for Assign Source: https://open-policy-agent.github.io/gatekeeper/website/docs/externaldata Example of the resulting object after applying an Assign mutation. ```yaml ... spec: containers: - name: nginx image: nginx:v1.2.3 ... ``` -------------------------------- ### Configure Mutation Operations Source: https://open-policy-agent.github.io/gatekeeper/website/docs/mutation Example of restricting a mutation to only trigger during resource creation. ```yaml applyTo: - groups: [""] kinds: ["Pod"] versions: ["v1"] operations: ["CREATE"] # Only mutate on resource creation ``` -------------------------------- ### Define Constraint for Specific Kinds Source: https://open-policy-agent.github.io/gatekeeper/website/docs/audit Example of a constraint that restricts auditing to Pod resources. ```yaml apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sAllowedRepos metadata: name: prod-repo-is-openpolicyagent spec: match: kinds: - apiGroups: [""] kinds: ["Pod"] ... ``` -------------------------------- ### AdmissionReview for DELETE operation Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Example of an AdmissionReview object configured for a DELETE operation using oldObject. ```yaml kind: AdmissionReview apiVersion: admission.k8s.io/v1beta1 request: operation: "DELETE" userInfo: username: "system:foo" oldObject: kind: Pod labels: - app: "bar" ``` -------------------------------- ### Run gator expand with files or images Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Use the --filename flag to specify local manifests or directories, or the --image flag to pull configurations from an OCI artifact. ```bash gator expand --filename="manifest.yaml" –filename="expansion-policy/" ``` ```bash gator expand --filename="my-deployment.yaml" --image=localhost:5000/gator/expansion-policy:v1 ``` -------------------------------- ### Implement Driver Connection Structure Source: https://open-policy-agent.github.io/gatekeeper/website/docs/export-driver Define the connection state and driver name for a new backend implementation. ```go type Connection struct { // properties needed for individual connection } type Foo struct { openConnections map[string]Connection } const ( Name = "foo" ) var Connections = &Foo{ openConnections: make(map[string]Connection), } ``` -------------------------------- ### Configure tilt-settings.json Source: https://open-policy-agent.github.io/gatekeeper/website/docs/developers Define local deployment settings such as Helm values and trigger modes in the project root. ```json { "helm_values": { "controllerManager.metricsPort": 8080, "enableExternalData": true }, "trigger_mode": "manual" } ``` -------------------------------- ### Define a K8sRequiredLabels Constraint Source: https://open-policy-agent.github.io/gatekeeper/website/docs/howto Example of a Constraint enforcing the presence of a 'gatekeeper' label on all Namespace resources. ```yaml apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabels metadata: name: ns-must-have-gk spec: match: kinds: - apiGroups: [""] kinds: ["Namespace"] parameters: labels: ["gatekeeper"] ``` -------------------------------- ### Implement Driver Interface Methods Source: https://open-policy-agent.github.io/gatekeeper/website/docs/export-driver Required methods for the driver to handle connection lifecycle and message publishing. ```go func (r *Foo) Publish(ctx context.Context, connectionName string, data interface{}, subject string) error { ... } func (r *Foo) CloseConnection(connectionName string) error { ... } func (r *Foo) UpdateConnection(ctx context.Context, connectionName string, config interface{}) error { ... } func (r *Foo) CreateConnection(ctx context.Context, connectionName string, config interface{}) error { ... } ``` -------------------------------- ### Deploy Gatekeeper from Source Source: https://open-policy-agent.github.io/gatekeeper/website/docs/install Deploys the built image to the cluster. ```bash make deploy REPOSITORY=$DESTINATION_GATEKEEPER_IMAGE ``` -------------------------------- ### Audit Log Event Source: https://open-policy-agent.github.io/gatekeeper/website/docs/audit Example of a JSON-formatted audit log event emitted by the audit pod. ```json { "level": "info", "ts": 1632889070.3075402, "logger": "controller", "msg": "container has no resource limits", "process": "audit", "audit_id": "2021-09-29T04:17:47Z", "event_type": "violation_audited", "constraint_group": "constraints.gatekeeper.sh", "constraint_api_version": "v1beta1", "constraint_kind": "K8sContainerLimits", "constraint_name": "container-must-have-limits", "constraint_namespace": "", "constraint_action": "deny", "constraint_enforcement_actions": [], "constraint_annotations": { "test-annotation-1": "annotation_1" }, "resource_group": "", "resource_api_version": "v1", "resource_kind": "Pod", "resource_namespace": "kube-system", "resource_name": "kube-scheduler-kind-control-plane" "resource_labels": { "env": "prod", "my-app-system": "true" } } ``` -------------------------------- ### Uninstall Gatekeeper via Prebuilt Image Source: https://open-policy-agent.github.io/gatekeeper/website/docs/install Removes Gatekeeper components installed via manifest URL. ```bash kubectl delete -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/v3.23.0/deploy/gatekeeper.yaml ``` -------------------------------- ### Run gator bench Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Execute the benchmark command by specifying the directory or file containing policies and resources. ```bash gator bench --filename=policies/ ``` -------------------------------- ### Create a kind cluster with a local registry Source: https://open-policy-agent.github.io/gatekeeper/website/docs/developers Provision a Kubernetes cluster with a local registry to optimize image push and pull operations. ```bash ./third_party/github.com/tilt-dev/kind-local/kind-with-registry.sh ``` -------------------------------- ### Compare Rego and CEL engines Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Runs benchmarks for both engines and displays a comparison table. ```bash gator bench --filename=policies/ --engine=all ``` -------------------------------- ### Deploy Gatekeeper via Prebuilt Image Source: https://open-policy-agent.github.io/gatekeeper/website/docs/install Deploys a specific released version of Gatekeeper using a manifest URL. ```bash kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/v3.23.0/deploy/gatekeeper.yaml ``` -------------------------------- ### Valid structural schema Source: https://open-policy-agent.github.io/gatekeeper/website/docs/constrainttemplates An example of a valid structural schema for a v1 ConstraintTemplate with the required type declaration. ```yaml openAPIV3Schema: type: object properties: labels: type: array items: type: string ``` -------------------------------- ### List all constraints via kubectl Source: https://open-policy-agent.github.io/gatekeeper/website/docs/howto Use this command to retrieve a list of all constraints currently deployed in the cluster. ```bash kubectl get constraints ``` -------------------------------- ### Invalid non-structural schema Source: https://open-policy-agent.github.io/gatekeeper/website/docs/constrainttemplates An example of an invalid schema for a v1 ConstraintTemplate due to the missing type declaration. ```yaml openAPIV3Schema: # missing type properties: labels: type: array items: type: string ``` -------------------------------- ### Define a v1beta1 ConstraintTemplate Source: https://open-policy-agent.github.io/gatekeeper/website/docs/constrainttemplates Example of a ConstraintTemplate using the v1beta1 API version, which does not require a structural schema. ```yaml apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: k8srequiredlabels spec: crd: spec: names: kind: K8sRequiredLabels validation: # Schema for the `parameters` field openAPIV3Schema: properties: labels: type: array items: type: string targets: - target: admission.k8s.gatekeeper.sh rego: | package k8srequiredlabels violation[{"msg": msg, "details": {"missing_labels": missing}}] { provided := {label | input.review.object.metadata.labels[label]} required := {label | label := input.parameters.labels[_]} missing := required - provided count(missing) > 0 msg := sprintf("you must provide labels: %v", [missing]) } ``` -------------------------------- ### View Constraint with Violations Source: https://open-policy-agent.github.io/gatekeeper/website/docs/audit Example of a Constraint resource showing the status field populated with detected violations. ```yaml apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabels metadata: name: ns-must-have-gk spec: match: kinds: - apiGroups: [""] kinds: ["Namespace"] parameters: labels: ["gatekeeper"] status: auditTimestamp: "2019-05-11T01:46:13Z" enforced: true violations: - enforcementAction: deny group: "" version: v1 kind: Namespace message: 'you must provide labels: {"gatekeeper"}' name: default - enforcementAction: deny group: "" version: v1 kind: Namespace message: 'you must provide labels: {"gatekeeper"}' name: gatekeeper-system - enforcementAction: deny group: "" version: v1 kind: Namespace message: 'you must provide labels: {"gatekeeper"}' name: kube-public - enforcementAction: deny group: "" version: v1 kind: Namespace message: 'you must provide labels: {"gatekeeper"}' name: kube-system ``` -------------------------------- ### Register New Driver Source: https://open-policy-agent.github.io/gatekeeper/website/docs/export-driver Add the new driver's connection instance to the supportedDrivers map in system.go. ```go var supportedDrivers = map[string]driver.Driver{ dapr.Name: dapr.Connections, foo.Name: foo.Connections, } ``` -------------------------------- ### Generate a policy catalog Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Generate a catalog file from a local gatekeeper-library directory. ```bash # Generate catalog from gatekeeper-library gator policy generate-catalog --library-path=/path/to/gatekeeper-library # Generate with custom output path gator policy generate-catalog --library-path=. --output=catalog.yaml # Generate with bundles file gator policy generate-catalog --library-path=. --bundles=bundles.yaml # Generate with custom version gator policy generate-catalog --library-path=. --version=v1.2.0 ``` -------------------------------- ### AssignMetadata CRD Example Source: https://open-policy-agent.github.io/gatekeeper/website/docs/mutation Defines a mutation to add an owner annotation to Pods matching the nginx-* name pattern. ```yaml apiVersion: mutations.gatekeeper.sh/v1 kind: AssignMetadata metadata: name: demo-annotation-owner spec: match: scope: Namespaced name: nginx-* kinds: - apiGroups: ["*"] kinds: ["Pod"] location: "metadata.annotations.owner" parameters: assign: value: "admin" ``` -------------------------------- ### Opt-out of Audit in Constraints Source: https://open-policy-agent.github.io/gatekeeper/website/docs/audit Example of a constraint configured to opt-out of the audit process using scoped enforcement actions. ```yaml apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sAllowedRepos metadata: name: prod-repo-is-openpolicyagent spec: ... enforcementAction: scoped scopedEnforcementActions: - action: warn enforcementPoints: - name: "validation.gatekeeper.sh" - action: deny enforcementPoints: - name: "gator.gatekeeper.sh" ... ``` -------------------------------- ### View Gatekeeper configuration flags Source: https://open-policy-agent.github.io/gatekeeper/website/docs/customize-startup Displays all available configuration flags for a specific Gatekeeper version using the --help flag. ```bash docker run openpolicyagent/gatekeeper:v3.10.0-beta.0 --help ``` -------------------------------- ### Set benchmark comparison thresholds Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator Configures percentage and absolute minimum thresholds for regression detection. ```bash gator bench --filename=policies/ --compare=baseline.json --threshold=10 --min-threshold=100µs ``` -------------------------------- ### Define a Connection resource for Dapr Source: https://open-policy-agent.github.io/gatekeeper/website/docs/export Example configuration for a Connection custom resource using the Dapr driver to export violations. ```yaml apiVersion: connection.gatekeeper.sh/v1alpha1 kind: Connection metadata: name: audit-connection namespace: gatekeeper-system spec: driver: "dapr" config: component: "pubsub" ``` -------------------------------- ### Disable external data via Helm Source: https://open-policy-agent.github.io/gatekeeper/website/docs/externaldata Use the --set flag during Helm installation to disable external data support. ```bash helm install gatekeeper/gatekeeper --name-template=gatekeeper --namespace gatekeeper-system --create-namespace \ --set enableExternalData=false ``` -------------------------------- ### Example metadata.gatekeeper.sh/requires-sync-data annotation Source: https://open-policy-agent.github.io/gatekeeper/website/docs/gator A JSON object representing a list of requirements for data replication, where each requirement contains interchangeable GVK clauses. ```json [ [ { "groups": ["group1", group2"], "versions": ["version1", "version2", "version3"], "kinds": ["kind1", "kind2"] }, { "groups": ["group3", group4"], "versions": ["version3", "version4"], "kinds": ["kind3", "kind4"] } ], [ { "groups": ["group5"], "versions": ["version5"], "kinds": ["kind5"] } ] ] ```