SaltStack部署Redis主从实现

需求:

  1. 192.168.56.11是主,192.168.56.12是从
  2. redis监听自己的ip地址,而不是0.0.0.0

分析:
linux-node1 安装 配置 启动
linux-node2 安装 配置 启动 设置主从

[root@linux-node1 ~]# yum install redis -y
[root@linux-node1 prod]# mkdir redis/files -p
[root@linux-node1 redis]# cp /etc/redis.conf /srv/salt/prod/redis/files/
[root@linux-node1 redis]# tree 
.
├── files
│   └── redis.conf
└── init.sls

1 directory, 2 files
[root@linux-node1 redis]# vim init.sls 
redis-install:
  pkg.installed:
    - name: redis

redis-config:
  file.managed:
    - name: /etc/redis.conf
    - source: salt://redis/files/redis.conf
    - user: root
    - group: root
    - mode: 644
    - template: jinja
      defaults:
      PORT: 6379
      IPADDR: {{ grains['fqdn_ip4'][0] }}

redis-service:
  service.running:
    - name: redis
    - enable: True
    - reload: True
[root@linux-node1 redis]# salt '*' state.sls redis.init saltenv=prod  #测试单一执行sls是否成功
[root@linux-node1 redis]# netstat -tulnp|grep redis-server
tcp        0      0 192.168.56.11:6379      0.0.0.0:*               LISTEN      10186/redis-server  
[root@linux-node2 ~]# netstat -tulnp |grep redis-server
tcp        0      0 192.168.56.12:6379      0.0.0.0:*               LISTEN      17973/redis-server  

主从配置:
[root@linux-node1 redis]# vim master.sls 
include:
  - redis.init
[root@linux-node1 redis]# vim slave.sls 
include:
  - redis.init

slave_config:
  cmd.run:
    - name: redis-cli -h 192.168.56.12 slaveof 192.168.56.11 6379--->设置主从
    - unless: redis-cli -h 192.168.56.12 info |grep role:slave-->判断node2是否为从,如果是就不执行设置主从
    - require:
      - service: redis-service
[root@linux-node1 redis]# vim /srv/salt/base/top.sls #配置top file
prod:
  'linux-node1.example.com':
    - lamp
    - redis.master
  'linux-node2.example.com':
    - lamp
    - redis.slave
[root@linux-node1 redis]# salt '*' state.highstate
......
----------
          ID: slave_config
    Function: cmd.run
        Name: redis-cli -h 192.168.56.12 slaveof 192.168.56.11 6379
      Result: True
     Comment: Command "redis-cli -h 192.168.56.12 slaveof 192.168.56.11 6379" run
     Started: 12:08:46.428924
    Duration: 31.328 ms
     Changes:   
              ----------
              pid:
                  18132
              retcode:
                  0
              stderr:
              stdout:
                  OK

Summary for linux-node2.example.com
-------------
Succeeded: 14 (changed=1)
Failed:     0
-------------
Total states run:     14
Total run time:    1.527 s
......
[root@linux-node1 redis]# tree 
.
├── files
│   └── redis.conf
├── init.sls
├── master.sls
└── slave.sls

1 directory, 4 files
[root@linux-node1 redis]# cat slave.sls 
include:
  - redis.init

slave_config:
  cmd.run:
    - name: redis-cli -h 192.168.56.12 slaveof 192.168.56.11 6379
    - unless: redis-cli -h 192.168.56.12 info |grep role:slave
    - require:
      - service: redis-service

TIPS:生产环境中,务必使用test=True进行与测试,并且目标选择一个节点进行,避免错误,影响业务的运行。