前面我們已經安裝完 Nginx,但是在日常維護中經常需要修改配置檔案,并重新加載配置檔案,是以來寫一個管理 Nginx 配置檔案的 Playbook:
[[email protected] ~]$ mkdir -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}
[[email protected] ~]$ tree /etc/ansible/nginx_config/
/etc/ansible/nginx_config/
└── roles # 定義角色目錄,new 為更新時用到的,old 為復原時用到的
├── new
│ ├── files # 存放配置檔案的目錄
│ ├── handlers # 存放當發生變更是要執行的操作,如修改配置檔案、重新開機服務等
│ ├── tasks # 存放核心的任務配置檔案
│ └── vars # 用來定義變量的目錄
└── old
├── files
├── handlers
├── tasks
└── vars
把配置檔案拷貝到 files 目錄:
[[email protected] ~]$ cp /usr/local/nginx/conf/nginx.conf /etc/ansible/nginx_config/roles/new/files/
[[email protected] ~]$ cp -r /usr/local/nginx/conf/vhost /etc/ansible/nginx_config/roles/new/files/
定義變量:
[[email protected] ~]$ cd /etc/ansible/nginx_config/roles/
[[email protected] roles]$ cat new/vars/main.yml
nginx_basedir: /usr/local/nginx
定義重新加載 Nginx 服務:
[[email protected] roles]$ cat new/handlers/main.yml
- name: restart nginx
shell: /etc/init.d/nginx reload
定義核心任務:
[[email protected] roles]$ cat new/tasks/main.yml
- name: copy conf file
copy: src={{ item.src }} dest={{ nginx_basedir }}/{{ item.dest }} backup=yes owner=root group=root
with_items:
- { src: nginx.conf, dest: conf/nginx.conf }
- { src: vhost, dest: conf/ }
notify: restart nginx
定義總入口配置(更新操作):
[[email protected] ~]$ cat /etc/ansible/nginx_config/update.yml
---
- hosts: 192.168.119.134
user: root
roles:
- new
執行:
[[email protected] ~]$ ansible-playbook /etc/ansible/nginx_config/update.yml