I use Ansible to manage configuration of a small group of real & virtual Linux machines. I am self-taught in Ansible, having gathered info here & there. I follow my own “template” for roles, so most of my roles use a var “pkgs_distro” to list any Linux-distro-specific packages to install. Is it “wrong” to reuse the same var name in multiple roles?
For each role, defaults/main.yml sets pkgs_distro to the empty list. This may or may not be overridden by distro-specific settings in the vars dir (e.g. vars/Fedora.yml or vars/Ubuntu.yml).
This mostly works well. But for some roles, pkgs_distro continues to have the value set by the most recent previous role. If role “foo” sets pkgs_distro to [foo_a, foo_b, ], then role “bar” runs next with no distro-specific setting, bar may have either the empty list or [foo_a, foo_b, ] as the value of pkgs_distro. I expect pkgs_distro to always be the empty list in this situation, as set in defaults/main.yml.
This surprising behavior seems to be documented, as the Ansible docs say the settings in the defaults dir have very low priority and can be overridden by settings from many other locations, including cached values. Two approaches for dealing with the behavior come to mind:
- Make var names unique for each role, or
- Make sure each var gets set by a file loaded from the vars dir.
So… am I doing Ansible wrong, misusing the defaults dir? Is Ansible broken? What’s the best approach for dealing with vars which may or may not have distro-specific values?
Thanks for any thoughts on the matter.