Playbook 是由一個或多個piay組成的列表,只要功能是講task 定義好角色歸併未一組進行統一管理,也就是經過task調用 Ansible 的模講多個play組成在一個playbook中運行mysql
- hosts: webserver //定義的主機組,即應用的主機 vars: //定義變量 http_port: 80 max_clients: 200 user: root tasks: //執行的任務 - name: ensure apache is at the latest version #顯示信息自定義顯示輸出 yum: pkg=httpd state=latest #模塊對參數 state=latest 檢查最新版本 - name: write the apache config file template: src=/srv/httpd.j2 dest=/etc/httpd.conf #放在管理端 notify: #調用 - restart apache #調用下面的參數 - name: ensure apache is running service: name=httpd state=started #開啓 restarted 重啓 stopped 中止 handlers: //處理器 - name: restart apache service: name=httpd state=restarted 執行一個playbook ansible-playbook [yaml文件名] 例如:ansible-playbook ping.yml 參數:-k(–ask-pass) 用來交互輸入ssh密碼 -K(-ask-become-pass) 用來交互輸入sudo密碼 -u 指定用戶
命令 | 說明 |
---|---|
ansible-playbook nginx.yaml --syntax-check | 檢查yaml文件的語法是否正確 |
ansible-playbook nginx.yaml --list-task | 檢查tasks任務 |
ansible-playbook nginx.yaml --list-hosts | 檢查生效的主機 |
ansible-playbook nginx.yaml --start-at-task='Copy Nginx.conf' | 指定從某個task開始運行 |
名稱 | IP | 組號 |
---|---|---|
主服務器 | 192.168.10.5 | |
被管理服務器 | 192.168.10.8 | aaa |
被管理服務器 | 192.168.10.11 | bbb |
能夠爲每一個任務定義遠程執行用戶:linux
- hosts: mysql remote_user: root tasks: #任務 - name: test connection #顯示信 ping: #使用ping這個模塊 remote_user: zhangsan #指定遠程主機執行tasks的運行用戶爲zhangsan
指定遠程主機sudo切換用戶:nginx
- hosts: mysql remote_user: root become: yes #2.6版本之後的參數,以前是sudo,意思爲切換用戶運行 become_user: mysql #指定sudo用戶爲mysql
忽略錯誤,強制返回成功web
- hosts: webserver remote_user: root tasks: - name: disable selinux command: '/sbin/setenforce 0' ignore_errors: True #忽略錯誤,強制返回成功 - name: make sure apache is running service: name=httpd state=started
Handlers也是一些task的列表,和通常的task並無什麼區別。
是由通知者進行的notify,若是沒有被notify,則Handlers不會執行,假如被notify了,則Handlers被執行
無論有多少個通知者進行了notify,等到play中的全部task執行完成以後,handlers也只會被執行一次sql
在主配置文件中定義變量
shell
若是須要根據變量、facts(setup)或此前任務的執行結果來做爲某task執行與否的前提時要用到條件測試,在Playbook中條件測試使用when子句。
在task後添加when子句便可使用條件測試:when子句支持jinjia2表達式或語法apache
當有須要重複性執行的任務時,可使用迭代機制。其使用格式爲將須要迭代的內容定義爲item變量引用,並經過with_items語句指明迭代的元素列表便可。
定義標籤
事實上,不光能夠爲單個或多個task指定同一個tags。playbook還提供了一個特殊的tags爲always。做用就是當使用always當tags的task時,不管執行哪個tags時,定義有always的tags都會執行安全