Ansible - Variables in /etc/ansible/hosts or your own inventory file

Variables can be created in the default hosts file or your own inventory file. In this example, two variables are defined, foo and bar, using the INI file format.

[all]
server1.example.com
server2.example.com

[all:vars]
foo=Hello
bar=World

 

In this example, two variables are defined, foo and bar, using the YAML file format.

all:
  hosts:
    server1.example.com:
    server2.example.com:
  vars:
    foo: Hello
    bar: World

 

In a playbook, the debug module can be used to print each variable.

---
- hosts: all
  tasks:
    - debug:
        var: foo

    - debug:
        var: bar

 

Something like this should be returned.

TASK [debug]
ok: [server1.example.com] => {
    "foo": "Hello"
}

TASK [debug]
ok: [server1.example.com] => {
    "bar": "World"
}

 

 


Unique variables for different groups of managed nodes

Unique variables for different groups of managed nodes can be created in your default hosts file or your own inventory file. Or, unique variables for different groups of managed nodes can be created in the group_vars directory.

In this example, when running a task on server1.example.com the foo variable will contain a value of "Hello" and when run on server2.example the foo variable will have a value of "World", using the INI file format

server1.example.com foo=Hello
server2.example.com foo=World

 

In this example, two variables are defined, foo and bar, using the YAML file format. In this example, the foo variable would only be defined for the "linux" managed nodes and the bar variable would only be defined for the "windows" managed nodes.

all:
  hosts:
    server1.example.com:
    server2.example.com:
  children:
    linux:
      hosts:
        server3.example.com:
        server4.example.com:
      vars:
        foo: Hello
    windows:
      hosts:
        server5.example.com:
        server6.example.com:
      vars:
        bar: World

 

In this example, when using the "linux" hosts, you can access the "foo" variable.

---
- hosts: linux
  tasks:
    - debug:
        var: foo

 

Something like this should be returned.

TASK [debug]
ok: [server1.example.com] => {
    "foo": "Hello"
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 8d229 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |