「Prometheus」- Scrape Exporter

  CREATED BY JENKINSBOT

访问 Basic Auth 保护

monitoring – Configure basic_auth for Prometheus Target – Stack Overflow

  - job_name: 'myapp_health_checks'
    scrape_interval: 5m
    scrape_timeout: 30s
    static_configs:
        - targets: ['mywebsite.org']
    metrics_path: "/api/health"
    basic_auth:
      username: 'email@username.me'
      password: 'cfgqvzjbhnwcomplicatedpasswordwjnqmd'

拆分配置文件、基于文件的服务发现

Configuration | Prometheus
Using JSON file service discovery with Prometheus – Robust Perception | Prometheus Monitoring Experts

随着主机和各种 Exporter 的增多,prometheus.yml 配置文件越来越长,长到难以维护。

我们能够使用基于文件的服务发现,以分割 prometheus.yml 文件:

# /etc/prometheus/prometheus.yml
...
scrape_configs:
  - job_name: 'dummy-job'  # This is a default value, it is mandatory.
    file_sd_configs:
      - files:
          - dummy/targets.yaml
...

# /etc/prometheus/dummy/targets.yaml
---
- targets:
  - "172.27.254.32:1987"
  labels:
    hostname: "my-hostname"

为了能够快速拆分 prometheus.yml 文件,我们编写如下 Groovy 脚本(需要结合配置文件调整,多半不能直接使用):

#!/usr/bin/groovy

import groovy.yaml.YamlSlurper

def configfile = "/etc/prometheus/prometheus.yml"
def yamlObject = new YamlSlurper().parseText(new File(configfile).text)

def processExporter = yamlObject.scrape_configs.find {
	it.job_name == 'your-job-name'
}

def yamlBuilder = new groovy.yaml.YamlBuilder()

processExporter.static_configs.each {
	def filename = it.labels.hostname + ".yaml"
	def result = yamlBuilder(it)
	def yamlContent = yamlBuilder.toString()
	new File(filename).text = yamlContent // 写入文件
	
	println "--------------- ${filename}"
	println yamlBuilder.toString() // 打印内容
}