一、安装ansible
[root@master ~]# yum install epel-release -y
[root@master ~]# yum install ansible
二、编写playbook
[root@master monitor]# vi playbook.yaml
[root@master ansible]# cat playbook.yaml
#- hosts: webservers
- hosts: webservers dbservers
gather_facts: no
vars:
port: 9100
tasks:
- name: 推送二进制文件
unarchive: src=node_exporter-0.18.1.linux-amd64.tar.gz dest=/usr/local
- name: 重命名
shell: |
cd /usr/local/
if [ ! -d node_exporter ]; then
mv node_exporter-0.18.1.linux-amd64 node_exporter
fi
- name: 推送配置文件
copy: src=config.yaml dest=/usr/local/node_exporter
- name: 拷贝systemd文件
copy: src=node_exporter.service dest=/usr/lib/systemd/system
- name: 启动服务
shell: systemctl daemon-reload;systemctl restart node_exporter.service;systemctl enable node_exporter.service
#systemd: name=node_exporter state=started enable=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 }} {{ port }}
[root@master ansible]# vi hosts
[webservers]
192.168.10.115 ansible_port=31235 name=web1
192.168.10.117 ansible_port=31235 name=web2
[dbservers]
192.168.10.116 ansible_port=31235 name=db1
[root@master ansible]# vim 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":"10s"}]}' http://192.168.10.117:8500/v1/agent/service/register
[root@master ansible]# vi node_exporter.service
[Unit]
Description=node_exporter
[Service]
Restart=on-failure
#ExecStart=/usr/local/node_exporter/node_exporter --web.config=/usr/local/node_exporter/config.yaml
ExecStart=/usr/local/node_exporter/node_exporter
[Install]
WantedBy=multi-user.target
三、配置consul分组
分别做两个分组,一个是webservers,一个是dbservers分组
- job_name: 'webservers'
consul_sd_configs:
- server: '192.168.10.117:8500'
services: ['webservers']
- job_name: 'dbservers'
consul_sd_configs:
- server: '192.168.10.117:8500'
services: ['dbservers']
备注:这里的webservers和注册请求”name”:”webservers” 一一对应
四、执行playbook
[root@master ansible]# ansible-playbook -i hosts playbook.yaml -uroot -k
PLAY RECAP *******************************************************************************************************************************************************************************************************************************************************************
192.168.10.115 : ok=7 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.10.116 : ok=7 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.10.117 : ok=7 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
五、Targets展示
六、consul注销服务
参考官方文档:https://www.consul.io/api/agent/service.html
curl \
--request PUT \
http://192.168.10.117:8500/v1/agent/service/deregister/db1
留言