11 скриптов автоматизации для автоматизации конфигурации Prometheus

от автора

Работа с Prometheus полита потом и кровью ручной работы. У себя в телеграм-канале monitorim_it публикую много статей про мониторинг, но эти скрипты туда не помещаются, поэтому публикую их здесь. Открывая эту статью вы подтверждаете, что умело пользуетесь Prometheus и знаете как он работает.

1. Скрипт автоматизации запуска сервиса Prometheus

Этот скрипт поможет настроить автоматический запуск сервиса Prometheus через systemd. Служба будет взлетать при запуске системы и будет управляться как любой другой сервис.

#!/bin/bash # Configure Prometheus as a systemd service with validation  SERVICE_FILE="/etc/systemd/system/prometheus.service"  echo "Configuring Prometheus systemd service..."  cat <<EOF | sudo tee $SERVICE_FILE [Unit] Description=Prometheus Monitoring System After=network.target  [Service] User=nobody ExecStart=/usr/local/bin/prometheus --config.file=/opt/prometheus/prometheus.yml --storage.tsdb.path=/opt/prometheus/data Restart=always  [Install] WantedBy=multi-user.target EOF  # Reload and enable the service if sudo systemctl daemon-reload && sudo systemctl enable prometheus && sudo systemctl start prometheus; then     echo "Prometheus service successfully configured and started." else     echo "Error: Failed to configure or start the Prometheus service. Check the logs for details."     exit 1 fi

2. Интеграция с Alertmanager

Этот скрипт поможет автоматизировать интеграцию с Alertmanager с Prometheus для отправки алертов.

#!/bin/bash # Integrate Alertmanager with Prometheus configuration  PROMETHEUS_CONFIG="/opt/prometheus/prometheus.yml"  echo "Integrating Alertmanager with Prometheus..."  if grep -q "alertmanagers" $PROMETHEUS_CONFIG; then     echo "Alertmanager configuration already exists in $PROMETHEUS_CONFIG." else     cat <<EOF | sudo tee -a $PROMETHEUS_CONFIG alerting:   alertmanagers:     - static_configs:         - targets: ['localhost:9093'] EOF     echo "Alertmanager configuration added to $PROMETHEUS_CONFIG."     sudo systemctl restart prometheus && echo "Prometheus restarted successfully." fi

3. Автоматизация настройки Exporter

Prometheus использует экспортеры для сбора метрик. Скрипт ниже автоматизирует установку и конфигурацию Node Exporter.

#!/bin/bash # Install and configure Node Exporter  VERSION=${1:-"1.7.0"} # Default Node Exporter version BIN_DIR="/usr/local/bin" SERVICE_FILE="/etc/systemd/system/node_exporter.service"  echo "Installing Node Exporter version $VERSION..."  if wget -q https://github.com/prometheus/node_exporter/releases/download/v$VERSION/node_exporter-$VERSION.linux-amd64.tar.gz; then     tar -xzf node_exporter-$VERSION.linux-amd64.tar.gz     sudo mv node_exporter-$VERSION.linux-amd64/node_exporter $BIN_DIR/     sudo useradd -M -r -s /bin/false node_exporter || echo "User node_exporter already exists."      # Create systemd service     cat <<EOF | sudo tee $SERVICE_FILE [Unit] Description=Node Exporter After=network.target  [Service] User=node_exporter ExecStart=$BIN_DIR/node_exporter Restart=always  [Install] WantedBy=multi-user.target EOF      sudo systemctl daemon-reload     sudo systemctl enable node_exporter && sudo systemctl start node_exporter     echo "Node Exporter installed and running as a service." else     echo "Error: Failed to download Node Exporter version $VERSION. Check the version and try again."     exit 1 fi

4. Автоматическое создание правила алертинга

Этот скрипт создает правило алертинга. Триггеры Prometheus будут алертить на основе указанных тут порогов.

#!/bin/bash # Add alerting rules to Prometheus with validation  RULES_FILE="/opt/prometheus/alert_rules.yml" PROMETHEUS_CONFIG="/opt/prometheus/prometheus.yml"  echo "Adding alerting rules..."  if ! grep -q "alert_rules.yml" $PROMETHEUS_CONFIG; then     cat <<EOF | sudo tee -a $PROMETHEUS_CONFIG rule_files:   - $RULES_FILE EOF     echo "Rules file linked in Prometheus configuration." fi  # Create alerting rules cat <<EOF | sudo tee $RULES_FILE groups:   - name: example_alerts     rules:       - alert: HighCPUUsage         expr: 100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80         for: 2m         labels:           severity: warning         annotations:           summary: "High CPU usage detected"            description: "CPU usage is over 80% for the past 2 minutes on instance {{ $labels.instance }}." EOF  sudo systemctl restart prometheus && echo "Alerting rules added and Prometheus restarted."

5. Импорт дашборда Grafana

Скрипт автоматизировать импорт дашбордов используя Grafana API.

#!/bin/bash # Import a Grafana dashboard JSON file  GRAFANA_URL=${1:-"http://localhost:3000"} DASHBOARD_FILE=${2:-"/path/to/dashboard.json"} API_KEY=${3:-"your_api_key"}  echo "Importing Grafana dashboard from $DASHBOARD_FILE to $GRAFANA_URL..."  if [ ! -f "$DASHBOARD_FILE" ]; then     echo "Error: Dashboard file $DASHBOARD_FILE does not exist."     exit 1 fi  response=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Authorization: Bearer $API_KEY" \   -H "Content-Type: application/json" \   -d @"$DASHBOARD_FILE" "$GRAFANA_URL/api/dashboards/db")  if [ "$response" -eq 200 ]; then     echo "Dashboard imported successfully." else     echo "Error: Failed to import dashboard. HTTP status code: $response"     exit 1 fi

