Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for acceptable command options #1457

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ per-file-ignores =
test/TestBaseFormatter.py: D100 D103
test/TestBecomeUserWithoutBecome.py: PT009 D100 D101 D102
test/TestCliRolePaths.py: PT009 D100 D101 D102
test/TestCommandsInsteadOfModulesRule.py: PT009
konstruktoid marked this conversation as resolved.
Show resolved Hide resolved
test/TestCommandLineInvocationSameAsConfig.py: D100 D103
test/TestCommandHasChangesCheck.py: PT009 D100 D101 D102
test/TestComparisonToEmptyString.py: PT009 D100 D101 D102
Expand Down
11 changes: 11 additions & 0 deletions examples/playbooks/commands-instead-of-modules-failure.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
- hosts: localhost
tasks:
- name: print git log
command: git log

- name: run apt-get update
command: apt-get update

- name: restart sshd
command: systemctl restart sshd
11 changes: 11 additions & 0 deletions examples/playbooks/commands-instead-of-modules-success.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
- hosts: localhost
tasks:
- name: set systemd runlevel
command: systemctl set-default multi-user.target

- name: show systemd environment
command: systemctl show-environment

- name: print current git branch
command: git branch
17 changes: 16 additions & 1 deletion src/ansiblelint/rules/CommandsInsteadOfModulesRule.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from typing import Any, Dict, Union

from ansiblelint.rules import AnsibleLintRule
from ansiblelint.utils import convert_to_boolean, get_first_cmd_arg
from ansiblelint.utils import convert_to_boolean, get_first_cmd_arg, get_second_cmd_arg


class CommandsInsteadOfModulesRule(AnsibleLintRule):
Expand Down Expand Up @@ -59,15 +59,30 @@ class CommandsInsteadOfModulesRule(AnsibleLintRule):
'yum': 'yum',
}

_executable_options = {
'git': 'branch',
'systemctl': ['set-default', 'show-environment'],
}

def matchtask(self, task: Dict[str, Any]) -> Union[bool, str]:
if task['action']['__ansible_module__'] not in self._commands:
return False

first_cmd_arg = get_first_cmd_arg(task)
second_cmd_arg = get_second_cmd_arg(task)

if not first_cmd_arg:
return False

executable = os.path.basename(first_cmd_arg)

if (
second_cmd_arg
and executable in self._executable_options
and second_cmd_arg in self._executable_options[executable]
):
return False

if executable in self._modules and convert_to_boolean(
task['action'].get('warn', True)
):
Expand Down
11 changes: 11 additions & 0 deletions src/ansiblelint/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,17 @@ def get_first_cmd_arg(task: Dict[str, Any]) -> Any:
return first_cmd_arg


def get_second_cmd_arg(task: Dict[str, Any]) -> Any:
try:
if 'cmd' in task['action']:
second_cmd_arg = task['action']['cmd'].split()[1]
else:
second_cmd_arg = task['action']['__ansible_arguments__'][1]
except IndexError:
return None
return second_cmd_arg


def is_playbook(filename: str) -> bool:
"""
Check if the file is a playbook.
Expand Down
30 changes: 30 additions & 0 deletions test/TestCommandsInsteadOfModulesRule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# pylint: disable=preferred-module # FIXME: remove once migrated per GH-725
"""command-instead-of-module rule testing."""
import unittest

from ansiblelint.rules import RulesCollection
from ansiblelint.rules.CommandsInsteadOfModulesRule import CommandsInsteadOfModulesRule
from ansiblelint.runner import Runner


class TestCommandsInsteadOfModulesRule(unittest.TestCase):
"""Unit test for command-instead-of-module rule."""

collection = RulesCollection()

def setUp(self):
"""Register rule."""
self.collection.register(CommandsInsteadOfModulesRule())

def test_file_positive(self):
"""Run tasks that should be successful."""
success = 'examples/playbooks/commands-instead-of-modules-success.yml'
good_runner = Runner(success, rules=self.collection)
self.assertEqual([], good_runner.run())

def test_file_negative(self):
"""Run tasks that should fail."""
failure = 'examples/playbooks/commands-instead-of-modules-failure.yml'
bad_runner = Runner(failure, rules=self.collection)
errs = bad_runner.run()
self.assertEqual(3, len(errs))
konstruktoid marked this conversation as resolved.
Show resolved Hide resolved