ansiblejinja2ansible-inventorynmap

Dynamic inventory groups from ansible plugin: nmap


I'm trying to use the nmap plugin in ansible to create a dynamic inventory, and then group things that the plugin returns. Unfortunately, I'm missing something, because I can't seem to get a group to be created.
In this scenario, I have a couple hosts named unknownxxxxxxxx that I would like to group.

plugin: nmap
strict: false
address: 10.0.1.0/24   
ports: no
groups:
  unknown: "'unknown' in hostname"

I run my plugin - ansible-inventory -i nmap.yml --export --output=inv --list

but the return is always the same...

By now, I've resorted to guessing possible var names

host, hosts, hostnames, hostname, inventory_hostname, hostvars, host.fqdn, and the list goes on and on...

I'm obviously missing something basic, but I can't seem to find anything via search that has yielded any results.

Can someone help me understand what I'm doing wrong with jinja?

Perhaps I need to use compose: and keyed_groups: ?


Solution

  • I'm obviously missing something basic...

    I'm not sure that you are. I agree that according to the documentation the nmap plugin is supposed to work the way you're trying to use it, but like you I'm not able to get the groups or compose keys to work as described.

    Fortunately, we can work around that problem by directly using the constructed inventory plugin.

    We'll need to use an inventory directory, rather than an inventory file, since we need multiple inventory files. We'll put the following into our ansible.cfg:

    [defaults]
    inventory = inventory
    

    And then we'll create a directory inventory, into which we'll place two files. First, we'll put your nmap inventory in inventory/10nmap.yml. It will look like this:

    plugin: nmap
    strict: false
    address: 10.0.1.0/24   
    ports: false
    

    And then we'll put the configuration for the constructed plugin to inventory/20constructed.yml:

    plugin: constructed
    strict: False
    
    groups:
      unknown: "'unknown' in inventory_hostname"
    

    We've named the file 10nmap.yml and 20constructed.yml because we need to ensure that the constructed plugin runs after the nmap plugin (also, we're checking against inventory_hostname here because that's the canonical name of a host in your Ansible inventory).


    With all this in place, you should see the behavior you're looking for: hosts with unknown in the inventory_hostname variable will end up in the unknown group.