Chapter 3. Policy controllers overview
Policy controllers monitor and report whether your cluster is compliant with a policy. Use the Red Hat Advanced Cluster Management for Kubernetes policy framework by using the supported policy templates to apply policies managed by these controllers. The policy controllers manage Kubernetes custom resource definition instances.
Policy controllers check for policy violations, and can make the cluster status compliant if the controller supports the enforcement feature. View the following topics to learn more about the following Red Hat Advanced Cluster Management for Kubernetes policy controllers:
- Kubernetes configuration policy controller
- Certificate policy controller
- Policy set controller
- Operator policy controller
Additional resources
3.1. Configuration policy controller Copy linkLink copied to clipboard!
Use the configuration policy controller to configure any Kubernetes resource and apply security policies across your clusters. The configuration policy controller communicates with the local Kubernetes API server so that you can get a list of your configurations that are in your cluster.
During installation, the configuration policy controller is created on the managed cluster. The configuration policy is provided in the policy-templates field of the policy on the hub cluster, and is propagated to the selected managed clusters by the governance framework.
When the remediationAction for the configuration policy controller is set to InformOnly, the parent policy does not enforce the configuration policy, even if the remediationAction in the parent policy is set to enforce.
If you have existing Kubernetes manifests that you want to put in a policy, use the Policy Generator.
Additional resources
- Create configuration policies
- Hub cluster policy framework
- NIST Special Publication 800-53 (Rev. 4)
-
CM-Configuration-Managementfolder - Dry-run
- Supported policies
- Policy controllers overview
- Policy controller advanced configuration
- Cleaning up resources that are created by policies
- Policy Generator configuration
- Governance dashboard
- Template processing in policies
3.2. Configuration policy YAML structure Copy linkLink copied to clipboard!
Review the structural YAML file structure and parameter definitions required to configure custom resource definitions for the configuration policy.
Find the description of a field on your managed cluster.
Run the following command and replace
<field-path>with the path to the field that you need:oc explain --api-version=policy.open-cluster-management.io/v1 ConfigurationPolicy.<field-path>Configuration policy YAML file structure:
apiVersion: policy.open-cluster-management.io/v1 kind: ConfigurationPolicy metadata: name: policy-config spec: namespaceSelector: include: ["default"] exclude: [] matchExpressions: [] matchLabels: {} remediationAction: inform customMessage: compliant: {} noncompliant: {} severity: low evaluationInterval: compliant: "" noncompliant: "" object-templates-raw: "" object-templates: - complianceType: musthave metadataComplianceType: recordDiff: "" recreateOption: "" objectSelector: matchLabels: {} matchExpressions: [] objectDefinition: apiVersion: v1 kind: Pod metadata: name: pod spec: containers: - image: pod-image name: pod-name ports: - containerPort: 80 - complianceType: mustonlyhave objectDefinition: apiVersion: v1 kind: ConfigMap metadata: name: myconfig namespace: default data: testData: hello-
When the
remediationActionfor the configuration policy is set toenforce, the controller applies the specified configuration to the target managed cluster. However, configuration policies that specify an object without a name can only be set toinform, unless theobjectSelectoris also configured. -
A Kubernetes object is defined in the
object-templatesarray in the configuration policy, where fields of the configuration policy controller is compared with objects on the managed cluster. You can also use templated values within configuration policies. For more advanced use cases, specify a string inobject-templates-rawto create theobject-templatesthat you want. For more information, see Template processing. - Configuration policy YAML table
| Field | Optional or required | Description |
|---|---|---|
|
| Required |
Set the value to |
|
| Required |
Set the value to |
|
| Required | The name of the policy. |
|
| Required for namespaced objects that do not have a namespace specified |
Determines namespaces in the managed cluster that the object is applied to. The |
|
| Required |
Specifies the action to take when the policy is non-compliant. Use the following parameter values: |
|
| Optional |
Configure the compliance message sent by the configuration policy based on the current compliance. Each message configuration is a string that can contain Go templates. The |
|
| Optional | Configure custom messages for configuration policies that are compliant. Go templates and UTF-8 encoded characters, including emoji and foreign characters, are supported values. |
|
| Optional | Configure custom messages for configuration policies that are non-compliant. Go templates and UTF-8 encoded characters, including emoji and foreign characters, are supported values. |
|
| Required |
Specifies the severity when the policy is non-compliant. Use the following parameter values: |
|
| Optional |
Specifies the frequency for a policy to be evaluated when it is in a particular compliance state. Use the parameters
When managed clusters have low resources, the evaluation interval can be set to long polling intervals to reduce CPU and memory usage on the Kubernetes API and policy controller. These are in the format of durations. For example, |
|
| Optional |
Specifies the evaluation frequency for a compliant policy. To enable the previous polling behavior, set this parameter to |
|
| Optional |
Specifies the evaluation frequency for a non-compliant policy. To enable the previous polling behavior, set this parameter to |
|
| Optional |
The array of Kubernetes objects (either fully defined or containing a subset of fields) for the controller to compare with objects on the managed cluster. Note: While |
|
| Optional |
Used to set object templates with a raw YAML string. Specify conditions for the object templates, where advanced functions like if-else statements and the {{- if eq .metadata.name "policy-grc-your-meta-data-name" }}
replicas: 2
{{- else }}
replicas: 1
{{- end }}
Note: While |
|
| Required | Use this parameter to define the desired state of the Kubernetes object on your managed clusters. Use one of the following verbs as the parameter value:
|
|
| Optional |
Overrides |
|
| Optional |
Use this parameter to specify if and where to display the difference between the object on the cluster and the
By default, this parameter is set to |
|
| Optional |
Describes when to delete and recreate an object when an update is required. When you set the object to |
|
| Optional |
|
|
| Required | A Kubernetes object (either fully defined or containing a subset of fields) for the controller to compare with objects on the managed cluster. |
|
| Optional | Determines whether to clean up resources related to the policy when the policy is removed from a managed cluster. |
Additional resources
3.3. Object selectors and raw templates Copy linkLink copied to clipboard!
Configuration policies support advanced parameters like objectSelector and object-templates-raw to filter objects or process complex logic, such as loops and conditionals.
Configuration policy objectSelector:
To iterate over multiple objects filtered by a label within a
ConfigurationPolicyresource, use theobjectSelectorparameter and specify the objectkindin theobjectDefinitionparameter. TheobjectSelectorparameter operates similarly tonamespaceSelectorbut does not support name filtering. To filter by name, use theskipObjectGo template function. Referencing{{ skipObject }}excludes that specific object from the selection.- Object selection configuration example
... object-templates: - objectSelector: matchExpressions: - key: foo operator: In values: - bar objectDefinition: apiVersion: v1 kind: ConfigMap data: key: '{{ if (hasSuffix "-prod" .ObjectName) }}{{ skipObject }}{{ end }}{{ hasNodesWithExactRoles "infra" }}'Raw template processing
The optional
object-templates-rawparameter supports advanced templating use cases, such as theifconditional function and therangeloop function. Theobject-templates-rawparameter accepts a string containing Go templates that must resolve to anobject-templatesarray.Note: You must set exactly one of either
spec.object-templatesorspec.object-templates-raw.Raw template configuration example with conditional labels
object-templates-raw: | {{- range (lookup "v1" "ConfigMap" "default" "").items }} {{- if eq .data.name "Sea Otter" }} - complianceType: musthave objectDefinition: kind: ConfigMap apiVersion: v1 metadata: name: {{ .metadata.name }} namespace: {{ .metadata.namespace }} labels: species-category: mammal {{- end }} {{- end }}-
Policy configuration example creating infrastructure
MachineSetobjects
apiVersion: policy.open-cluster-management.io/v1 kind: ConfigurationPolicy metadata: name: create-infra-machineset spec: remediationAction: enforce severity: low object-templates-raw: | {{- /* Specify the parameters needed to create the MachineSet */ -}} {{- $machineset_role := "infra" }} {{- $region := "ap-southeast-1" }} {{- $zones := list "ap-southeast-1a" "ap-southeast-1b" "ap-southeast-1c" }} {{- $infrastructure_id := (lookup "config.openshift.io/v1" "Infrastructure" "" "cluster").status.infrastructureName }} {{- $worker_ms := (index (lookup "machine.openshift.io/v1beta1" "MachineSet" "openshift-machine-api" "").items 0) }} {{- /* Generate the MachineSet for each zone as specified */ -}} {{- range $zone := $zones }} - complianceType: musthave objectDefinition: apiVersion: machine.openshift.io/v1beta1 kind: MachineSet metadata: labels: machine.openshift.io/cluster-api-cluster: {{ $infrastructure_id }} name: {{ $infrastructure_id }}-{{ $machineset_role }}-{{ $zone }} namespace: openshift-machine-api spec: replicas: 1 selector: matchLabels: machine.openshift.io/cluster-api-cluster: {{ $infrastructure_id }} machine.openshift.io/cluster-api-machineset: {{ $infrastructure_id }}-{{ $machineset_role }}-{{ $zone }} template: metadata: labels: machine.openshift.io/cluster-api-cluster: {{ $infrastructure_id }} machine.openshift.io/cluster-api-machine-role: {{ $machineset_role }} machine.openshift.io/cluster-api-machine-type: {{ $machineset_role }} machine.openshift.io/cluster-api-machineset: {{ $infrastructure_id }}-{{ $machineset_role }}-{{ $zone }} spec: metadata: labels: node-role.kubernetes.io/{{ $machineset_role }}: "" taints: - key: node-role.kubernetes.io/{{ $machineset_role }} effect: NoSchedule providerSpec: value: ami: id: {{ $worker_ms.spec.template.spec.providerSpec.value.ami.id }} apiVersion: awsproviderconfig.openshift.io/v1beta1 blockDevices: - ebs: encrypted: true iops: 2000 kmsKey: arn: '' volumeSize: 500 volumeType: io1 credentialsSecret: name: aws-cloud-credentials deviceIndex: 0 instanceType: {{ $worker_ms.spec.template.spec.providerSpec.value.instanceType }} iamInstanceProfile: id: {{ $infrastructure_id }}-worker-profile kind: AWSMachineProviderConfig placement: availabilityZone: {{ $zone }} region: {{ $region }} securityGroups: - filters: - name: tag:Name values: - {{ $infrastructure_id }}-worker-sg subnet: filters: - name: tag:Name values: - {{ $infrastructure_id }}-private-{{ $zone }} tags: - name: kubernetes.io/cluster/{{ $infrastructure_id }} value: owned userDataSecret: name: worker-user-data {{- end }}
Additional resources
3.4. Certificate policy controller Copy linkLink copied to clipboard!
You can use the certificate policy controller to detect certificates that are close to expiring, time durations (hours) that are too long, or contain DNS names that fail to match specified patterns. You can add the certificate policy to the policy-templates field of the policy on the hub cluster, which propagates to the selected managed clusters by using the governance framework.
When you create the certificate policy controller on your hub cluster, a replicated policy is created on your managed cluster.
Non-compliant scernarios
A policy status changes to non-compliant when either of these situations occurs:
- When a certificate expires in less than the minimum duration of time or exceeds the maximum time.
- When DNS names fail to match the specified pattern.
The certificate policy controller runs on your managed cluster. The controller communicates with the local Kubernetes API server to get the list of secrets that contain certificates and find all non-compliant certificates.
Notes:
-
Certificate policy controller does not support the
enforcefeature. -
The certificate policy controller automatically looks for a certificate in a secret in only the
tls.crtkey. If you store a secret in a different key, define thecertificate_key_nameparameter. For example, if you have a secret that contains asensor-cert.pemcertificate, add the following label to the secret:certificate_key_name: sensor-cert.pem.
3.5. Certificate policy controller schema and parameters Copy linkLink copied to clipboard!
Review the structural YAML file composition and parameter definitions required to configure custom resource definitions for the certificate policy controller.
Certificate policy YAML file structure
apiVersion: policy.open-cluster-management.io/v1 kind: CertificatePolicy metadata: name: certificate-policy-example spec: namespaceSelector: include: ["default"] exclude: [] matchExpressions: [] matchLabels: {} labelSelector: myLabelKey: myLabelValue remediationAction: severity: minimumDuration: minimumCADuration: maximumDuration: maximumCADuration: allowedSANPattern: disallowedSANPattern:- Certificate policy controller YAML file table
| Field | Optional or required | Description |
|---|---|---|
|
| Required |
Set the value to |
|
| Required |
Set the value to |
|
| Required | The name to identify the policy. |
|
| Optional |
In a certificate policy, the |
|
| Required |
Determines namespaces in the managed cluster where secrets are monitored. The
Note: If the |
|
| Optional | Specifies identifying attributes of objects. See the Kubernetes labels and selectors documentation. |
|
| Required |
Specifies the remediation of your policy. Set the parameter value to |
|
| Optional |
Informs the user of the severity when the policy is non-compliant. Use the following parameter values: |
|
| Required |
When a value is not specified, the default value is |
|
| Optional |
Set a value to identify signing certificates that might expire soon with a different value from other certificates. If the parameter value is not specified, the CA certificate expiration is the value used for the |
|
| Optional | Set a value to identify certificates that have been created with a duration that exceeds your desired limit. The parameter uses the Golang Parse Duration format. |
|
| Optional | Set a value to identify signing certificates that have been created with a duration that exceeds your defined limit. The parameter uses the Golang Parse Duration format. |
|
| Optional | A regular expression that must match every SAN entry that you have defined in your certificates. This parameter checks DNS names against patterns. See the Golang Regular Expression syntax documentation. |
|
| Optional | A regular expression that must not match any SAN entries you have defined in your certificates. This parameter checks DNS names against patterns.
Note: To detect wild-card certificate, use the following SAN pattern: See the Golang Regular Expression syntax documentation. |
Additional resources
3.6. Policy set controller Copy linkLink copied to clipboard!
The policy set controller aggregates the policy status scoped to policies that are defined in the same namespace. Create a policy set (PolicySet) to group policies that are in the same namespace. All policies in the PolicySet are placed together in a selected cluster by creating a PlacementBinding to bind the PolicySet and Placement. The policy set is deployed to the hub cluster.
Additionally, when a policy is a part of multiple policy sets, existing and new Placement resources remain in the policy. When a user removes a policy from the policy set, the policy is not applied to the cluster that is selected in the policy set, but the placements remain. The policy set controller only checks for violations in clusters that include the policy set placement.
Notes:
- The Red Hat Advanced Cluster Management sample policy set uses cluster placement. If you use cluster placement, bind the namespace containing the policy to the managed cluster set. See Deploying policies to your cluster for more details on using cluster placement.
-
To use a
Placementresource, bind aManagedClusterSetresource to the namespace of thePlacementresource with aManagedClusterSetBindingresource. See Creating a ManagedClusterSetBinding resource for additional details. Policy set YAML structure
Your policy set might resemble the following YAML file:
apiVersion: policy.open-cluster-management.io/v1beta1
kind: PolicySet
metadata:
name: demo-policyset
spec:
policies:
- policy-demo
---
apiVersion: policy.open-cluster-management.io/v1
kind: PlacementBinding
metadata:
name: demo-policyset-pb
placementRef:
apiGroup: cluster.open-cluster-management.io
kind: Placement
name: demo-policyset-pr
subjects:
- apiGroup: policy.open-cluster-management.io
kind: PolicySet
name: demo-policyset
---
apiVersion: cluster.open-cluster-management.io/v1beta1
kind: Placement
metadata:
name: demo-policyset-pr
spec:
predicates:
- requiredClusterSelector:
labelSelector:
matchExpressions:
- key: name
operator: In
values:
- local-cluster
tolerations:
- key: cluster.open-cluster-management.io/unavailable
operator: Exists
- key: cluster.open-cluster-management.io/unreachable
operator: Exists
Policy set table
View the following parameter table for descriptions:
| Field | Optional or required | Description |
|---|---|---|
|
| Required |
Set the value to |
|
| Required |
Set the value to |
|
| Required | The name for identifying the policy resource. |
|
| Required | Add configuration details for your policy. |
|
| Optional | The list of policies that you want to group together in the policy set. |
Policy set sample
apiVersion: policy.open-cluster-management.io/v1beta1 kind: PolicySet metadata: name: pci namespace: default spec: description: Policies for PCI compliance policies: - policy-pod - policy-namespace status: compliant: NonCompliant placement: - placementBinding: binding1 placement: placement1 policySet: policyset-ps
3.7. Operator policy controller Copy linkLink copied to clipboard!
The operator policy controller allows you to monitor and install Operator Lifecycle Manager operators across your clusters. Use the operator policy controller to monitor the health of various pieces of the operator and to specify how you want to automatically handle updates to the operator.
You can also distribute an operator policy to managed clusters by using the governance framework and adding the policy to the policy-templates field of a policy on the hub cluster.
You can also use template values within the operatorGroup and subscription fields of an operator policy. For more information, see Template processing.
Notes:
- Operator Lifecycle Manager must be available on your managed cluster. This is enabled by default on Red Hat OpenShift Container Platform.
- Required access: Cluster administrator
Operator policy YAML table
Field Optional or required Description apiVersionRequired
Set the value to
policy.open-cluster-management.io/v1beta1.kindRequired
Set the value to
OperatorPolicyto indicate the type of policy.metadata.nameRequired
The name for identifying the policy resource.
spec.remediationActionRequired
If the
remediationActionfor the operator policy is set toenforce, the controller creates resources on the target managed cluster to communicate to OLM to install the operator and approve updates based on the versions specified in the policy. + If theremediationActionset toinform, the controller only reports the status of the operator, including if any upgrades are available.spec.operatorGroupOptional
By default, if the
operatorGroupfield is not specified, the controller generates anAllNamespacestypeOperatorGroupresource in the same namespace as the subscription, if supported. The operator policy controller produces this resource. View the following parameter descriptions:-
name: The name of theOperatorGroupresource. -
namespace: The namespace of theOperatorGroupresource. This parameter must match the namespace where you install the operator. -
targetNamespaces: A list of namespaces that the operator is configured to watch and operate.
spec.complianceTypeRequired
Specifies the desired state of the operator on the cluster. If set to
musthave, the policy is compliant when the operator is found. If set tomustnothave, the policy is compliant when the operator is not found.spec.removalBehaviorOptional
Determines which resource types need to be kept or removed when you enforce an
OperatorPolicyresource withcomplianceType: mustnothavedefined. There is no effect whencomplianceTypeis set tomusthave. View the following parameter descriptions:-
operatorGroupscan be set toKeeporDeleteIfUnused. The default value isDeleteIfUnusuedwhich only removes theOperatorGroupresource if it is not used by any other operators. -
subscriptionscan be set toKeeporDelete. The default value isDelete. -
clusterServiceVersionscan be set toKeeporDelete. The default value isDelete. -
customResourceDefinitionscan be set toKeeporDelete. The default value isKeep. If you set this toDelete, theCustomResourceDefintionresources on the managed cluster are removed and can cause data loss.
spec.subscriptionRequired
Define the configurations to create an operator subscription. Add information in the following fields to create an operator subscription. View the following parameter descriptions:
-
channel: If not specified, the default channel is selected from the operator catalog. The default can be different on different OpenShift Container Platform versions. -
name: Specify the package name of the operator. -
namespace: If not specified, the default namespaced that is used for OpenShift Container Platform managed clusters isopenshift-operators. -
source: If not specified, the catalog that contains the operator is chosen. -
sourceNamespace: If not specified, the namespace of the catalog that contains the operator is chosen. -
config: Optional. Specify extra configuration details for the operator subscription.
The
namefield is the only required field. The other fields are populated based on the catalog information within the managed cluster.Note: If you define a value for the
installPlanApprovalfield in this parameter section, the policy becomes non-compliant. Usespec.upgradeApprovalin theOperatorPolicyresource.spec.complianceConfigOptional
Use this parameter to define the compliance behavior for specific scenarios that are associated with operators. You can set each of the following options individually, where the supported values are
CompliantandNonCompliant:-
catalogSourceUnhealthy: Define the compliance when the catalog source for the operator is unhealthy. The default value isCompliantbecause this only affects possible upgrades. -
deploymentsUnavailable: Define the compliance when at least one deployment of the operator is not fully available. The default value isNonCompliantbecause this reflects the availability of the service that the operator provides. -
upgradesAvailable: Define the compliance when there is an upgrade available for the operator. The default value isCompliantbecause the existing operator installation might be running correctly. -
deprecationsPresent: Specifies that the compliance of the policy is affected by the deprecations. For example, the default value isCompliant, but if thedeprecationsPresent=NonCompliantconfiguration detects the deprecations, then the policy compliance status is set toNonCompliant. -
minorChannelUpgradeAvailable: Detects if a minor version upgrade is available for the operator on different channels. The default value isCompliant.
spec.upgradeApprovalRequired
If the
upgradeApprovalfield is set toAutomatic, version upgrades on the cluster are approved by the policy when the policy is set toenforce. If you set the field toNone, version upgrades to the specific operator are not approved when the policy is set toenforce.spec.versionsOptional
Declare which versions of the operator are compliant. The
versionsparameter is a list of templatable strings that specifies which installedClusterServiceVersionnames are compliant when ininformmode, and whichInstallPlansare approved when inenforcemode. To give different versions in one entry, separate the versions with commas. If the field is empty, the strings are ignored and allClusterServiceVersionnames are approved. The default value is empty.-