This topic illustrates how to use Policy Controller constraints to achieve many of the same protections as PodSecurityPolicies, with the added ability to test your policies before enforcing them. The examples in this topic do not cover every related constraint, but show how to get started.
Before you begin
Install Policy Controller on one of your clusters enrolled in Anthos Config Management. Be sure to leave the constraint template library enabled.
The source code for the constraints and constraint templates discussed in this topic is available in the pod-security-policy directory of the Gatekeeper project repository. Each of the constraint templates includes unit tests as well.
Preventing Pods from running privileged containers
An example in the topic on PodSecurityPolicies prevents Pods from running privileged containers. This is recommended, because privileged containers can potentially impact the host operating system on the node or other workloads running on the node.
This constraint re-implements the same restriction, using the
K8sPSPPrivilegedContainer
constraint template:
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPPrivilegedContainer metadata: name: psp-privileged-container spec: match: kinds: - apiGroups: [""] kinds: ["Pod"]
Requiring a read-only root filesystem on the container
By default, a container can write to its root filesystem. Aside from security
concerns, this can cause performance bottlenecks due to write latency in the
container's writable layer. You can require a read-only root filesystem on
containers using a PodSecurityPolicy or by using a constraint. This constraint
uses the K8sPSPReadOnlyRootFilesystem
constraint template.
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPReadOnlyRootFilesystem metadata: name: psp-readonlyrootfilesystem spec: match: kinds: - apiGroups: [""] kinds: ["Pod"]
Restricting the types of volumes a container can mount
By default, a container can mount any type of volume registered with the
Kubernetes API on the cluster. This constraint restricts containers to a
bounded set of volume types, using the K8sPSPVolumeTypes
constraint template.
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPVolumeTypes metadata: name: psp-volume-types spec: match: kinds: - apiGroups: [""] kinds: ["Pod"] parameters: volumes: # - "*" # * may be used to allow all volume types - configMap - emptyDir - projected - secret - downwardAPI - persistentVolumeClaim #- hostPath #required for allowedHostPaths - flexVolume #required for allowedFlexVolumes
Auditing results
You can test the effectiveness of constraints without disrupting active
workloads by using the dryrun
enforcement action. This produces audit results
for your policies without actively blocking To learn more, see
Auditing using constraints.
What's next
- Use the constraint template library
- Read more about Creating constraints and Writing a constraint template.