可以為playbook中的任務(wù)打tag標(biāo)簽遥赚,方便在ansible-playbook中設(shè)置只執(zhí)行哪些被打上tag的任務(wù)或忽略被打上tag的任務(wù)芦岂。
使用 tag 為 task 分類
tasks:
- name: make sure apache is running
service: name=httpd state=started
tags: apache
- name: make sure mysql is running
service: name=mysqld state=started
tags: mysql
以下是ansible-playbook命令關(guān)于tag的選項(xiàng)卑吭。
--list-tags # list all available tags
-t TAGS, --tags=TAGS # only run plays and tasks tagged with these values
--skip-tags=SKIP_TAGS # only run plays and tasks whose tags do not match these values
使用 include击罪,import 和 roles 提高 playbook 的復(fù)用性
如果playbook很大唆香,task很多步氏,或者某task要經(jīng)常使用虐块,可以考慮拆分位獨(dú)立文件俩滥。
Ansible 2.4 起引入 include 和 import 的概念
- import 是靜態(tài)導(dǎo)入,會(huì)在playbooks解析階段將父和子task變量全部讀取并加載
import_playbook, import_tasks 等 - include 是動(dòng)態(tài)導(dǎo)入贺奠,執(zhí)行play之前才加載變量
include_tasks, include_role 等
導(dǎo)入 task
導(dǎo)入task可以使用
import_tasks:
include_tasks
# playbook.yaml
# -- task/ntupdate.yml
---
- hosts: centos7
tasks:
- import_tasks: task/ntupdate.yaml
# ntupdate.yml
---
- name: execute ntpdate
shell: /usr/sbin/ntpdate ntp1.aliyun.com
雖然仍然可以用
include: task/ntupdate.yaml
來直接導(dǎo)入 task 或 playbook 已經(jīng)不推薦這么做霜旧,將來會(huì)被廢棄
導(dǎo)入 playbook
即加載一個(gè)或多個(gè)play
導(dǎo)入playbook可以使用 import_playbook
---
- name: first demo
hosts: cloud
vars:
name: finley
tasks:
- name: execute date cmd
shell: echo date
- name: create hello
shell: touch helloworld.txt
args:
creates: /tmp/hello.txt # 存在此文件就不執(zhí)行 shell
- include_tasks: tasks/task-hello.yml
- import_playbook: playbooks/web.yml
Role
role 需要一個(gè)特定的目錄結(jié)構(gòu),執(zhí)行時(shí)會(huì)自動(dòng)加載定義好的文件如vars_files,tasks,handles等
通過role進(jìn)行內(nèi)容分組方便與其他用戶分享role儡率。
示例項(xiàng)目結(jié)構(gòu)
site.yml
webservers.yml
fooservers.yml
roles/
common/
tasks/
handlers/
files/
templates/
vars/
defaults/
meta/
webservers/
tasks/
defaults/
meta/
- tasks目錄:存放task列表挂据。若role要生效,此目錄必須要有一個(gè)主task文件main.yml儿普,在main.yml中可以使用 include包含同目錄(即tasks)中的其他文件崎逃。
- handlers目錄: 存放handlers的目錄,若要生效眉孩,則文件必須名為main.yml文件个绍。
- files目錄:在task中執(zhí)行copy或script模塊時(shí)勒葱,如果使用的是相對(duì)路徑,則會(huì)到此目錄中尋找對(duì)應(yīng)的文件巴柿。
- templates 目錄:在task中執(zhí)行template模塊時(shí)错森,如果使用的是相對(duì)路徑,則會(huì)到此目錄中尋找對(duì)應(yīng)的模塊文 件篮洁。
- vars目錄:定義專屬于該role的變量,如果要有var文件殃姓,則必須為main.yml文件袁波。
- defaults 目錄:定義角色默認(rèn)變量,角色默認(rèn)變量的優(yōu)先級(jí)最低蜗侈,會(huì)被任意其他層次的同名變量覆蓋篷牌。如果要有var文件,則必須為main.yml文件踏幻。
- meta目錄:用于定義角色依賴(dependencies)枷颊,如果要有角色依賴關(guān)系,則文件必須為main.yml该面。
參考
https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse.html