Ansible+Consul实现100台主机自动监控
架构:

原理:
- ansible批量部署node_exporter;
- 基于consul服务发现;
- 将node_exporter所在机器的ip和端口按照机器的用途进行分组并注册到consul;
- 普罗米修斯从consul获取到ip和端口自动加入监控
- grafana按照分组进行展示
100台:web、db、负载均衡、消息队列进行分组:
"id": "web-1","name": "web"
"id": "web-2","name": "web"
"id": "db-1","name": "db"
"id": "db-2","name": "db"
安装ansible:
yum -y install epel-release
yum -y install ansible
把原来机器已经部署的node_exporter清除,完全基于ansible来部署node_exporter:
[root@k8s-2 monitor]# mv node_exporter/ node_exporter.bak
普罗米修斯配置分组web和db,并且consul安装在132上面:
- job_name: 'web'
consul_sd_configs:
- server: 192.168.121.132:8500
services: ['webservers']
- job_name: 'db'
consul_sd_configs:
- server: 192.168.121.132:8500
services: ['dbservers']
配置ansible:
[root@k8s-1 ansible]# pwd
/opt/monitor/ansible
[root@k8s-1 ansible]# ll
total 9324
-rw-r--r--. 1 root root 320 May 2 00:44 consul-register.sh
-rw-r--r--. 1 root root 77 May 2 01:10 hosts
-rw-r--r--. 1 root root 9520728 Oct 27 2020 node_exporter-1.0.1.linux-amd64.tar.gz
-rw-r--r--. 1 root root 203 May 2 05:35 node_exporter.service
-rw-r--r--. 1 root root 917 May 2 05:49 playbook.yaml
cousul-register.sh配置,$1-$4对应ansible的四个变量,用于获取hosts文件里面的数据:
[root@k8s-1 ansible]# cat consul-register.sh
#!/bin/bash
service_name=$1
instance_id=$2
ip=$3
port=$4
curl -X PUT -d '{"id": "'"$instance_id"'","name": "'"$service_name"'","address": "'"$ip"'","port": '"$port"',"tags": ["'"$service_name"'"],"checks": [{"http": "http://'"$ip"':'"$port"'","interval": "5s"}]}' http://192.168.121.132:8500/v1/agent/service/register
playbook.yaml配置:
[root@k8s-1 ansible]# vim playbook.yaml
- hosts: dbservers
gather_facts: no
vars:
exporter_port: 9100
tasks:
- name: 推送二进制文件
unarchive: src=node_exporter-1.0.1.linux-amd64.tar.gz dest=/usr/local
- name: 重命名
shell: |
cd /usr/local
if [ ! -d node_exporter ];then
mv node_exporter-1.0.1.linux-amd64 node_exporter
fi
- name: 推送配置文件
copy: src=config.yml dest=/usr/local/node_exporter
- name: 拷贝systemd文件
copy: src=node_exporter.service dest=/usr/lib/systemd/system
- name: 启动服务
systemd: name=node_exporter state=restarted enabled=yes daemon_reload=yes
- name: 推送注册脚本
copy: src=consul-register.sh dest=/usr/local/bin/
- name: 注册当前节点
# 服务名 实例名 IP 端口
shell: /bin/bash /usr/local/bin/consul-register.sh {{ group_names[0] }} {{ name }} {{ inventory_hostname }} {{exporter_port}}
hosts配置:
[root@k8s-1 ansible]# cat hosts
[webservers]
192.168.121.132 name=web1
[dbservers]
192.168.121.133 name=db1
node_exporter.service配置:
[root@k8s-1 ansible]# cat node_exporter.service
[Unit]
Description=node_exporter
[Service]
ExecStart=/usr/local/node_exporter/node_exporter
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
[Install]
WantedBy=multi-user.target
[root@k8s-1 ansible]#
执行剧本:
ansible-playbook -i hosts playbook.yaml -uroot -k
SSH password:
查看普罗米修斯:

查看consul:

查看grafana:

100台监控,原理一样,只需要修改hosts和prometheus.yml配置即可。
浙公网安备 33010602011771号