<p>I like to give every gitlab namespace / project (microservices) a <em>ServiceMonitor</em> from <em>monitoring.coreos.com</em> provided by <a href="https://github.com/coreos/prometheus-operator" rel="nofollow noreferrer">prometheus-operator</a>.
But while running a gitlab pipeline creating it, there comes an error that this ressource can not be created by </p>

<pre><code> servicemonitors.monitoring.coreos.com "service-monitor" is forbidden: User "system:serviceaccount:ABC_NAMESPACE:ABC-dev-service-account" cannot get resource "servicemonitors" in API group "monitoring.coreos.com" in the namespace "ABC_NAMESPACE"
</code></pre>

<p>So i workaround for one mircroservice by apply a Role &amp; a RoleBinding for a single namespace but doing that for all is really nice.</p>

<pre><code>kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: service_cluster_monitor_reader
rules:
  - apiGroups: ["monitoring.coreos.com"] # "" indicates the core API group
    resources: ["servicemonitors"]
    verbs: ["get", "create", "update", "patch", "delete"]
---
kind: CluserRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: cluster-monitor-binding
subjects:
  - kind: ServiceAccount
    name: gitlab-project-id-dev-service-account
roleRef:
  kind: ClusterRole
  name: service_cluster_monitor_reader
  apiGroup: rbac.authorization.k8s.io
</code></pre>

<p>Is it possible to give all gitlab created namespace a role-binding to obtain this permissions?</p>

bgeissler
<p>While it's non trivial to give this permission to service accounts only in namespaces created by gitlab you can assign this permission to all service accounts across all the namespaces in the cluster using below.</p>

<pre><code>kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: service_cluster_monitor_reader
rules:
- apiGroups: ["monitoring.coreos.com"] # "" indicates the core API group
  resources: ["servicemonitors"]
  verbs: ["get", "create", "update", "patch", "delete"]

---

kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: cluster-monitor-binding
subjects:
- kind: Group
  name: system:serviceaccounts
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: service_cluster_monitor_reader
  apiGroup: rbac.authorization.k8s.io
</code></pre>

<p>Validate the permission by </p>

<pre><code>kubectl auth can-i get servicemonitors --as=system:serviceaccount:ABC_NAMESPACE:ABC-dev-service-account -n ABC_NAMESPACE
</code></pre>
