Using the Prometheus Operator ServiceMonitor CRD with Operator SDK

prometheus-operator is an operator that creates, configures, and manages Prometheus clusters atop Kubernetes.

ServiceMonitor is a CustomResource of the prometheus-operator, which discovers the Endpoints in Service objects and configures Prometheus to monitor those pods. See the prometheus-operator documentation to learn more about ServiceMonitor.

The CreateServiceMonitors function takes Service objects and generates ServiceMonitor resources based on the endpoints. To add Service target discovery of your created monitoring Service you can use the metrics.CreateServiceMonitors() helper function, which accepts the newly created Service.


Usage example:


    func main() {


        // Populate below with the Service(s) for which you want to create ServiceMonitors.
        services := []*v1.Service{}

        // Create one `ServiceMonitor` per application per namespace.
        // Change below value to name of the Namespace you want the `ServiceMonitor` to be created in.
        ns := "default"

        // Pass the Service(s) to the helper function, which in turn returns the array of `ServiceMonitor` objects.
        serviceMonitors, err := metrics.CreateServiceMonitors(restConfig, ns, services)
        if err != nil {
            // handle error here