3

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 ?

techraf
  • 64,883
  • 27
  • 193
  • 198
Rahul Sharma
  • 779
  • 2
  • 12
  • 27

2 Answers2

3

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.

techraf
  • 64,883
  • 27
  • 193
  • 198
1

Put your global variables in group_vars/all. See how this fits in your directory structure in Directory layout.

Role vars have precedence over group_vars, so you can override the global value in a role.

René Pijl
  • 4,310
  • 1
  • 19
  • 25
  • 1
    OP wrote "i want to put a global variable file in the root folders, so ansible use vars/global.yml and **overwrite** role/vars/main.yml" -- you answer exactly the opposite request. What am I missing? – techraf Sep 23 '17 at 10:05
  • If that's what he means, I misunderstood the question. – René Pijl Sep 23 '17 at 10:27