Custom filter plugin - how to throw an error

I’m trying to write a custom filter plugin, and I need it to throw an error. What I have so far …

  • filter_plugins/custom.py

    #!/usr/bin/python
    
    class FilterModule( object ) :
        def filters( self ) :
            return { 'custom' : self._custom }
    
        def _custom( self , input : str ) :
            if not input.startswith( '/' ) :
                raise AnsibleError( "input must start with '/'" )
    
  • doit.yml (playbook)

    ---
    - name          : Testing custom filter
      hosts         : localhost
      become        : false
      gather_facts  : false
      tasks         :
        - name : do the thing
          ansible.builtin.debug :
            msg : "{{ 'x' | custom }}"
    
  • Output

    TASK [fail] *******************************************************************
    An exception occurred during task execution. To see the full traceback, use -vvv. The error was: NameError: name 'AnsibleError' is not defined
    fatal: [localhost]: FAILED! => {}
    

I suspect I need to import something at the top of the Python file, but … I’ll be honest, today was the first day I’ve ever tried to write anything in Python, and all of the documentation I’ve found about this, seems to assume that the reader is already familiar with the language, and with enough of Ansible’s internals that they already know whatever it is I’m missing here.

You can find all ansible specific error classes at ansible/lib/ansible/errors/__init__.py at devel · ansible/ansible · GitHub

You probably want to use AnsibleFilterError since it’s a custom filter plugin:

from ansible.errors import AnsibleFilterError
...
raise AnsibleFilterError(...)

Hope that helps!

Updated the plugin …

#!/usr/bin/python

from ansible.errors import AnsibleFilterError

class FilterModule( object ) :
    def filters( self ) :
        return { 'custom' : self._custom }

    def _custom( self , input : str ) :
        if not input.startswith( '/' ) :
            raise AnsibleFilterError( "input must start with '/'" )

And now the output is …

TASK [fail] ********************************************************
fatal: [localhost]: FAILED! => {"msg": "input must start with '/'"}

Thank you VERY much!

Hopefully next week I’ll have some time to start getting familiar with Python itself, so I’m better able to read what I’m finding on Github, and so I know what an __init__.py file is for in the first place.

Have a good weekend!

No worries. Happy to help!