问题
I'm writing an Ansible role that is usable on different Linux OS families and has a different default value for variables per OS family.
At first, I thought this would be easy to set up using an include vars task in the role, such as:
- name: Gather OS family variables
include_vars: "{{ ansible_os_family|lower }}.yml"
with
my_role_variable: "Here is the default for Enterprise Linux"
in myrole/vars/redhat.yml
my_role_variable: "Here is the default for Debian Linux"
in myrole/vars/debian.yml
However, in my case it's very important that a playbook using the role be able to easily override the default values.
So, I'm trying to figure out a way to set up a different default value for the variable per OS family as described above, but I want the variables be role default vars instead of role include vars. Is there a way to do this?
回答1:
Use a ternary operator:
- name: Gather OS family variables
include_vars: "{{ (override_os_family is defined) | ternary(override_os_family,ansible_os_family) | lower }}.yml"
This way, if the variable override_os_family
is defined, your expression will have its value, if not, it will use the value of ansible_os_family
.
Example:
---
- hosts: localhost
connection: local
tasks:
- debug: msg="{{ (override_os_family is defined) | ternary(override_os_family,ansible_os_family) | lower }}.yml"
- hosts: localhost
connection: local
vars:
override_os_family: Lamarck
tasks:
- debug: msg="{{ (override_os_family is defined) | ternary(override_os_family,ansible_os_family) | lower }}.yml"
Result (excerpt):
...
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "darwin.yml"
}
...
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "lamarck.yml"
回答2:
what about having something like the following in your defaults/main.yml file
my_role_variable_default: "global default"
my_role_variable_redhat: "redhat specific default"
my_role_variable: "{{ lookup('vars', 'my_role_variable_'+ansible_os_family|lower, default=my_role_variable_default) }}"
来源:https://stackoverflow.com/questions/41189336/define-ansible-variable-in-a-role-with-os-specific-default-which-can-be-easily-o