Skip to content

Commit

Permalink
Merge pull request #297 from qwestduck/296-tasks-contain-duplicated-a…
Browse files Browse the repository at this point in the history
…nd-templated-tags

Remove duplicate and templated task tags
  • Loading branch information
uk-bolly authored Sep 17, 2024
2 parents e06de6c + 006d294 commit 34db62c
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .ansible-lint
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,6 @@ skip_list:
- '602'
- '208'
use_default_rules: true
rulesdir:
- ./rules/
verbosity: 0
63 changes: 63 additions & 0 deletions rules/tag.py
Original file line number Diff line number Diff line change
@@ -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
4 changes: 2 additions & 2 deletions tasks/fix-cat2.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2733,7 +2733,6 @@
tags:
- RHEL-08-010830
- CAT2
- V-230330
- CCI-000366
- SRG-OS-000480-GPOS-00229
- SV-230330r858713_rule
Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit 34db62c

Please sign in to comment.