Parsing vCenter Folders into Ansible groups in dynamic inventory

SadDev
Mon, 22 Sep 2025 16:40:51 +0000
Get Help

Is there a way to do this? I feel like there must be. I’ve tried scouring the internet and couldn’t actually find much about this. My EE is python 3.12, Ansible 10, jina 3.1.5, ansible-inventory core 2.17.8
Is there any more info I can grab that might be helpful?

We have our VMs organized by their folder structure in vCenter, and I’m wanting to carry that over as groups in Ansible.

I’m trying to use

docs.ansible.com

community.vmware.vmware_vm_inventory inventory – VMware Guest inventory source...

to make a dynamic inventory in ansible. Most importantly, I want my VM’s folder path to be parsed into a flat group structure. I’ve using with_path: true

I have got very close using this, but it’s creating a group like datacenter_VM_OU1_Dev_OU2 instead of several groups.
ie

vm1 at Site/ou1/windows/prod/ou2/vm1
creates
Site/ou1/windows/prod/ou2/
or I can get it to create that + the vm1 as it's own group which seems like a proof of concept, that I'm able to extract at least some of the string and make a group from it.

Can I have the inventory source parse that when it runs to make a flat group structure for each vm?

Ie
Vm1 in groups
Site
Ou1
Windows
Prod
Ou2

Based entirely off parsing that path?
One of my recent attempts

---
hostnames:
  - name
  - guest.hostName
  - guest.ipAddress

strict: false
validate_certs: false
with_path: true

# Properties to gather from vCenter
properties:
  - name
  - guest.guestId
  - runtime.powerState
  - config.template

# Filter out templates
filters:
  - config.template == False

# Create groups based on various properties
keyed_groups:
  # Try splitting by underscores first (remove Datacenters_ prefix)
  - key: name | regex_replace('^Datacenters_', '') | regex_replace('_', '/')
    separator: '/'
    prefix: ''

  # Also try splitting by forward slashes in case that's the format
  - key: name | regex_replace('^Datacenters/', '')
    separator: '/'
    prefix: ''

  # Group by power state
  - key: runtime.powerState
    prefix: power

  # Group by OS using guestId
  - key: guest.guestId
    prefix: os
    default_value: unknown

# Create additional groups based on composed variables
groups:
  # Simple OS grouping
  windows: os_simple == 'windows'
  linux: os_simple in ['rhel', 'ubuntu', 'centos', 'debian', 'sles']

  # Power state groups
  powered_on: runtime.powerState == 'poweredOn'
  powered_off: runtime.powerState == 'poweredOff'

7 posts - 4 participants