1、引用的目的
当项目过大时,一个项目里执行的模块和play变多时,我们可以将原有的模块引入减少工作量,同时也可以将任务分配,加快任务进度,最后将任务组合起来即可。
2、两种方式
2.1 任务包含
##任务包含
tasks:
- include_tasks: tasks.yml
2.2 任务导入
##任务导入
- name: configure webserver
import_playbook: web.yml ##导入web.yml文件
使用导入时,when等条件语句会应用于导入的每个任务;但循环不能用于于导入任务。
3、用例说明
以两台主机为单位,对所有linux.com域内的所有主机配置Apache服务。
整体结构:
##整体结构
[root@contral progreammer]# tree .
.
├── ansible.cfg ##ansible配置
├── files ##Apache配置文件
│ └── example.conf
├── inventory ##管理的主机
├── playbook.yml ##主play
└── tasks ##子任务
├── firewall_task.yml ##火墙配置
├── install_and_enabled.yml ##安装配置
└── web_task.yml ##Apache配置
2 directories, 7 files
ansible配置:
##清单配置
1 [weba]
2 servera.linux.com
3 [webb]
4 serverb.linux.com
5 [webc]
6 serverc.linux.com
##默认配置
1 [defaults]
2 inventory = ./inventory
各个模块:
##安装模块,可调用安装apadhe和firewall
1 ---
2 - name: install {{ packages }}
3 yum:
4 name: "{{ packages }}"
5 state: latest
6 - name: Enable and start {{ packages }}
7 service:
8 name: "{{ packages }}"
9 enabled: true
10 state: started
~
##apache配置
1 ---
2 - name: install and start httpd
3 import_tasks: install_and_enabled.yml
4 vars:
5 packages: httpd
6 service: httpd
7 - name: Configure apache
8 copy:
9 src: ../files/example.conf
10 dest: /etc/httpd/conf.d/example.conf
11 owner: root
12 group: root
13 mode: 0644
14 notify:
15 - restart httpd
##火墙配置
1 ---
2 - name: Install and start firewalld
3 import_tasks: install_and_enabled.yml
4 vars:
5 packages: firewalld
6 service: firewalld
7
8 - name: firewalld permint apcahe
9 firewalld:
10 service: http
11 immediate: true
12 permanent: true
13 state: enabled
##Apache配置页
1 <VirtualHost *:80>
2 DocumentRoot /www
3 ServerName www.linux.com
4 </VirtualHost>
5
6 <VirtualHost *:80>
7 DocumentRoot /bbs
8 ServerName bbs.linux.com
9 </VirtualHost>
主Playbook
##主play
1 ---
2 - name: Install and Configure web service
3 hosts: server*.linux.com
4 serial: 2
5 tasks:
6 - name: import web_tasks.yml
7 import_tasks: tasks/web_task.yml
8
9 - name: import firewall_task.yml
10 import_tasks: tasks/firewall_task.yml
11 handlers:
12 - name: restart httpd
13 service:
14 name: httpd
15 state: restarted
调试结果:
