Ansible facts nested variable syntax preference
-
Consider the below example playbook.
For those that use Ansible regularly, do you have a syntax preference when referencing nested variables within Ansible facts? From what I've gathered there doesn't seem to be a technical difference between these formats:
ansible_cmdline.BOOT_IMAGE
ansible_cmdline['BOOT_IMAGE']
ansible_facts.cmdline.BOOT_IMAGE
ansible_facts['cmdline']['BOOT_IMAGE']
The example in the documentation shows using
ansible_facts
and mentions using either dots or brackets, but it appears just starting withansible_cmdline
in this example appears to work fine.--- - name: Testing Ansible facts variable syntax hosts: ansible-client-5 become: yes tasks: - name: Display BOOT_IMAGE using variable name with dots. debug: msg: "The ansible_cmdline.BOOT_IMAGE is {{ ansible_cmdline.BOOT_IMAGE }}." - name: Display BOOT_IMAGE using variable name with brackets. debug: msg: "The ansible_cmdline['BOOT_IMAGE'] is {{ ansible_cmdline['BOOT_IMAGE'] }}." - name: Display BOOT_IMAGE using ansible facts variable with dots. debug: msg: "The ansible_facts.cmdline.BOOT_IMAGE is {{ ansible_facts.cmdline.BOOT_IMAGE }}." - name: Display BOOT_IMAGE using ansible facts variable with brackets. debug: msg: "The ansible_facts['cmdline']['BOOT_IMAGE'] is {{ ansible_facts['cmdline']['BOOT_IMAGE'] }}." ...
-
Looks like Bracket notation is best choice instead of dot.
Bracket notation always works. Dot notation can cause problems because some keys collide with attributes and methods of python dictionaries. Use bracket notation if you use keys which start and end with two underscores (which are reserved for special meanings in python) or are any of the known public attributes:
-
@black3dynamite said in Ansible facts nested variable syntax preference:
Looks like Bracket notation is best choice instead of dot.
Bracket notation always works. Dot notation can cause problems because some keys collide with attributes and methods of python dictionaries. Use bracket notation if you use keys which start and end with two underscores (which are reserved for special meanings in python) or are any of the known public attributes:
Overlooked that in the documentation. While it's less efficient to type
['
and']
rather than.
, I'll live with it.