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