1. 程式人生 > >ansible運維自動化之五---roles高階進階

ansible運維自動化之五---roles高階進階

Roles應用場景

複雜場景(建議使用roles)

  • 變更指定主機或主機組
  • 如命名不規範維護和傳承成本大
  • 某些功能需Inlogs.com/blog/675193/201901/675193-20190102225646401-1546983424.png)

roles下面每一個目錄是一個專案,比如git專案,該目下按功能集的不同又分為多個功能集 如 tasks(執行命令) files(要傳輸到遠端的檔案)
vars(要去使用的變數),每個功能集下面有一個main.yml

roles示例-1

cd /etc/ansible/roles/ #roles可以放在任何目錄
mkdir nginx && cd nginx
mkdir {tasks,templates,files,vars,handlers,meta,default}

vim  tasks/nginstall.yml
---
- name: install nginx
  yum: name=nginx state=installed
cp ~/ansible/templates/nginx.conf.j2   /etc/ansible/roles/templates  #先把nginx.conf.j2中的for迴圈註釋掉
vim tasks/ngconf.yml
- name: nginx config
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
vim tasks/main.yml
- include: nginstall.yml
- include: ngconf.yml


vim nginx-role.yml  #隨便哪個目錄
---
- hosts: web
  remote_user: root
  vars:
  - webs:
     - node1
     - node2
     - node3
  roles:
  - nginx
 
ansible-playbook -C nginx-role.yml
ansible-playbook  nginx-role.yml

示例2 使用handlers

vim handlers/main.yml
---
- name: restart nginx
  service: name=nginx state=restarted

 
vim tasks/ngconf.yml
- name: nginx config
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  notify: restart nginx
vim nginx-role.yml   
---
- hosts: web
  remote_user: root
  vars:
  - webs:
     - node1
     - node2
     - node3
  roles:
  - nginx

修改templates下面的nginx.conf.j2中的埠測試
ansible-playbook nginx-role.yml