Search code examples
ansibleansible-2.xansible-inventoryansible-ad-hoc

Ansible unable to access group_vars


I am not able to access my group_vars.

My current directory where i have my inventory file

[ansible@akashd1c inventory]$ pwd
/home/ansible/inventory

created group_vars directory in inventory

[ansible@akashd1c inventory]$ ls
group_vars  inventory

created labservers file inside group_vars

[ansible@akashd1c group_vars]$ vi labservers

added the variable content

[ansible@akashd1c inventory]$ cat group_vars/labservers
opt_dir: /opt

Testing using ping --- it works fine

[ansible@akashd1c inventory]$ ansible akashd2c.mylabserver.com -i inventory -m ping
 akashd2c.mylabserver.com | SUCCESS => {
"ansible_facts": {
    "discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}

Now running using variable - GETTING ERROR

[ansible@akashd1c inventory]$ ansible akashd2c.mylabserver.com -i inventory -a "ls -l {{opt_dir}}"
akashd2c.mylabserver.com | FAILED | rc=-1 >>
The task includes an option with an undefined variable. The error was: 'opt_dir' is undefined

I tried to change the ansible.cfg inventory log - still wont work.

#inventory = /home/ansible/inventory/inventory

updated file to yml file

[ansible@akashd1c group_vars]$ ls
labservers.yml
[ansible@akashd1c group_vars]$ cat labservers.yml 
 ---
 opt_dir: /opt

inventory

 [ansible@akashd1c inventory]$ cat inventory 
 akashd2c ansible_host=akashd2c.mylabserver.com
 [labserver]
 akashd2c.mylabserver.com
 akashd3c.mylabserver.com

Solution

  • Your group in your inventory is labserver, but the group_vars filename is labservers.yml, plural

    Change one or the other to match

    In the future, you can very easily use ansible-inventory -i ./inventory --list to verify what ansible sees with respect to the hosts and their resolved vars:

    $ echo 'opt_dir: /opt' > inventory/group_vars/labservers.yml
    $ ansible-inventory -i ./inventory --list
    {
        "_meta": {
            "hostvars": {
                "akashd2c": {
                    "ansible_host": "akashd2c.mylabserver.com"
                }
            }
    
    $ echo 'opt_dir: /opt' > inventory/group_vars/labserver.yml
    $ ansible-inventory -i ./inventory --list
    {
        "_meta": {
            "hostvars": {
                "akashd2c": {
                    "ansible_host": "akashd2c.mylabserver.com"
                },
                "akashd2c.mylabserver.com": {
                    "opt_dir": "/opt"