重用单个playbook文件(include语句)

Include语句的功能,基本的代码重用机制。主要重用tasks。同时Include可将tasks分割成多个文件,避免Playbook过于臃肿,使用户更关注于整体的架构,而不是实现的细节上。

普通用法

像其它语言的Include语句一样,直接Include:

---
# possibly saved as tasks/firewall_httpd_default.yml

  - name: insert firewalld rule for httpd
    firewalld: port=80/tcp permanent=true state=enabled immediate=yes

main.yml文件中调用include的方法:

tasks:
    - include: tasks/firewall_httpd_default.yml

高级用法-使用参数

include文件中还可以定义参数

被include的文件tasks/firewall_httpd_default.yml中,使用\{\{ port \}\}定义了一个名字为port的参数。

---
  - name: insert firewalld rule for httpd
    firewalld: port=\{\{ port \}\}/tcp permanent=true state=enabled immediate=yes

传参数的各种方法

  tasks:
    - include: tasks/firewall.yml port=80
    - include: tasks/firewall.yml port=3260
    - include: tasks/firewall.yml port=423

  tasks:

    - include: wordpress.yml
      vars:
          wp_user: timmy
          ssh_keys:
            - keys/one.txt
            - keys/two.txt
  tasks:
   - { include: wordpress.yml, wp_user: timmy, ssh_keys: [ 'keys/one.txt', 'keys/two.txt' ] }

  ---
  - hosts: lb
    vars:
      port: 3206
    remote_user: root
    tasks:
      - include: tasks/firewall.yml

include语句相关的那些坑

  handlers:
    - include: handlers/handlers.yml

然而为什么有一处文档里面写可以调用。文档下面两个地方提到include里面的handlers,但是两处是矛盾的:

通过下面的例子实测后,基于ansible1.9是不能调用include里面的handler的,不过基于ansible2.0+是可以调用include里面的handler的。所以在使用的时候注意你安装的ansible版本。

  ---
  - hosts: lb
    user: root
    gather_facts: no
    vars:
        random_number: "\{\{ 10000 | random \}\}"
    tasks:
    - name: Copy the /etc/hosts to /tmp/hosts.\{\{ random_number \}\}
      copy: src=/etc/hosts dest=/tmp/hosts.\{\{ random_number \}\}
      notify:
        - restart apache
        - restart apache in handlers


    handlers:
      - include: handlers/handlers.yml
      - name: restart apache
        debug: msg="This is the handler restart apache"
  - 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,或者叫playbook include
  - include: load_balancers.yml
  - include: webservers.yml
  - include: dbservers.yml