Operators Scope

Overview

A namespace-scoped operator watches and manages resources in a single Namespace, whereas a cluster-scoped operator watches and manages resources cluster-wide.

An operator should be cluster-scoped if it watches resources that can be created in any Namespace. An operator should be namespace-scoped if it is intended to be flexibly deployed. This scope permits decoupled upgrades, namespace isolation for failures and monitoring, and differing API definitions.

By default, operator-sdk init scaffolds a cluster-scoped operator. This document details conversion of default operator projects to namespaced-scoped operators. Before proceeding, be aware that your operator may be better suited as cluster-scoped. For example, the cert-manager operator is often deployed with cluster-scoped permissions and watches so that it can manage and issue certificates for an entire cluster.

IMPORTANT: When a Manager instance is created in the main.go file, the Namespaces are set via Manager Options as described below. These Namespaces should be watched and cached for the Client which is provided by the Manager.Only clients provided by cluster-scoped Managers are able to manage cluster-scoped CRD’s. For further information see: CRD scope doc.

Manager watching options

Watching resources in all Namespaces (default)

A Manager is initialized with no Namespace option specified, or Namespace: "" will watch all Namespaces:

  1. ...
  2. mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
  3. Scheme: scheme,
  4. MetricsBindAddress: metricsAddr,
  5. Port: 9443,
  6. LeaderElection: enableLeaderElection,
  7. LeaderElectionID: "f1c5ece8.example.com",
  8. })
  9. ...

Watching resources in a single Namespace

To restrict the scope of the Manager’s cache to a specific Namespace set the Namespace field in Options:

  1. ...
  2. mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
  3. Scheme: scheme,
  4. MetricsBindAddress: metricsAddr,
  5. Port: 9443,
  6. LeaderElection: enableLeaderElection,
  7. LeaderElectionID: "f1c5ece8.example.com",
  8. Namespace: "operator-namespace",
  9. })
  10. ...

Watching resources in a set of Namespaces

It is possible to use MultiNamespacedCacheBuilder from Options to watch and manage resources in a set of Namespaces:

  1. ...
  2. namespaces := []string{"foo", "bar"} // List of Namespaces
  3. ...
  4. mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
  5. Scheme: scheme,
  6. MetricsBindAddress: metricsAddr,
  7. Port: 9443,
  8. LeaderElection: enableLeaderElection,
  9. LeaderElectionID: "f1c5ece8.example.com",
  10. NewCache: cache.MultiNamespacedCacheBuilder(namespaces),
  11. })
  12. ...

In the above example, a CR created in a Namespace not in the set passed to Options will not be reconciled by its controller because the Manager does not manage that Namespace.

IMPORTANT: Note that this is not intended to be used for excluding Namespaces, this is better done via a Predicate.

Restricting Roles and permissions

An operator’s scope defines its Manager’s cache’s scope but not the permissions to access the resources. After updating the Manager’s scope to be Namespaced, Role-Based Access Control (RBAC) permissions applied to the operator’s service account should be restricted accordingly.

These permissions are found in the directory config/rbac/. The ClusterRole in role.yaml and ClusterRoleBinding in role_binding.yaml are used to grant the operator permissions to access and manage its resources.

NOTE For changing the operator’s scope only the role.yaml and role_binding.yaml manifests need to be updated. For the purposes of this doc, the other RBAC manifests <kind>_editor_role.yaml, <kind>_viewer_role.yaml, and auth_proxy_*.yaml are not relevant to changing the operator’s resource permissions.

Changing the permissions to Namespaced

To change the scope of the RBAC permissions from cluster-wide to a specific namespace, you will need to:

  • Use Roles instead of ClusterRoles.

RBAC markers defined in the controller (e.g controllers/memcached_controller.go) are used to generate the operator’s RBAC ClusterRole (e.g config/rbac/role.yaml). The default markers don’t specify a namespace property and will result in a ClusterRole.

Update the RBAC markers in <kind>_controller.go with namespace=<namespace> where the Role is to be applied, such as:

  1. //+kubebuilder:rbac:groups=cache.example.com,namespace=memcached-operator-system,resources=memcacheds,verbs=get;list;watch;create;update;patch;delete
  2. //+kubebuilder:rbac:groups=cache.example.com,namespace=memcached-operator-system,resources=memcacheds/status,verbs=get;update;patch

Then run make manifests to update config/rbac/role.yaml. In our example it would like:

  1. apiVersion: rbac.authorization.k8s.io/v1
  2. kind: Role
  3. metadata:
  4. creationTimestamp: null
  5. name: manager-role
  6. namespace: memcached-operator-system
  • Use RoleBindings instead of ClusterRoleBindings. The config/rbac/role_binding.yaml needs to be manually updated:
  1. apiVersion: rbac.authorization.k8s.io/v1
  2. kind: RoleBinding
  3. metadata:
  4. name: manager-rolebinding
  5. roleRef:
  6. apiGroup: rbac.authorization.k8s.io
  7. kind: Role
  8. name: manager-role
  9. subjects:
  10. - kind: ServiceAccount
  11. name: controller-manager
  12. namespace: system

