系列文章
Ansible 介绍和架构
Ansible 安装和入门
配置控制机器和受控机器
Inventory文件介绍
Ansible核心工具介绍
Ansible常用模块介绍与演示
Playbook 的基本概念
Playbook 的使用实例
Ansible 中的变量
目录
Include
Include Files
假如你希望在多个 play 或者多个 playbook 中重用同一个 task 列表,你可以使用 include files 做到这一点。
典型 task include file
一个典型的 task include file 由一个普通的 task 列表所组成,像这样:
# tasks/foo.yml
- name: placeholder foo
command: /bin/foo
- name: placeholder bar
command: /bin/bar
要在 Playbook 中包含这个文件,你可以使用 include_tasks
语句(在 Ansible 2.4 及以上版本推荐使用):
- name: Example playbook with included tasks
hosts: all
tasks:
- name: Include tasks from foo.yml
include_tasks: tasks/foo.yml
参数化的 include
还可以向 include 语句传递变量,这种方法被称为“参数化的 include”。
举个例子,如果我们要部署多个 wordpress 实例,我们可将所有的 wordpress task 写在一个 wordpress.yml
文件中, 然后再playbook中include该 wordpress.yml 文件并给参数赋值。
wordpress.yml
文件:
# tasks/wordpress.yml
- name: Create WordPress user
user:
name: "{{ wp_user }}"
home: /home/{{ wp_user }}
- name: Deploy WordPress files
copy:
src: /path/to/wordpress/files/
dest: /var/www/html/
owner: "{{ wp_user }}"
group: www-data
mode: 0755
在 Playbook 中,我们可以这样调用这个文件:
- name: Deploy multiple WordPress instances
hosts: all
tasks:
- name: Deploy WordPress instance for Timmy
include_tasks: tasks/wordpress.yml
vars:
wp_user: timmy
ssh_keys: [ 'keys/one.txt', 'keys/two.txt' ]
- name: Deploy WordPress instance for Alice
include_tasks: tasks/wordpress.yml
vars:
wp_user: alice
ssh_keys: [ 'keys/three.txt', 'keys/four.txt' ]
Include 处理器 (Handlers)
我们也可以使用 include 语句来包含处理器(Handlers)。例如,我们可以定义一个重启 Apache 的处理器,并在所有 Playbook 中使用它:
# handlers/handlers.yml
- name: Restart Apache
service:
name: apache
state: restarted
然后在一个 play 的最后使用 include 包含 handlers.yml:
- name: Example playbook with included handlers
hosts: all
handlers:
- include: handlers/handlers.yml
Include 其他 Playbook
Include 语句也可用来将一个 playbook 文件导入另一个 playbook 文件。这种方式允许你定义一个 顶层的 playbook,这个顶层 playbook 由其他 playbook 所组成。
举个例子:
- name: this is a play at the top level of a file
hosts: all
remote_user: root
tasks:
- name: say hi
tags: foo
shell: echo "hi..."
- include: load_balancers.yml
- include: webservers.yml
- include: dbservers.yml