Table of Contents

Ansible - Function

About

function in Ansible are tasks that includes other playbook and can pass variable.

List

include_tasks vs import_tasks

If you have a conditional (such as when), you would see:

Include_tasks

include_tasks 1) permits to include a playbook with task

The same example than above where:

- name: "Copy http and tcp site template configuration"
  with_filetree: 'host_files/{{ inventory_hostname }}/nginx/'
  include_tasks: nginx_template_conf.yml
  vars:
    fqdn: '{{ item.path | basename | splitext | first }}'
    file: '{{ item.path }}'
    protocol: '{{ item.path | dirname }}'
  when: item.state != 'directory'

Include (Deprecated)

The most known function task was include 2) but is now deprecated for more dedicated include syntax such as include_tasks, include_role, …

Example:

- name: "Copy http and tcp site template configuration"
  become: true
  with_filetree: 'host_files/{{ inventory_hostname }}/nginx/'
  include: nginx_template_conf.yml fqdn={{ item.path | basename | splitext | first }} file={{ item.path }} protocol={{ item.path | dirname }}
  when: item.state != 'directory'

Note that to pass variables, you can also use the var keywords. The below syntax is equivalent to the above.

  include: nginx_template_conf.yml
  vars:
    fqdn: '{{ item.path | basename | splitext | first }}'
    file: '{{ item.path }}'
    protocol: '{{ item.path | dirname }}'