Ansible: How to declare global variable within playbook?
Asked Answered
R

3

14

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.

Retrace answered 20/11, 2017 at 13:4 Comment(0)
A
19

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

Aspectual answered 20/11, 2017 at 13:28 Comment(0)
G
0

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

Garrow answered 20/11, 2017 at 18:20 Comment(0)
B
-1

well, this can be done using

set_fact.

I don't know the best practice for this but this works for me

Here's my playbook example

- hosts: all
  gather_facts: false
  tasks:
   - set_fact: host='hostname'

- hosts: host-name1
  gather_facts: false
  tasks:
    - name: CheckHostName
      shell: "{{ host }}"
      register: output
    - debug: msg="{{ output }}"

- hosts: host-name2
  gather_facts: false
  tasks:
    - name: CheckHostName
      shell: "{{ host }}"
      register: output
    - debug: msg="{{ output }}"
Batish answered 14/7, 2022 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.