File: NoFormattingInWhenRule.py

package info (click to toggle)
ansible-lint 4.1.0%2Bdfsg.1-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,096 kB
  • sloc: python: 3,373; sh: 4; makefile: 2
file content (39 lines) | stat: -rw-r--r-- 1,305 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from ansiblelint import AnsibleLintRule
try:
    from types import StringTypes
except ImportError:
    # Python3 removed types.StringTypes
    StringTypes = str,


class NoFormattingInWhenRule(AnsibleLintRule):
    id = '102'
    shortdesc = 'No Jinja2 in when'
    description = '``when`` lines should not include Jinja2 variables'
    severity = 'HIGH'
    tags = ['deprecated', 'ANSIBLE0019']
    version_added = 'historic'

    def _is_valid(self, when):
        if not isinstance(when, StringTypes):
            return True
        return when.find('{{') == -1 and when.find('}}') == -1

    def matchplay(self, file, play):
        errors = []
        if isinstance(play, dict):
            if 'roles' not in play:
                return errors
            for role in play['roles']:
                if self.matchtask(file, role):
                    errors.append(({'when': role},
                                   'role "when" clause has Jinja2 templates'))
        if isinstance(play, list):
            for play_item in play:
                sub_errors = self.matchplay(file, play_item)
                if sub_errors:
                    errors = errors + sub_errors
        return errors

    def matchtask(self, file, task):
        return 'when' in task and not self._is_valid(task['when'])