Skip to content

Commit

Permalink
Auto-detect modules from collection layouts
Browse files Browse the repository at this point in the history
Makes local modules available to ansible when the plugins/modules exists
on disk but only if the user did not already define ANSIBLE_LIBRARY.

This means that from now on users are not forced to use use the old
hack of defining ANSIBLE_LIBRARY=plugins/modules before running the
linter, something that made it harder to use with pre-commit, tox, CI.

If the variable is already defined or the folder does not exist,
nothing is done.

Fixes: #778
  • Loading branch information
ssbarnea committed Jan 11, 2021
1 parent 1d6a24c commit 3f088b8
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 0 deletions.
5 changes: 5 additions & 0 deletions examples/playbooks/custom_module.yml
@@ -0,0 +1,5 @@
- hosts: localhost
gather_facts: false
tasks:
- name: Run custom module
fake_module: {}
9 changes: 9 additions & 0 deletions lib/ansiblelint/_prerun.py
@@ -1,3 +1,4 @@
import os
import sys

from packaging import version
Expand Down Expand Up @@ -28,4 +29,12 @@ def check_ansible_presence() -> None:
sys.exit(ANSIBLE_MISSING_RC)


def prepare_environment() -> None:
"""Make custom modules available if needed."""
if os.path.exists("plugins/modules") and 'ANSIBLE_LIBRARY' not in os.environ:
os.environ['ANSIBLE_LIBRARY'] = "plugins/modules"
print("Added ANSIBLE_LIBRARY=plugins/modules", file=sys.stderr)


check_ansible_presence()
prepare_environment()
16 changes: 16 additions & 0 deletions plugins/modules/fake_module.py
@@ -0,0 +1,16 @@
"""Sample custom ansible module named fake_module.
This is used to test ability to detect and use custom modules.
"""
from ansible.module_utils.basic import AnsibleModule


def main():
"""Return the module instance."""
return AnsibleModule(
argument_spec=dict(
data=dict(default=None),
path=dict(default=None, type=str),
file=dict(default=None, type=str),
)
)
3 changes: 3 additions & 0 deletions test-requirements.txt
Expand Up @@ -9,7 +9,9 @@ attrs==20.3.0
colorama==0.4.4
commonmark==0.9.1
coverage==5.3.1
dataclasses==0.8
execnet==1.7.1
importlib-metadata==3.4.0
iniconfig==1.1.1
packaging==20.4
pluggy==0.13.1
Expand All @@ -25,6 +27,7 @@ rich==9.5.1
six==1.15.0
toml==0.10.2
typing-extensions==3.7.4.3
zipp==3.4.0

# The following packages are considered to be unsafe in a requirements file:
# setuptools
8 changes: 8 additions & 0 deletions test/TestExamples.py
Expand Up @@ -14,3 +14,11 @@ def test_example_plain_string(default_rules_collection):
assert len(result) == 1
assert result[0].rule.id == "911"
assert "A playbook must be a list of plays" in result[0].message


def test_example_custom_module(default_rules_collection):
"""custom_module.yml is expected to pass."""
result = Runner(
default_rules_collection,
'examples/playbooks/custom_module.yml', [], [], []).run()
assert len(result) == 0

0 comments on commit 3f088b8

Please sign in to comment.