Exercise 06 — Dynamic Inventory

Ansible for Proxmox VE · Module 06

Author

credativ GmbH

~8 min · in ~/ansible-proxmox · needs exercise 05: web01 and the API token

Objective: stop maintaining a list of guests. Ask the cluster instead.

NoteWhere to look

Everything here was on the slides; the handout has every option of the plugin. Inventory plugin · Dynamic inventory · ansible-inventory · offline: ansible-doc -t inventory community.proxmox.proxmox

inventory/lab.proxmox.yml is already in the project, configured except for task 3.

1 — Hand the plugin the token

Module 05 wrote the secret to ~/pve-token.json, once, at creation:

export PVE_TOKEN_SECRET=$(jq -r .ansible ~/pve-token.json)

Done when: echo ${#PVE_TOKEN_SECRET} prints 36.

An environment variable is fine for a workshop shell. In a pipeline the secret belongs in Ansible Vault or your CI secret store.

2 — Ask the cluster

ansible-inventory -i inventory/lab.proxmox.yml --graph
ansible-inventory -i inventory/lab.proxmox.yml --host web01

Done when: the graph has proxmox_nodes with your three nodes and proxmox_all_qemu with web01, and the host output shows the guest’s own configuration — proxmox_ciuser: student, proxmox_ipconfig0 with the address you set in module 05. Nobody typed any of that into an inventory file.

A 401 here means the token does not match the cluster — most often the secret was never exported, or module 05 ran against a different cluster. The file name matters too: it must end in .proxmox.yml, otherwise the plugin ignores it silently and you get an empty inventory with no error at all.

3 — Let a tag decide the group

In the GUI, open web01 and add the tag web (Options → Tags). Then uncomment the last block of inventory/lab.proxmox.yml and run the graph again.

Done when: the groups tagweb and webservers exist and contain web01.

The person creating the VM decided which group it belongs to, in the GUI, and your playbooks follow.

4 — Both inventories at once

ansible-inventory -i inventory/hosts.yml -i inventory/lab.proxmox.yml --graph

Done when: your static groups (pve, pve_primary, pve_secondary) and the generated ones appear in the same tree. The nodes stay static — they have to exist before anything can be dynamic.

If you finish early

  • Create a second VM in the GUI, re-run the graph, and watch it appear without you touching a file.
  • Stop web01 and watch it move from proxmox_all_running to proxmox_all_stopped.
  • Put inventory = inventory/hosts.yml,inventory/lab.proxmox.yml in ansible.cfg so both sources are used by default.
  • Restrict the token to PVEAuditor and check that listing still works while creating a VM no longer does.

Solutions

Solutions are discussed live with the trainer.