Configuring watch namespaces dynamically

Instead of having any Namespaces hard-coded in the main.go file a good practice is to use an environment variable to allow the restrictive configurations. The one suggested here is WATCH_NAMESPACE, a comma-separated list of namespaces passed to the manager at deploy time.

Configuring Namespace scoped operators

  • Add a helper function in the main.go file:
  1. // getWatchNamespace returns the Namespace the operator should be watching for changes
  2. func getWatchNamespace() (string, error) {
  3. // WatchNamespaceEnvVar is the constant for env variable WATCH_NAMESPACE
  4. // which specifies the Namespace to watch.
  5. // An empty value means the operator is running with cluster scope.
  6. var watchNamespaceEnvVar = "WATCH_NAMESPACE"
  7. ns, found := os.LookupEnv(watchNamespaceEnvVar)
  8. if !found {
  9. return "", fmt.Errorf("%s must be set", watchNamespaceEnvVar)
  10. }
  11. return ns, nil
  12. }
  • Use the environment variable value:
  1. ...
  2. watchNamespace, err := getWatchNamespace()
  3. if err != nil {
  4. setupLog.Error(err, "unable to get WatchNamespace, " +
  5. "the manager will watch and manage resources in all namespaces")
  6. }
  7. mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
  8. Scheme: scheme,
  9. MetricsBindAddress: metricsAddr,
  10. Port: 9443,
  11. LeaderElection: enableLeaderElection,
  12. LeaderElectionID: "f1c5ece8.example.com",
  13. Namespace: watchNamespace, // namespaced-scope when the value is not an empty string
  14. })
  15. ...
  • Define the environment variable in the config/manager/manager.yaml:
  1. spec:
  2. containers:
  3. - command:
  4. - /manager
  5. args:
  6. - --enable-leader-election
  7. image: controller:latest
  8. name: manager
  9. resources:
  10. limits:
  11. cpu: 100m
  12. memory: 30Mi
  13. requests:
  14. cpu: 100m
  15. memory: 20Mi
  16. env:
  17. - name: WATCH_NAMESPACE
  18. valueFrom:
  19. fieldRef:
  20. fieldPath: metadata.namespace
  21. terminationGracePeriodSeconds: 10

NOTE WATCH_NAMESPACE here will always be set as the namespace where the operator is deployed.

Configuring cluster-scoped operators with MultiNamespacedCacheBuilder

  • Add a helper function to get the environment variable value in the main.go file as done in the previous example (e.g getWatchNamespace())
  • Use the environment variable value and check if it is a multi-namespace scenario:
  1. ...
  2. watchNamespace, err := getWatchNamespace()
  3. if err != nil {
  4. setupLog.Error(err, "unable to get WatchNamespace, " +
  5. "the manager will watch and manage resources in all Namespaces")
  6. }
  7. options := ctrl.Options{
  8. Scheme: scheme,
  9. MetricsBindAddress: metricsAddr,
  10. Port: 9443,
  11. LeaderElection: enableLeaderElection,
  12. LeaderElectionID: "f1c5ece8.example.com",
  13. Namespace: watchNamespace, // namespaced-scope when the value is not an empty string
  14. }
  15. // Add support for MultiNamespace set in WATCH_NAMESPACE (e.g ns1,ns2)
  16. if strings.Contains(watchNamespace, ",") {
  17. setupLog.Info("manager set up with multiple namespaces", "namespaces", watchNamespace)
  18. // configure cluster-scoped with MultiNamespacedCacheBuilder
  19. options.Namespace = ""
  20. options.NewCache = cache.MultiNamespacedCacheBuilder(strings.Split(watchNamespace, ","))
  21. }
  22. ...
  • Define the environment variable in the config/manager/manager.yaml:
  1. ...
  2. env:
  3. - name: WATCH_NAMESPACE
  4. value: "ns1,ns2"
  5. terminationGracePeriodSeconds: 10
  6. ...

Updating your CSV’s installModes

If your operator is integrated with OLM, you will want to update your CSV base’s spec.installModes list to support the desired namespacing requirements. Support for multiple types of namespacing is allowed, so supporting multiple install modes in a CSV is permitted. After doing so, update your [bundle][bundle-quickstart] or package manifests by following the linked guides.

Watching resources in all Namespaces (default)

Only the AllNamespaces install mode is supported: true by default, so no changes are required.

Watching resources in a single Namespace

If the operator can watch its own namespace, set the following in your spec.installModes list:

  1. - type: OwnNamespace
  2. supported: true

If the operator can watch a single namespace that is not its own, set the following in your spec.installModes list:

  1. - type: SingleNamespace
  2. supported: true

Watching resources in multiple Namespaces

If the operator can watch multiple namespaces, set the following in your spec.installModes list:

  1. - type: MultiNamespace
  2. supported: true

Last modified March 11, 2021: docs: remove redundancy in Go migration, discuss service account in scope doc (#4637) (819ce7b2)