【Ansible 学习之旅】Playbook 中的 Include 语句

系列文章

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不怕娜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值