前面我们已经安装完 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