0

I have the following manifest to export some RabbitMQ stats:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: rabbitmq-exporter
  labels:
    app: rabbitmq
spec:
  selector:
    matchLabels:
      app: rabbitmq
  endpoints:
    - port: prometheus
      path: /metrics
      interval: 10s

The ServiceMonitor CRD already exists on my cluster, I would like to send the yml via the python client's create_from_yaml function, but I get the following error:

File /virtualenv/lib/python3.9/site-packages/kubernetes/utils/create_from_yaml.py:242, in create_from_yaml_single_item(k8s_client, yml_object, verbose, **kwargs)
    240 group = "".join(word.capitalize() for word in group.split('.'))
    241 fcn_to_call = "{0}{1}Api".format(group, version.capitalize())
--> 242 k8s_api = getattr(client, fcn_to_call)(k8s_client)
    243 # Replace CamelCased action_type into snake_case
    244 kind = yml_object["kind"]

AttributeError: module 'kubernetes.client' has no attribute 'MonitoringCoreosComV1Api'

I've been reading a lot of issues regarding CRD and create_from_yaml, in this case I believe I just need the a create_namespaced_servicemonitor method inside a MonitoringCoreosComV1Api class but I don't really know what to base the body of the method on, etc..

Paulo
  • 6,982
  • 7
  • 42
  • 56

1 Answers1

0

You can use the api create_namespaced_custom_object to create a custom resource.The Doc

Example:

from kubernetes import client, config

config.load_kube_config()

api = client.CustomObjectsApi()
prometheus_rule = {
    "apiVersion": "monitoring.coreos.com/v1",
    "kind": "PrometheusRule",
    "metadata": {
        "name": "my-prometheus-rule",
        "namespace": "my-namespace",
    },
    "spec": {
        "groups": [
            {
                "name": "my-group",
                "rules": [
                    {
                        "alert": "HighErrorRate",
                        "expr": "job:request_latency_seconds:mean5m{job='my-service'} > 0.5",
                        "for": "10m",
                        "labels": {
                            "severity": "critical",
                        },
                        "annotations": {
                            "summary": "High request latency",
                        },
                    },
                ],
            },
        ],
    },
}

api.create_namespaced_custom_object(
    group="monitoring.coreos.com",
    version="v1",
    namespace="my-namespace",
    plural="prometheusrules",
    body=prometheus_rule,
)

martin
  • 1