Ansible:如何在剧本中声明全局变量? [英] Ansible: How to declare global variable within playbook?

查看:514
本文介绍了Ansible:如何在剧本中声明全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Ansible剧本中声明全局变量.我已经在google中搜索并找到了以下解决方案,但其无法正常工作.

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

播放:每次播放并包含结构,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

因此,您在播放中声明的任何内容都只能是播放变量或(宿主)事实.

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屋!

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