Ansible: How to declare global variable within playbook?

女生的网名这么多〃 提交于 2019-12-05 04:26:43

You cannot define a variable accessible on a playbook level (global variable) from within a play.

Variable Scopes

Ansible has 3 main scopes:

  • Global: this is set by config, environment variables and the command line

  • Play: each play and contained structures, vars entries (vars; vars_files; vars_prompt), role defaults and 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.


To define a variable, which you can use in the hosts declaration:

  • 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):

what you seem to want is an inventory (http://docs.ansible.com/ansible/latest/intro_inventory.html), it looks like you have an static list of IP's that may be prod servers (or dev, or whatever), therefore you can create an static inventory.

In your second play you want to use the list of IP's as hosts to run the tasks, that's not what Ansible expects. After the "hosts" keyword in a play declaration, Ansible expects a group name from the inventory.

If, on the opossite, your prod servers change from time to time, you may need to create a dynamic inventory. You can have a look at examples in https://github.com/ansible/ansible/tree/devel/contrib/inventory (for instance, there are examples of dynamic inventory based on EC2 from Amazon or vsphere)

regards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!