Ansible Roles Global Variables

Rahul Sharma picture Rahul Sharma · Sep 23, 2017 · Viewed 8.6k times · Source

I use roles to deploy my machines, Roles have vars, but sometimes i have multiple role and i want to put a global variable file in the root folders, so ansible use vars/global.yml and overwrite role/vars/main.yml

#vars/global.yml
somevariable: somevalue

But if there is global variable in root folder, Just overwrite role based variable and implement vars/global instead.

├── Playbook.yml
├── ansible.cfg
├── roles
│   ├── Ansible-Role-UserProfile
│   │   ├── LICENSE
│   │   ├── README.md
│   │   ├── meta
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   └── main.yml
│   │   ├── templates
│   │   │   ├── rm.j2
│   │   │   └── vimrc.j2
│   │   └── vars
│   │       └── main.yml
└── vars
    └── global.yml

Is anything comes which suite reusability of roles and variable natively ?

Answer

techraf picture techraf · Sep 23, 2017

Have a look at the Variable Precedence: Where Should I Put A Variable? chapter.

All roles listed after "role vars" on the list will have precedence, so use any of these.

  • block vars (only for tasks in block)
  • task vars (only for the task)
  • role (and include_role) params
  • include params
  • include_vars
  • set_facts / registered vars
  • extra vars (always win precedence)

Otherwise use role defaults, which has the lowest priority, to define variable values. Role defaults are overridden by play vars, from the example in your question.