From 006d294453c9e905e9fe3ca1e5364902c5b14079 Mon Sep 17 00:00:00 2001 From: William Panlener Date: Sun, 18 Aug 2024 17:48:39 -0500 Subject: [PATCH] Remove duplicate and templated task tags Signed-off-by: William Panlener --- .ansible-lint | 2 ++ rules/tag.py | 63 ++++++++++++++++++++++++++++++++++++++++++++++ tasks/fix-cat2.yml | 4 +-- 3 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 rules/tag.py diff --git a/.ansible-lint b/.ansible-lint index b717f678..44e65894 100644 --- a/.ansible-lint +++ b/.ansible-lint @@ -19,4 +19,6 @@ skip_list: - '602' - '208' use_default_rules: true +rulesdir: + - ./rules/ verbosity: 0 diff --git a/rules/tag.py b/rules/tag.py new file mode 100644 index 00000000..1208011d --- /dev/null +++ b/rules/tag.py @@ -0,0 +1,63 @@ +"""Implementation of TagRule.""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING + +from ansiblelint.constants import LINE_NUMBER_KEY +from ansiblelint.file_utils import Lintable +from ansiblelint.rules import AnsibleLintRule, TransformMixin + +if TYPE_CHECKING: + from ansiblelint.errors import MatchError + from ansiblelint.utils import Task + + +class TagRule(AnsibleLintRule, TransformMixin): + """Rule for checking task tags.""" + + id = "tag" + description = ( + "All task tags should have distinct names" + "and templates in tags should be avoided." + ) + severity = "MEDIUM" + tags = ["idiom"] + _re_templated = re.compile(r"^.*\{\{.*\}\}.*$") + _ids = { + "tag[no-duplicate]": "Tasks should not duplicate tags.", + "tag[no-template]": "Tasks should not use Jinja templates in tags.", + } + + def matchtask( + self, + task: Task, + file: Lintable | None = None, + ) -> list[MatchError]: + results: list[MatchError] = [] + if file and file.failed(): + return results + tags = task.get("tags") + if tags: + if len(tags) != len(set(tags)): + results.append( + self.create_matcherror( + message="Tasks should not duplicate tags.", + lineno=task[LINE_NUMBER_KEY], + tag="tag[no-duplicate]", + filename=file, + ), + ) + for tag in tags: + if self._re_templated.match(tag): + results.append( + self.create_matcherror( + message="Tasks should not use Jinja templates in tags.", + lineno=task[LINE_NUMBER_KEY], + tag="tag[no-template]", + filename=file, + ), + ) + break + return results diff --git a/tasks/fix-cat2.yml b/tasks/fix-cat2.yml index ec4bce82..089e8129 100644 --- a/tasks/fix-cat2.yml +++ b/tasks/fix-cat2.yml @@ -2733,7 +2733,6 @@ tags: - RHEL-08-010830 - CAT2 - - V-230330 - CCI-000366 - SRG-OS-000480-GPOS-00229 - SV-230330r858713_rule @@ -5973,7 +5972,8 @@ - SV-230505r744020_rule - V-230505 - firewall - - "{{ rhel8stig_firewall_service }}" + - iptables + - firewalld - name: "MEDIUM | RHEL-08-040101 | PATCH | A firewall must be active on RHEL 8" block: