Ansible:如何在剧本中声明全局变量? [英] Ansible: How to declare global variable within playbook?
问题描述
如何在 Ansible playbook 中声明全局变量.我在谷歌搜索并找到了以下解决方案,但没有按预期工作.
How can I declare global variable within Ansible playbook. I have searched in google and found the below solution, but its not working as expected.
- hosts: all
vars:
prod-servers:
- x.x.x.x
- x.x.x.x
- hosts: "{{prod-servers}}"
tasks:
- name: ping
action: ping
当我尝试上述代码时,它说变量 prod-servers
未定义.
When I'm trying the above code, it says variable prod-servers
is undefined.
推荐答案
您不能定义一个可在剧本级别(全局变量)从剧本中访问的变量.
You cannot define a variable accessible on a playbook level (global variable) from within a play.
Ansible 有 3 个主要范围:
Ansible has 3 main scopes:
全局:这是由配置、环境变量和命令行设置的
Global: this is set by config, environment variables and the command line
Play:每个 play 和包含的结构、vars 条目(vars;vars_files;vars_prompt)、角色默认值和 vars.
Play: each play and contained structures, vars entries (vars; vars_files; vars_prompt), role defaults and vars.
主机:与主机直接关联的变量,如库存、include_vars、事实或注册的任务输出
Host: variables directly associated to a host, like inventory, include_vars, facts or registered task outputs
因此,您在 play 中声明的任何内容都只能是 play 变量或(主机)事实.
Anything you declare inside a play can thus only be either a play variable, or a (host) fact.
定义一个变量,你可以在hosts
声明中使用它:
To define a variable, which you can use in the hosts
declaration:
- 使用
--extra-vars
选项运行ansible-playbook
并在参数中传递值;
- run
ansible-playbook
with--extra-vars
option and pass the value in the argument;
或实现相同的功能(决定在哪个主机上运行一个游戏,从前一个游戏中):
or to achieve the same functionality (decide which hosts to run a play on, from within a preceding play):
- 定义一个内存清单并针对该清单运行后续游戏.
- define an in-memory inventory and run the subsequent play against that inventory.
这篇关于Ansible:如何在剧本中声明全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!