1

Im trying to build a very simple plugin filter within a role. However, when I go to test the plugin it doesnt detect it. Ansible version is 2.9.

dir

(base) root@8c08139d265e:/workspace# tree
.
├── Dockerfile
├── Makefile
├── README.md
├── defaults
│   └── main.yml
├── filter_plugins
│   ├── __init__.py
│   └── sample_filter.py
├── handlers
│   └── main.yml
├── meta
│   └── main.yml
├── requirements.txt
├── tasks
│   └── main.yml
├── tests
│   ├── inventory
│   └── test.yml
└── vars
    └── main.yml

Plugin

(base) root@8c08139d265e:/workspace# cat filter_plugins/sample_filter.py 
class FilterModule(object):
    def filters(self):
        return {'cloud_truth': cloud_truth}

def cloud_truth(a):
    print(type(a))
    return a.replace("the cloud", "somebody else's computer")

test

(base) root@8c08139d265e:/workspace# cat tests/test.yml 
---
- name: test cloud_truth filter
  hosts: localhost
  roles:
    - .

  vars:
    statement: "I store my files in the cloud"

  tasks:
  - name: make a statement
    debug:
      msg: "{{ statement | cloud_truth }}"

error

TASK [make a statement] *****************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "template error while templating string: no filter named 'cloud_truth'. String: {{ statement | cloud_truth }}"}

Thanks,

felix001
  • 15,341
  • 32
  • 94
  • 121

2 Answers2

0

Managed to resolve this by installing itself as a role. Like so:

ansible-galaxy install git+git@github.com:<user>/ansible-role-networking.git

Then add the role within test.yml.

felix001
  • 15,341
  • 32
  • 94
  • 121
-1

The problem seems to be related to where the filter plugin is in relation to your playbook.

In order for your playbook to work, the filter_plugins folder needs to be inside the tests folder:

.
└── tests
    ├── filter_plugins
    │   ├── __init__.py
    │   └── sample_filter.py
    └── test.yml

However, this then causes the problem that the filter is no longer available to other tasks. The alternative would be to perhaps use roles and a structure like this:

.
├── filter_plugins
│   ├── __init__.py
│   └── sample_filter.py
├── playbook.yml
└── roles
    └── tests
        └── tasks
            └── main.yml

But of course, this depends on the framework you're trying to build.

user7440787
  • 831
  • 7
  • 22
  • I've encountered the same problem and trying to call the filter from a role, but placing the `filter_plugins` directory neither to the root directory of the playbook nor to the role's root directory won't help. Still banging my head to understand what's wrong. :-) – Volodymyr Melnyk Mar 30 '23 at 11:52
  • My problem was conditioned by my inattentiveness. The module had an error and I didn't notice the `[WARNING]: Skipping plugin` line in the Ansible output. – Volodymyr Melnyk Mar 30 '23 at 12:20