Ansible - Function

Card Puncher Data Processing

About

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

List

include_tasks vs import_tasks

  • Include_tasks is done at runtime
  • while import_tasks is done at start time

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

  • one task that was skipped for Include_tasks
  • all tasks that were skipped after the import_tasks

Include_tasks

include_tasks 1) 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'

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:

  • 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 }}'





Discover More
Card Puncher Data Processing
Ansible - Getting Started

This is a getting started guide that shows how to install and where are the training/example. lightbulb ...



Share this page:
Follow us:
Task Runner