FAQ | This is a LIVE service | Changelog

Skip to content
Snippets Groups Projects
Commit 1a38d573 authored by Dr Catherine Pitt's avatar Dr Catherine Pitt
Browse files

Make TemplatesHaveTag rule handle simple loops

Handles simple cases of with_items, with_first_found, and
with_random_choice. Examples:

template:
  src: "{{ item }}".j2
with_items:
  - foo
  - bar

template:
  src: "{{ item }}".j2
with_first_found:
  - foo
  - bar

will both look for templates called foo.j2 and bar.j2 in the usual
template locations, and check them if found.

template:
  src: "{{ item }}".j2
with_first_found:
  - files:
    - foo
    - bar
  - paths:
    - etc
    - usr/lib

will look for and check any of etc/foo.j2 etc/bar.j2 usr/lib/foo.j2 usr/lib/bar.j2
parent 159fb3c5
No related branches found
No related tags found
No related merge requests found
import os
import re
from ansiblelint import AnsibleLintRule
class TemplatesHaveTag(AnsibleLintRule):
......@@ -36,10 +37,35 @@ class TemplatesHaveTag(AnsibleLintRule):
potential_paths.append(os.path.join(dirname,subdir,template))
return [ x for x in potential_paths if os.path.isfile(x) ]
def possible_templates(self,taskfile,task):
# handle simple cases with loops, mostly lifted from UsingBareVariablesIsDeprecatedRule.py
item_sub = re.compile('{{\s*item\s*}}')
loop_type = next((key for key in task
if key.startswith("with_")), None)
if loop_type:
if loop_type in ["with_items", "with_random_choice"]:
possibles = task[loop_type]
return [ item_sub.sub(x,task['action']['src']) for x in possibles if not isinstance(x,dict)]
elif loop_type in ["with_first_found"]:
possibles = []
for i in task[loop_type]:
if isinstance(i,dict):
possibles += [ os.path.join(x,y) for x in i.get('paths',[]) for y in i['files']]
else:
possibles += task[loop_type]
return [ item_sub.sub(x,task['action']['src']) for x in possibles ]
else:
pass
return [task['action']['src']]
def matchtask(self,taskfile,task):
results = []
if task['action']['__ansible_module__'] == 'template':
for template in self.possible_paths(taskfile['path'],task['action']['src']):
with open(template,'r') as f:
if '{{ ansible_managed | chem_managed }}' not in f.read():
return "{{{{ ansible_managed | chem_managed }}}} not found in {}".format(template)
for filename in self.possible_templates(taskfile,task):
for template in self.possible_paths(taskfile['path'],filename):
with open(template,'r') as f:
if '{{ ansible_managed | chem_managed }}' not in f.read():
results.append(template)
if results:
return "{{{{ ansible_managed | chem_managed }}}} not found in {}".format(' '.join(results))
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment