Ansible is one of the most prominent tools among DevOps for managing software configuration because of its ease of use and bare minimum dependencies. The highlight of this tool is Ansible roles which provide a wholesome package of various functionalities that we need for software configuration.
As we know that ansible roles have a wide directory structure that looks something like this.
$ tree -d . ├── defaults ├── files ├── handlers ├── media ├── meta ├── molecule │ └── default │ └── tests ├── tasks └── templates 10 directories
We can read online about the significance of these directories but often there is some confusion around two of them that always bugs me, which are vars and defaults. Whenever I write a role I often think of whether to put my variables in defaults or the vars.
According to Ansible’s definition, the difference between defaults and vars is:
defaults mean “default variables for the roles” and vars mean “other variables for the role”.
The priority of the vars is higher than that of defaults.
For example, consider a variable named ‘version’ defined in the defaults have value ‘5.0.1’ and the same variable defined in vars have value ‘7.1.3’, so the final value that will be taken into account is the value defined in vars i.e., ‘7.1.3’.
Due to my limited understanding of this, I used to define all variables in defaults and whenever needed to override them, I declared those variables in vars.
But there was more to it just than precedence, which motivated me to deep dive into it and finds out that there are two types of variables in terms of content, “static” with constant value and “dynamic” with changing value. According to the ansible definition, the static variables should be placed in default and the dynamic should be placed in vars.