Ansible Dynamic Inventory for Proxmox

I’ve been playing with Ansible lately as part of my RHCA studies, and found a nice way of using dynamic inventory to manage my Proxmox homelab.

Installation

On the Ansible control node, change to the folder where playbooks are stored:

$ cd /home/ansible/playbooks

Download the script:

$ wget https://raw.githubusercontent.com/ansible/ansible/devel/contrib/inventory/proxmox.py

Make it executable:

$ chmod 0755 ./proxmox.py

Configuration

Try listing dynamic inventory:

$ ./proxmox.py \
  --url=https://pve.lisenet.com:8006/ \
  [email protected] \
  --password=changeme \
  --list --pretty
{
  "all": {
    "hosts": [
      "ansible5.hl.local", 
      "proxy1.hl.local", 
      "ansible2.hl.local", 
      "rhel70-tmpl", 
      "monitoring.hl.local", 
      "storage1.hl.local", 
      "admin2.hl.local", 
      "katello.hl.local", 
      "db1.hl.local", 
      "web2.hl.local", 
      "proxy2.hl.local", 
      "ansible3.hl.local", 
      "db2.hl.local", 
      "ldap2.hl.local", 
      "syslog.hl.local", 
      "admin1.hl.local", 
      "web1.hl.local", 
      "ansible4.hl.local", 
      "ldap1.hl.local", 
      "ansible1.hl.local", 
      "backup.hl.local", 
      "storage2.hl.local"
    ]
  },
[...]

Create a file setenv.sh with environment variables to store Proxmox credentials:

#!/bin/bash
export PROXMOX_URL=https://pve.lisenet.com:8006/
export [email protected]
export PROXMOX_PASSWORD=changeme

Execute commands from filename in the current shell environment:

$ source ./setenv.sh

List dynamic inventory without passing credentials on the CLI:

$ ./proxmox.py --list --pretty

Use inventory with Ansible:

$ ansible all -i ./proxmox.py -m ping -u ansible
ansible5.hl.local | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
proxy1.hl.local | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[...]

Leave a Reply

Your email address will not be published. Required fields are marked *