Ansible 使用 Playbook 管理 Nginx 配置文件

前面我们已经安装完 Nginx,但是在日常维护中经常需要修改配置文件,并重新加载配置文件,因此来写一个管理 Nginx 配置文件的 Playbook:

[root@localhost ~]$ mkdir -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}
[root@localhost ~]$ tree /etc/ansible/nginx_config/
/etc/ansible/nginx_config/
└── roles               # 定义角色目录,new 为更新时用到的,old 为回滚时用到的
    ├── new 
    │   ├── files       # 存放配置文件的目录
    │   ├── handlers    # 存放当发生变更是要执行的操作,如修改配置文件、重启服务等
    │   ├── tasks       # 存放核心的任务配置文件
    │   └── vars        # 用来定义变量的目录
    └── old
        ├── files
        ├── handlers
        ├── tasks
        └── vars

把配置文件拷贝到 files 目录:

[root@localhost ~]$ cp /usr/local/nginx/conf/nginx.conf /etc/ansible/nginx_config/roles/new/files/
[root@localhost ~]$ cp -r /usr/local/nginx/conf/vhost /etc/ansible/nginx_config/roles/new/files/

定义变量:

[root@localhost ~]$ cd /etc/ansible/nginx_config/roles/
[root@localhost roles]$ cat new/vars/main.yml
nginx_basedir: /usr/local/nginx

定义重新加载 Nginx 服务:

[root@localhost roles]$ cat new/handlers/main.yml
- name: restart nginx
  shell: /etc/init.d/nginx reload

定义核心任务:

[root@localhost 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

定义总入口配置(更新操作):

[root@localhost ~]$ cat /etc/ansible/nginx_config/update.yml
---
- hosts: 192.168.119.134
  user: root
  roles:
    - new

执行:

[root@localhost ~]$ ansible-playbook /etc/ansible/nginx_config/update.yml

 

 

 

 

 

     

posted @ 2019-01-04 18:33  孔雀东南飞  阅读(873)  评论(0编辑  收藏  举报