Search code examples
pythonansiblepickleansible-2.xansible-api

Calling a filter plugin from an action plugin


I am developing a custom Ansible action plugin. From in there I would like to calculate the gateway and subnet mask from an CIDR. This is already possible with the ipaddr filter. Instead of replicating the code, is there a way to call the ipaddr filter from inside an action plugin?

I know you can call a module from an action plugin like so:

self._execute_module(...)

Is anything like this available for filters?

I looked into the source of Ansible and found the filter_loader class but have not figured out how to use it.

from ansible.errors import AnsibleError, AnsibleFilterError
from ansible.plugins import filter_loader
...
ipaddr = filter_loader.get('ipaddr')

This results into an error, I think I can not avoid without modifications on the ipaddr filter itself, which of course is no option.

Traceback (most recent call last):
  File "/usr/lib64/python2.7/multiprocessing/queues.py", line 266, in _feed
    send(obj)
PicklingError: Can't pickle <class '/usr/lib/python2.7/site-packages/ansible/plugins/filter/ipaddr.FilterModule'>: import of module /usr/lib/python2.7/site-packages/ansible/plugins/filter/ipaddr failed

Solution

  • If you only have to use the ipaddr module, why not just import it directly?

    >>> from ansible.plugins.filter import ipaddr
    >>> dir(ipaddr)
    ['FilterModule', '_6to4_query', '__builtins__', '__doc__', '__file__', '__metaclass__', '__name__', '__package__', '_bare_query', '_bool_hwaddr_query', '_bool_ipaddr_query', '_broadcast_query', '_cidr_lookup_query', '_cidr_query', '_cisco_query', '_empty_hwaddr_query', '_empty_ipaddr_query', '_gateway_query', '_host_query', '_hostmask_query', '_int_query', '_ip_query', '_ipv4_query', '_ipv6_query', '_link_local_query', '_linux_query', '_loopback_query', '_multicast_query', '_need_netaddr', '_net_query', '_netmask_query', '_network_query', '_postgresql_query', '_prefix_query', '_private_query', '_public_query', '_revdns_query', '_size_query', '_subnet_query', '_type_query', '_unicast_query', '_unix_query', '_version_query', '_win_query', '_wrap_query', 'absolute_import', 'division', 'errors', 'hwaddr', 'ipaddr', 'ipsubnet', 'ipv4', 'ipv6', 'ipwrap', 'macaddr', 'netaddr', 'nthhost', 'partial', 'print_function', 'slaac', 'types']