How to set an Ansible variable depending on hostname

ansible

If I run ansible-playbook playbooks/snapshot.yml -l my.host.net I want to reference a VMID variable which is pre-set to this hosts virtual machine ID (4321 for instance).

I've found a question that should have answered this, however when I add my.host.net.yml(below) to a host_vars directory under my project, I get the error ...'VMID' is undefined when running the playbook. Either ansible isn't automatically reading host_vars/my.host.net.yml or I've got something messed.

---
- hosts: all
  gather_facts: false
  tasks:

  - name: print a host variable
    debug:
      msg: "hostvar VMID is {{ VMID }}"

host_vars/my.host.net.yml

---
VMID: 4321

Update – Added directory structure:

ansible
├── ansible.cfg
├── group_vars
├── host_vars
│   └── my.host.net.yml
├── inventories
├── playbooks
│   └── snapshot.yml
├── roles
└── tests

Best Answer

For anyone else running across this, I ended up putting symlinks in my playbooks directory. I didn't realize when setting up ansible that putting playbooks in a different directory would cause these issues. I sure don't want hundreds of playbooks cluttering the ansible root however so this works. I could do the same with group_vars as it's in my playbooks as vars_files: ../group_vars/ but for now that seems OK.

ansible
├── ansible.cfg
├── group_vars
├── host_vars
│   └── my.host.net.yml
├── inventories
├── templates
├── playbooks
│   ├── snapshot.yml
│   ├── templates -> ../templates 
|   └── host_vars -> ../host_vars
├── roles
└── tests