Separate Namespaces

This page describes how to enhance the security of running Operator Service for Jenkins® and Jenkins on Kubernetes by deploying the Operator and Jenkins instance in their own namespaces. This is the recommended way of running Operator Service for Jenkins®.

Assumptions

In this example, we will be deploying Operator Service for Jenkins® to the op-svc-jenkins namespace, while the Jenkins instance will be run in the jenkins namespace.

To create these namespaces run:

$ kubectl create ns op-svc-jenkins
$ kubectl create ns jenkins

CRDs should be already deployed to the cluster. You should have access to operator.yaml with deployment of the Operator Service for Jenkins® or be able to modify existing deployment (that is deployed to the op-svc-jenkins namespace).

op-svc-jenkins namespace

If you don’t have an existing ServiceAccount for the Operator Service for Jenkins®, create one:

service_account.yaml

apiVersion: v1
kind: ServiceAccount
metadata:
  name: operator-service
$ kubectl -n op-svc-jenkins apply -f service_account.yaml

Add a Role for the Operator in the op-svc-jenkins namespace, see Roles for YAML.

Add a RoleBinding for the Operator’s ServiceAccount:

role_binding.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: operator-rolebinding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: operator-role
subjects:
- kind: ServiceAccount
  name: operator-service
$ kubectl -n op-svc-jenkins apply -f role_binding.yaml

jenkins namespace

Add a Role for the Operator in the jenkins namespace, see Roles for YAML. It’s the same role as in op-svc-jenkins namespace.

Add a RoleBinding for the Operator’s ServiceAccount:

role_binding_jenkins.yaml

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: operator-rolebinding
  namespace: jenkins
subjects:
- kind: ServiceAccount
  name: operator-service
  namespace: op-svc-jenkins
roleRef:
  kind: Role
  name: operator-role
  apiGroup: rbac.authorization.k8s.io
$ kubectl -n jenkins apply -f role_binding_jenkins.yaml

Update the Operator deployment

Edit the WATCH_NAMESPACE environment variable in the Operator deployment (also make sure serviceAccountName is set correctly):

    spec:
      containers:
        - command:
            - /manager
          (...)
          env:
            - name: WATCH_NAMESPACE
              value: jenkins
      serviceAccountName: operator-service

Don’t forget to apply your changes:

$ kubectl -n op-svc-jenkins apply -f operator.yaml

Now the Operator Service for Jenkins® will run in its own namespace (op-svc-jenkins), watch for CRs in a different namespace (jenkins) and deploy Jenkins there.