4343223 发表于 2016-9-30 08:51:44

ansible管理nginx配置文件

#生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。下面我们来写个管理nginx配置文件的playbook
一、创建相关目录
mkdir-p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}


#其中new为更新时用到的,old为回滚时用到的,files下面为nginx.conf和vhosts目录,handlers为重启nginx服务的命令。
#关于回滚,需要在执行playbook之前先备份一下旧的配置,所以对于老配置文件的管理一定要严格,千万不能随便去修改线上机器的配置,并且要保证new/files下面的配置和线上的配置一致


二、拷贝配置文件
cd /usr/local/nginx/conf/
mkdir vhosts
cp -r nginx.conf vhosts/etc/ansible/nginx_config/roles/new/files/

三、定义变量vars文件夹的子入口yml文件
vim /etc/ansible/nginx_config/roles/new/vars/main.yml
nginx_basedir: /usr/local/nginx

四、定义handlers文件夹的子入口yml文件
vim /etc/ansible/nginx_config/roles/new/handlers/main.yml
- name: restart nginx
shell: /etc/init.d/nginx reload

五、创建核心tasks任务文件夹的子入口yml文件
vim /etc/ansible/nginx_config/roles/new/tasks/main.yml
- name: copy conffile
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

六、定义总入口yml文件
vim /etc/ansible/nginx_config/update.yml

---
- hosts: testhost
user: root
roles:
- new

七、执行:
ansible-playbook /etc/ansible/nginx_config/update.yml

八、测试
cd /etc/ansible/nginx_config/roles/new/files/vhosts
touch 1.txt
vim 1.txt
#ceshi1
#ceshi2
vim /etc/ansible/nginx_config/roles/new/files/nginx
加入include vhosts/*.conf;   #记住此处要加分号否则出错
然后重新同步:
ansible-playbook /etc/ansible/nginx_config/update.yml查看客户端的1.txt是否有更改,以及客户端是否重新加载了nginx,使用ps aux|grep nginx查看nginx的启动时间是不是最新的
九、回滚
#回滚前应该把旧文件备份一下
rsync -av/etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/
#而回滚的backup.yml对应的roles为old,回滚的时候只要执行backup.yml就行了

vim /etc/ansible/nginx_config/backup.yml
---- hosts: testhost user: root roles: - old


页: [1]
查看完整版本: ansible管理nginx配置文件