6. Автоматизация выполнения запросов PromQL

Скрипт поможет автоматизировать регулярное выполнение PromQL запросов для отчетности или хелсчеков. А заодно отформатирует вывод в читаемый формат.

#!/bin/bash # Run a PromQL query and display the results  PROMETHEUS_URL=${1:-"http://localhost:9090"} QUERY=${2:-"up"} QUERY_ENDPOINT="$PROMETHEUS_URL/api/v1/query"  echo "Running PromQL query: $QUERY..."  response=$(curl -s "$QUERY_ENDPOINT?query=$QUERY")  if jq -e . >/dev/null 2>&1 <<<"$response"; then     echo "Query results:"     echo "$response" | jq '.data.result[] | {metric: .metric, value: .value}' else     echo "Error: Failed to fetch query results. Ensure Prometheus is accessible at $PROMETHEUS_URL."     exit 1 fi

7. Отправка нотификаций в Slack

Скрипт интегрирует Slack с Alertmanager.

#!/bin/bash # Configure Slack notifications cat <<EOF | sudo tee /opt/alertmanager/alertmanager.yml global:   slack_api_url: 'https://hooks.slack.com/services/your/slack/webhook'  route:   receiver: slack  receivers:   - name: slack     slack_configs:       - channel: '#alerts'         text: "{{ .CommonAnnotations.summary }}" EOF  sudo systemctl restart alertmanager echo "Slack notifications configured."

8. Резервное копирование конфигурации

Скрипт выполнит резервное копирование конфигурации Prometheus и сожмет ее на выходе.

#!/bin/bash # Backup Prometheus data directory  DATA_DIR=${1:-"/opt/prometheus/data"} BACKUP_DIR=${2:-"/backups/prometheus"} TIMESTAMP=$(date +"%Y%m%d%H%M%S")  echo "Backing up Prometheus data from $DATA_DIR to $BACKUP_DIR..."  if [ ! -d "$DATA_DIR" ]; then     echo "Error: Prometheus data directory $DATA_DIR does not exist."     exit 1 fi  sudo mkdir -p "$BACKUP_DIR" sudo tar -czvf "$BACKUP_DIR/prometheus_backup_$TIMESTAMP.tar.gz" "$DATA_DIR"  if [ $? -eq 0 ]; then     echo "Backup completed: $BACKUP_DIR/prometheus_backup_$TIMESTAMP.tar.gz" else     echo "Error: Backup failed. Check permissions and disk space."     exit 1 fi

9. Автоматизация проверки конфигурации

Проверка конфигурации prometheus.yml перед применением. Использует для проверки promtool.

#!/bin/bash # Validate Prometheus configuration  CONFIG_FILE="/opt/prometheus/prometheus.yml" PROMTOOL_CMD="promtool"  # Check if promtool is installed if ! command -v $PROMTOOL_CMD &> /dev/null; then     echo "Error: promtool is not installed or not in PATH."     exit 1 fi  # Check if the configuration file exists if [ ! -f "$CONFIG_FILE" ]; then     echo "Error: Configuration file '$CONFIG_FILE' not found."     exit 1 fi  # Validate the Prometheus configuration $PROMTOOL_CMD check config "$CONFIG_FILE" if [ $? -eq 0 ]; then     echo "Configuration is valid." else     echo "Configuration validation failed." fi

10. Тестирование Alertmanager Receiver

Скрипт отправит демо-алерт в Alertmanager, чтобы проверить его работоспособность.

#!/bin/bash # Send a test alert to Alertmanager  ALERTMANAGER_URL=${1:-"http://localhost:9093"} RECEIVER=${2:-"default"} ALERT_FILE=${3:-"/tmp/test_alert.json"}  echo "Sending test alert to Alertmanager at $ALERTMANAGER_URL..."  # Create a test alert payload cat <<EOF > $ALERT_FILE [   {     "labels": {       "alertname": "TestAlert",       "severity": "info"     },     "annotations": {       "summary": "This is a test alert."     },     "startsAt": "$(date -Iseconds)"   } ] EOF  response=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Content-Type: application/json" \   -d @"$ALERT_FILE" "$ALERTMANAGER_URL/api/v1/alerts")  if [ "$response" -eq 200 ]; then     echo "Test alert sent successfully to receiver: $RECEIVER." else     echo "Error: Failed to send test alert. HTTP status code: $response"     exit 1 fi

11. Мониторинг логов Prometheus

Репортит об ошибках в логе.

#!/bin/bash # Monitor Prometheus logs for errors  LOG_FILE=${1:-"/var/log/prometheus/prometheus.log"} TAIL_LINES=${2:-100}  echo "Checking the last $TAIL_LINES lines of Prometheus logs at $LOG_FILE for errors..."  if [ ! -f "$LOG_FILE" ]; then     echo "Error: Log file $LOG_FILE does not exist."     exit 1 fi   grep -i "error" <(tail -n $TAIL_LINES "$LOG_FILE") || echo "No errors found in the last $TAIL_LINES lines."

Спасибо за внимание! Если было интересно, подписывайтесь на мой авторский канал по мониторингу monitorim_it, публикую там много интересного материала по теме.


ссылка на оригинал статьи https://habr.com/ru/articles/863920/


Комментарии

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *