问题描述
我有一个包含多个主机部分的剧本.我想在这个 playbook.yml 文件中定义一个仅适用于该文件的变量,例如:
I have a playbook with multiple hosts section. I would like to define a variable in this playbook.yml file that applies only within the file, for example:
vars:
my_global_var: 'hello'
- hosts: db
tasks:
-shell: echo {{my_global_var}}
- hosts: web
tasks:
-shell: echo {{my_global_var}}
上面的例子不起作用.我必须为每个主机部分复制变量(坏)或在更高级别定义它,例如在我的 group_vars/all
(不是我想要的,但有效).我也知道可以包含变量文件,但这会影响可读性.有什么建议可以让它在正确的范围内(例如剧本文件本身)?
The example above does not work. I have to either duplicate the variable for each host section (bad) or define it at higher level, for example in my group_vars/all
(not what I want, but works). I am also aware that variables files can be included, but this affects readibility. Any suggestion to get it in the right scope (e.g the playbook file itself)?
推荐答案
如果 group_vars 不适合您的需要,set_fact
模块将完成此任务.
The set_fact
module will accomplish this if group_vars don't suit your needs.
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/set_fact_module.html
这个模块允许设置新的变量.变量是在逐个主机 > 的基础上设置的,就像设置模块发现的事实一样.在 Ansible 运行期间,这些变量将在两次播放之间继续存在,但即使您使用事实缓存,也不会在执行期间保存.
- hosts: db:web
tasks:
- set_fact: my_global_var='hello'
- hosts: db
tasks:
-shell: echo {{my_global_var}}
- hosts: web
tasks:
-shell: echo {{my_global_var}}
这篇关于Ansible 剧本范围的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!