Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: How to declare global variable within 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

When I'm trying the above code, it says variable prod-servers is undefined.

like image 302
Shibankar Avatar asked Nov 20 '17 13:11

Shibankar


1 Answers

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

  • define an in-memory inventory and run the subsequent play against that inventory.
like image 159
techraf Avatar answered Nov 24 '22 07:11

techraf