Bootstrap FreeKB - Ansible - Create variables in /etc/ansible/hosts or your own inventory file
Ansible - Create variables in /etc/ansible/hosts or your own inventory file

Updated:   |  Ansible articles

Following are the differet ways that variables can be set in Ansible. This list is in the order of precedence, where the option higher in the list takes precedence over options lower in the list.

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"
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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