Include语句

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

普通用法

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

  1. ---
  2. # possibly saved as tasks/firewall_httpd_default.yml
  3. - name: insert firewalld rule for httpd
  4. firewalld: port=80/tcp permanent=true state=enabled immediate=yes

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

  1. tasks:
  2. - include: tasks/firewall_httpd_default.yml

高级用法-使用参数

include文件中还可以定义参数

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

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

传参数的各种方法

  • 在执行的playbook传参数,可以加在行尾,使用空格分隔:

    1. tasks:
    2. - include: tasks/firewall.yml port=80
    3. - include: tasks/firewall.yml port=3260
    4. - include: tasks/firewall.yml port=423
  • 还可以使用yml的字典传参数:

    1. tasks:
    2. - include: wordpress.yml
    3. vars:
    4. wp_user: timmy
    5. ssh_keys:
    6. - keys/one.txt
    7. - keys/two.txt
  • 还可以把一条task简写成成一个类JSON的形式传参数:

    1. tasks:
    2. - { include: wordpress.yml, wp_user: timmy, ssh_keys: [ 'keys/one.txt', 'keys/two.txt' ] }
  • 当然在playbook中已经定义了的参数,就不需要再显示传入值了,可以直接写成下面的:

    1. ---
    2. - hosts: lb
    3. vars:
    4. port: 3206
    5. remote_user: root
    6. tasks:
    7. - include: tasks/firewall.yml

include语句相关的那些坑

  1. - hosts: lb
  2. user: root
  3. gather_facts: no
  4. vars:
  5. random_number: "{{ 10000 | random }}"
  6. tasks:
  7. - name: Copy the /etc/hosts to /tmp/hosts.{{ random_number }}
  8. copy: src=/etc/hosts dest=/tmp/hosts.{{ random_number }}
  9. notify:
  10. - restart apache
  11. - restart apache in handlers
  12. handlers:
  13. - include: handlers/handlers.yml
  14. - name: restart apache
  15. debug: msg="This is the handler restart apache"
  • Ansible允许的全局(或者叫plays)加include

    然而这种使用方式并不推荐,首先它不支持嵌入include,而且很多playbook的参数也不可以使用。

    1. - name: this is a play at the top level of a file
    2. hosts: all
    3. remote_user: root
    4. tasks:
    5. - name: say hi
    6. tags: foo
    7. shell: echo "hi..."
    8. # 全局include,或者叫playbook include
    9. - include: load_balancers.yml
    10. - include: webservers.yml
    11. - include: dbservers.yml
  • 为了使include功能更强大,在每个新出的ansible都会添加新的一些功能,例如在2.0中添加了include动态名字的yml,然而这样的用法有很多的限制,不够成熟,可能在更新的ansible又去掉了,学习和维护成本很高。所以需要使用更灵活的重用机制时,建议用下一节介绍的role。