在具有操作系统特定默认值的角色中定义Ansible变量,该默认值可以轻松重写
我正在编写一个Ansible角色,它可以在不同的Linux操作系统系列上使用,并且每个操作系统系列的变量具有不同的默认值 起初,我认为在角色中使用include vars任务可以很容易地进行设置,例如:在具有操作系统特定默认值的角色中定义Ansible变量,该默认值可以轻松重写,ansible,ansible-role,Ansible,Ansible Role,我正在编写一个Ansible角色,它可以在不同的Linux操作系统系列上使用,并且每个操作系统系列的变量具有不同的默认值 起初,我认为在角色中使用include vars任务可以很容易地进行设置,例如: - name: Gather OS family variables include_vars: "{{ ansible_os_family|lower }}.yml" 与 在myrole/vars/redhat.yml my_role_variable: "Here is the def
- name: Gather OS family variables
include_vars: "{{ ansible_os_family|lower }}.yml"
与
在myrole/vars/redhat.yml
my_role_variable: "Here is the default for Debian Linux"
在myrole/vars/debian.yml
my_role_variable: "Here is the default for Debian Linux"
但是,在我的例子中,使用角色的剧本能够轻松覆盖默认值是非常重要的
因此,我试图找到一种方法,为每个OS系列的变量设置不同的默认值,如上所述,但我希望变量是角色默认变量,而不是角色包含变量。有办法做到这一点吗?使用:
这样,如果定义了变量override\u os\u family
,则表达式将有其值,否则,它将使用ansible\u os\u family
的值
例如:
---
- 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"
结果(摘录):
在defaults/main.yml文件中包含如下内容怎么样
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) }}"
...
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "darwin.yml"
}
...
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "lamarck.yml"
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) }}"