Ansible 剧本范围的变量 [英] Ansible playbook-wide variable

查看:29
本文介绍了Ansible 剧本范围的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个主机部分的剧本.我想在这个 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 运行期间,这些变量将在两次播放之间继续存在,但即使您使用事实缓存,也不会在执行期间保存.

This module allows setting new variables. Variables are set on a host-by-host >basis just like facts discovered by the setup module. These variables will >survive between plays during an Ansible run, but will not be saved across >executions even if you use a fact cache.

- 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 剧本范围的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