Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

ansible: multiple var files for roles?

In all ansible docs I have found, the [role]/vars/main.yml file is referenced as the place for role variables.

There is some customization possible by using [role]/defaults/main.yml which then can be overwritten by [role]/vars/main.yml.

What if I'd want to address a multitude of scenarios, and say load a group of vars based on a main variable, and then place the grouped vars in each file like

[role]/vars/main.yml
[role]/vars/scenario1.yml
[role]/vars/scenario2.yml
[role]/vars/scenario3.yml
[role]/vars/scenario4.yml

In other words, is there any use for the [role]/vars directory to contain more than just the main.yml file?

The concrete challenge is, define sets of users with their public keys, so depending on which machine I am, create the appropriate user accounts


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The role of vars/main.yml is not really to overwrite variables defined in defaults/main.yml. In fact that would actually be counter-productive as variables defined in vars/main.yml have a quite high precedence level and are harder to override while you usually want vars in defaults/main.yml to be easilly modified by a user.

Regarding the vars folder, it contains by convention files defining variables that are specific to your role. But only vars/main.yml will be loaded by default.

Meanwhile that folder (like the vars folder adjacent to your playbook if you have one) is on the search path when you include_vars from your role. So if I take your example, you can easilly include_vars: scenario1.yml somewhere in you role or even include_vars: "scenario{{ scenario_number }}.yml" if you get that dynamically.

Disclaimer: I am the maintainer of the role taken as example below

Here is a real life example taken from ansible-thoteam/nexus-oss role.

As you can see, this role has a vars folder with several files but no default.yml. So no role variables are loaded by default. Those files are loaded dynamically when needed.

There are 2 files related to different OS famillies supported by the role: configure-Debian.yml and configure-RedHat.yml. They are loaded as needed in tasks/main.yml with the following task:

- name: Include OS specific variables.
  include_vars: "configure-{{ ansible_os_family }}.yml"

Alternatively, you can have a look at the first_found lookup which can also be used for this kind of scenario.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...