Ansible - Function

About

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

List

Include

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

Example:

  • for each nginx configuration file in a local directory with the filetree
  • call the nginx_template_conf.yml
  • pass the parameters:
    • fqdn with the file basename without extension.
    • file with the relative file path
    • protocol with the directory name
- 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 }}'

Include_tasks

include_tasks 2) permits to include a playbook with task

The same example than above where:

  • for each nginx configuration file in a local directory with the filetree
  • call the nginx_template_conf.yml
  • pass the parameters:
    • fqdn with the file basename without extension.
    • file with the relative file path
    • protocol with the directory name
- 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'

Powered by ComboStrap