Skip to content

Commit

Permalink
Merge pull request #262 from greg-hellings/when_formatting
Browse files Browse the repository at this point in the history
Add format checking for when lines
  • Loading branch information
willthames committed Jul 25, 2018
2 parents 651d926 + 5383572 commit 89565bf
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 0 deletions.
37 changes: 37 additions & 0 deletions lib/ansiblelint/rules/NoFormattingInWhenRule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from ansiblelint import AnsibleLintRule
try:
from types import StringTypes
except ImportError:
# Python3 removed types.StringTypes
StringTypes = str,


class NoFormattingInWhenRule(AnsibleLintRule):
id = 'ANSIBLE0019'
shortdesc = 'No Jinja2 in when'
description = '"when" lines should not include Jinja2 variables'
tags = ['deprecated']

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'])
21 changes: 21 additions & 0 deletions test/TestNoFormattingInWhenRule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import unittest
from ansiblelint import RulesCollection, Runner
from ansiblelint.rules.NoFormattingInWhenRule import NoFormattingInWhenRule


class TestNoFormattingInWhenRule(unittest.TestCase):
collection = RulesCollection()

def setUp(self):
self.collection.register(NoFormattingInWhenRule())

def test_file_positive(self):
success = 'test/jinja2-when-success.yml'
good_runner = Runner(self.collection, success, [], [], [])
self.assertEqual([], good_runner.run())

def test_file_negative(self):
failure = 'test/jinja2-when-failure.yml'
bad_runner = Runner(self.collection, failure, [], [], [])
errs = bad_runner.run()
self.assertEqual(2, len(errs))
10 changes: 10 additions & 0 deletions test/jinja2-when-failure.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
- hosts: all
tasks:
- name: test when with jinja2
debug: msg=text
when: "{{ false }}"

- hosts: all
roles:
- role: test
when: "{{ '1' = '1' }}"
10 changes: 10 additions & 0 deletions test/jinja2-when-success.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
- hosts: all
tasks:
- name: test when
debug: msg=text
when: true

- hosts: all
roles:
- role: role
when: 1 = 1

0 comments on commit 89565bf

Please sign in to comment.