Example 15
hosts.yml
centos:
hosts:
provisioner:
ansible_connection: local
centos1:
ansible_host: '192.168.77.22'
ubuntu:
hosts:
ubuntu1:
ansible_host: '192.168.77.23'
playbook.yml
- name: Example playbook
hosts: provisioner
gather_facts: false
vars:
vars_directory_content: "{{ lookup('pipe', 'ls {{ playbook_dir }}')}}"
tasks:
- name: Set the custom fact
set_fact:
fact_directory_content: "{{ lookup('pipe', 'ls')}}"
- name: Initial value for vars_directory_content
debug:
msg: "{{ vars_directory_content }}"
- name: Initial value for fact_directory_content
debug:
msg: "{{ fact_directory_content }}"
- name: Add a file to the playbook directory
file:
state: touch
dest: "{{ playbook_dir}}/var_vs_fact"
- name: Post-modification value for vars_directory_content
debug:
msg: "{{ vars_directory_content }}"
- name: Post-modification value for fact_directory_content
debug:
msg: "{{ fact_directory_content }}"
Tip
In Ansible vars
and facts
act in a different manner. Knowing when and how to use on of these concepts or another is key to successful playbook writing.
Execute the following command
ansible-playbook playbook.yml
What is the expected output of the command ?
The var
will reflect the changes in the directory content. Variables are evaluated in runtime, whereas facts
as the name suggests are set in stone.