Ansible 使用 Playbook 管理 Nginx 配置檔案
阿新 • • 發佈:2019-01-04
前面我們已經安裝完 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