Ansible 管理配置文件

* 生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。下面我们来写个管理nginx配置文件的playbook

1.mkdir  -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}

说明:其中new为更新时用到的,old为回滚时用到的,files下面为nginx.conf和vhosts目录,handlers为重启nginx服务的命令

关于回滚,需要在执行playbook之前先备份一下旧的配置,所以对于老配置文件的管理一定要严格,千万不能随便去修改线上机器的配置,并且要保证new/files下面的配置和线上的配置一致

2.先把nginx.conf和vhosts目录放到files目录下面

cd /usr/local/nginx/conf/ 

cp -r nginx.conf vhosts  /etc/ansible/nginx_conf/roles/new/files/

3.定义变量

vim /etc/ansible/nginx_config/roles/new/vars/main.yml   #内容如下

nginx_basedir: /usr/local/nginx       #可以不定义,但为了规范和完美,最好写上

4.定义重新加载nginx配置文件服务

vim /etc/ansible/nginx_config/roles/new/handlers/main.yml   #内容如下

- name: restart nginx

  shell: /etc/init.d/nginx reload

5.定义tasks核心任务

vim /etc/ansible/nginx_config/roles/new/tasks/main.yml  #内容如下

- name: copy conf file

  copy: src=` item`.`src ` dest=` nginx_basedir `/` item`.`dest ` backup=yes owner=root group=root mode=0644

  with_items:

    - { src: nginx.conf, dest: conf/nginx.conf }

    - { src: vhosts, dest: conf/ }

  notify: restart nginx

说明:` item`.`src `相当于数组,循环时,两次的源地址和目的地址是不一样的,固定写法,如:item.*  很好用。

6.最后是定义总入口配置文件

vim /etc/ansible/nginx_config/update.yml   #内容如下

---

- hosts: testhost

  user: root

  roles:

  - new

执行命令:ansible-playbook /etc/ansible/nginx_config/update.yml  #下发配置,重启服务。

而回滚的backup.yml对应的roles为old

回滚操作就是把旧的配置重新下发,然后重新加载nginx服务,所以每次发布新配置时,先备份旧配置

1.rsync -av  /etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/

#new/下的文件在修改之前是旧配置,所以先复制到old/下,如果新的new出现错误,然后回滚old

2.vim /etc/ansible/nginx_config/backup.yml    #内容如下

---

- hosts: testhost

  user: root

  roles:

  - old

3.执行命令:ansible-playbook /etc/ansible/nginx_config/backup.yml