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.

Prerequisites:

Usage example:

  1. import(
  2. "k8s.io/api/core/v1"
  3. "github.com/operator-framework/operator-sdk/pkg/metrics"
  4. )
  5. func main() {
  6. ...
  7. // Populate below with the Service(s) for which you want to create ServiceMonitors.
  8. services := []*v1.Service{}
  9. // Create one `ServiceMonitor` per application per namespace.
  10. // Change below value to name of the Namespace you want the `ServiceMonitor` to be created in.
  11. ns := "default"
  12. // Pass the Service(s) to the helper function, which in turn returns the array of `ServiceMonitor` objects.
  13. serviceMonitors, err := metrics.CreateServiceMonitors(restConfig, ns, services)
  14. if err != nil {
  15. // handle error here
  16. }
  17. ...
  18. }

Last modified January 1, 0001