可以为playbook中的任务打tag标签,方便在ansible-playbook中设置只执行哪些被打上tag的任务或忽略被打上tag的任务。
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命令关于tag的选项。
--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
如果playbook很大,task很多,或者某task要经常使用,可以考虑拆分位独立文件。
Ansible 2.4 起引入 include 和 import 的概念
导入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
来直接导入 task 或 playbook 已经不推荐这么做,将来会被废弃
即加载一个或多个play 导入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 # 存在此文件就不执行 shell
- include_tasks: tasks/task-hello.yml
- import_playbook: playbooks/web.yml
role 需要一个特定的目录结构,执行时会自动加载定义好的文件如vars_files,tasks,handles等 通过role进行内容分组方便与其他用户分享role。
示例项目结构
site.yml
webservers.yml
fooservers.yml
roles/
common/
tasks/
handlers/
files/
templates/
vars/
defaults/
meta/
webservers/
tasks/
defaults/
meta/
https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse.html