使用 ansible 模板化 haproxy 配置文件
今天使用 ansible 自动化一些日常工作,其中包括 haproxy 的配置变更,我们 haproxy 里面定义了很多 frontend 和 backend,猛一看还不好模版化,其实仔细研究一下发现完全可以通过模板的循环语法动态生成配置文件,在此分享下。首先看一下未模板化时的原始配置:
haproxy.cfg
:
global
maxconn 20000
ulimit-n 204800
log 127.0.0.1 local3
user haproxy
group haproxy
chroot /var/empty
nbproc 4 #启动后运行的进程数量
daemon #以后台形式运行haproxy
pidfile /var/run/haproxy.pid
defaults
log global
mode tcp
retries 3 #3次连接失败认为服务不可用,也可以在后面设置
timeout connect 5s #连接超时
timeout client 30s #客户端超时
timeout server 30s #服务器端超时
option redispatch
option nolinger
no option dontlognull
option tcplog
option log-separate-errors
listen admin_stats #监控页面设置
bind 0.0.0.0:26000
bind-process 1
mode http
log 127.0.0.1 local3 err
stats refresh 30s #每隔30秒自动刷新监控页面
stats uri /admin
stats realm welcome login\ Haproxy
stats auth admin:123456
stats hide-version
stats admin if TRUE
# 通过配置文件动态生成 hproxy 配置
frontend redis
bind *:6379
default_backend redis
backend redis
server 10.1.1.1:6379 10.1.1.1:6379 check inter 1500 rise 3 fall 3
frontend es
bind *:9300
default_backend es
backend es
server 10.1.1.2:9300 10.1.1.2