Debian Codegraph @

test/integration/targets/var_precedence/ansible-var-precedence-check.py

raw ◀ ▶
1 Debian patch touch this file
•1 #!/usr/bin/env python3
2
3 # A tool to check the order of precedence for ansible variables
4 # https://github.com/ansible/ansible/blob/devel/test/integration/test_var_precedence.yml
5
6 from __future__ import annotations
7
8 import json
9 import os
10 import sys
11 import shutil
12 import stat
13 import subprocess
14 import tempfile
15 import yaml
16 from optparse import OptionParser
17 from jinja2 import Environment
18
19 ENV = Environment()
20 TESTDIR = tempfile.mkdtemp()
21
22
23 def run_command(args, cwd=None):
24 p = subprocess.Popen(
25 args,
26 stderr=subprocess.PIPE,
27 stdout=subprocess.PIPE,
28 shell=True,
29 cwd=cwd,
30 )
31 (so, se) = p.communicate()
32 return (p.returncode, so, se)
33
34
35 def clean_test_dir():
36 if os.path.isdir(TESTDIR):
37 shutil.rmtree(TESTDIR)
38 os.makedirs(TESTDIR)
39
40
41 class Role(object):
42 def __init__(self, name):
43 self.name = name
44 self.load = True
45 self.dependencies = []
46 self.defaults = False
47 self.vars = False
48 self.tasks = []
49 self.params = dict()
50
51 def write_role(self):
52
53 fpath = os.path.join(TESTDIR, 'roles', self.name)
54 if not os.path.isdir(fpath):
55 os.makedirs(fpath)
56
57 if self.defaults:
58 # roles/x/defaults/main.yml
59 fpath = os.path.join(TESTDIR, 'roles', self.name, 'defaults')
60 if not os.path.isdir(fpath):
61 os.makedirs(fpath)
62 fname = os.path.join(fpath, 'main.yml')
63 with open(fname, 'w') as f:
64 f.write('findme: %s\n' % self.name)
65
66 if self.vars:
67 # roles/x/vars/main.yml
68 fpath = os.path.join(TESTDIR, 'roles', self.name, 'vars')
69 if not os.path.isdir(fpath):
70 os.makedirs(fpath)
71 fname = os.path.join(fpath, 'main.yml')
72 with open(fname, 'w') as f:
73 f.write('findme: %s\n' % self.name)
74
75 if self.dependencies:
76 fpath = os.path.join(TESTDIR, 'roles', self.name, 'meta')
77 if not os.path.isdir(fpath):
78 os.makedirs(fpath)
79 fname = os.path.join(fpath, 'main.yml')
80 with open(fname, 'w') as f:
81 f.write('dependencies:\n')
82 for dep in self.dependencies:
83 f.write('- { role: %s }\n' % dep)
84
85
86 class DynamicInventory(object):
87 BASESCRIPT = '''#!/usr/bin/python
88 import json
89 data = """{{ data }}"""
90 data = json.loads(data)
91 print(json.dumps(data, indent=2, sort_keys=True))
92 '''
93
94 BASEINV = {
95 '_meta': {
96 'hostvars': {
97 'testhost': {}
98 }
99 }
100 }
101
102 def __init__(self, features):
103 self.ENV = Environment()
104 self.features = features
105 self.fpath = None
106 self.inventory = self.BASEINV.copy()
107 self.build()
108
109 def build(self):
110 xhost = 'testhost'
111 if 'script_host' in self.features:
112 self.inventory['_meta']['hostvars'][xhost]['findme'] = 'script_host'
113 else:
114 self.inventory['_meta']['hostvars'][xhost] = {}
115
116 if 'script_child' in self.features:
117 self.inventory['child'] = {
118 'hosts': [xhost],
119 'vars': {'findme': 'script_child'}
120 }
121
122 if 'script_parent' in self.features:
123
124 self.inventory['parent'] = {
125 'vars': {'findme': 'script_parent'}
126 }
127
128 if 'script_child' in self.features:
129 self.inventory['parent']['children'] = ['child']
130 else:
131 self.inventory['parent']['hosts'] = [xhost]
132
133 if 'script_all' in self.features:
134 self.inventory['all'] = {
135 'hosts': [xhost],
136 'vars': {
137 'findme': 'script_all'
138 },
139 }
140 else:
141 self.inventory['all'] = {
142 'hosts': [xhost],
143 }
144
145 def write_script(self):
146 fdir = os.path.join(TESTDIR, 'inventory')
147 if not os.path.isdir(fdir):
148 os.makedirs(fdir)
149 fpath = os.path.join(fdir, 'hosts')
150 # fpath = os.path.join(TESTDIR, 'inventory')
151 self.fpath = fpath
152
153 data = json.dumps(self.inventory)
154 t = self.ENV.from_string(self.BASESCRIPT)
155 fdata = t.render(data=data)
156 with open(fpath, 'w') as f:
157 f.write(fdata + '\n')
158 st = os.stat(fpath)
159 os.chmod(fpath, st.st_mode | stat.S_IEXEC)
160
161
162 class VarTestMaker(object):
163 def __init__(self, features, dynamic_inventory=False):
164 clean_test_dir()
165 self.dynamic_inventory = dynamic_inventory
166 self.di = None
167 self.features = features[:]
168 self.inventory = ''
169 self.playvars = dict()
170 self.varsfiles = []
171 self.playbook = dict(hosts='testhost', gather_facts=False)
172 self.tasks = []
173 self.roles = []
174 self.ansible_command = None
175 self.stdout = None
176
177 def write_playbook(self):
178 fname = os.path.join(TESTDIR, 'site.yml')
179 pb_copy = self.playbook.copy()
180
181 if self.playvars:
182 pb_copy['vars'] = self.playvars
183 if self.varsfiles:
184 pb_copy['vars_files'] = self.varsfiles
185 if self.roles:
186 pb_copy['roles'] = []
187 for role in self.roles:
188 role.write_role()
189 role_def = dict(role=role.name)
190 role_def.update(role.params)
191 pb_copy['roles'].append(role_def)
192 if self.tasks:
193 pb_copy['tasks'] = self.tasks
194
195 with open(fname, 'w') as f:
196 pb_yaml = yaml.dump([pb_copy], f, default_flow_style=False, indent=2)
197
198 def build(self):
199
200 if self.dynamic_inventory:
201 # python based inventory file
202 self.di = DynamicInventory(self.features)
203 self.di.write_script()
204 else:
205 # ini based inventory file
206 if 'ini_host' in self.features:
207 self.inventory += 'testhost findme=ini_host\n'
208 else:
209 self.inventory += 'testhost\n'
210 self.inventory += '\n'
211
212 if 'ini_child' in self.features:
213 self.inventory += '[child]\n'
214 self.inventory += 'testhost\n'
215 self.inventory += '\n'
216 self.inventory += '[child:vars]\n'
217 self.inventory += 'findme=ini_child\n'
218 self.inventory += '\n'
219
220 if 'ini_parent' in self.features:
221 if 'ini_child' in self.features:
222 self.inventory += '[parent:children]\n'
223 self.inventory += 'child\n'
224 else:
225 self.inventory += '[parent]\n'
226 self.inventory += 'testhost\n'
227 self.inventory += '\n'
228 self.inventory += '[parent:vars]\n'
229 self.inventory += 'findme=ini_parent\n'
230 self.inventory += '\n'
231
232 if 'ini_all' in self.features:
233 self.inventory += '[all:vars]\n'
234 self.inventory += 'findme=ini_all\n'
235 self.inventory += '\n'
236
237 # default to a single file called inventory
238 invfile = os.path.join(TESTDIR, 'inventory', 'hosts')
239 ipath = os.path.join(TESTDIR, 'inventory')
240 if not os.path.isdir(ipath):
241 os.makedirs(ipath)
242
243 with open(invfile, 'w') as f:
244 f.write(self.inventory)
245
246 hpath = os.path.join(TESTDIR, 'inventory', 'host_vars')
247 if not os.path.isdir(hpath):
248 os.makedirs(hpath)
249 gpath = os.path.join(TESTDIR, 'inventory', 'group_vars')
250 if not os.path.isdir(gpath):
251 os.makedirs(gpath)
252
253 if 'ini_host_vars_file' in self.features:
254 hfile = os.path.join(hpath, 'testhost')
255 with open(hfile, 'w') as f:
256 f.write('findme: ini_host_vars_file\n')
257
258 if 'ini_group_vars_file_all' in self.features:
259 hfile = os.path.join(gpath, 'all')
260 with open(hfile, 'w') as f:
261 f.write('findme: ini_group_vars_file_all\n')
262
263 if 'ini_group_vars_file_child' in self.features:
264 hfile = os.path.join(gpath, 'child')
265 with open(hfile, 'w') as f:
266 f.write('findme: ini_group_vars_file_child\n')
267
268 if 'ini_group_vars_file_parent' in self.features:
269 hfile = os.path.join(gpath, 'parent')
270 with open(hfile, 'w') as f:
271 f.write('findme: ini_group_vars_file_parent\n')
272
273 if 'pb_host_vars_file' in self.features:
274 os.makedirs(os.path.join(TESTDIR, 'host_vars'))
275 fname = os.path.join(TESTDIR, 'host_vars', 'testhost')
276 with open(fname, 'w') as f:
277 f.write('findme: pb_host_vars_file\n')
278
279 if 'pb_group_vars_file_parent' in self.features:
280 if not os.path.isdir(os.path.join(TESTDIR, 'group_vars')):
281 os.makedirs(os.path.join(TESTDIR, 'group_vars'))
282 fname = os.path.join(TESTDIR, 'group_vars', 'parent')
283 with open(fname, 'w') as f:
284 f.write('findme: pb_group_vars_file_parent\n')
285
286 if 'pb_group_vars_file_child' in self.features:
287 if not os.path.isdir(os.path.join(TESTDIR, 'group_vars')):
288 os.makedirs(os.path.join(TESTDIR, 'group_vars'))
289 fname = os.path.join(TESTDIR, 'group_vars', 'child')
290 with open(fname, 'w') as f:
291 f.write('findme: pb_group_vars_file_child\n')
292
293 if 'pb_group_vars_file_all' in self.features:
294 if not os.path.isdir(os.path.join(TESTDIR, 'group_vars')):
295 os.makedirs(os.path.join(TESTDIR, 'group_vars'))
296 fname = os.path.join(TESTDIR, 'group_vars', 'all')
297 with open(fname, 'w') as f:
298 f.write('findme: pb_group_vars_file_all\n')
299
300 if 'play_var' in self.features:
301 self.playvars['findme'] = 'play_var'
302
303 if 'set_fact' in self.features:
304 self.tasks.append(dict(set_fact='findme="set_fact"'))
305
306 if 'vars_file' in self.features:
307 self.varsfiles.append('varsfile.yml')
308 fname = os.path.join(TESTDIR, 'varsfile.yml')
309 with open(fname, 'w') as f:
310 f.write('findme: vars_file\n')
311
312 if 'include_vars' in self.features:
313 self.tasks.append(dict(include_vars='included_vars.yml'))
314 fname = os.path.join(TESTDIR, 'included_vars.yml')
315 with open(fname, 'w') as f:
316 f.write('findme: include_vars\n')
317
318 if 'role_var' in self.features:
319 role = Role('role_var')
320 role.vars = True
321 role.load = True
322 self.roles.append(role)
323
324 if 'role_parent_default' in self.features:
325 role = Role('role_default')
326 role.load = False
327 role.defaults = True
328 self.roles.append(role)
329
330 role = Role('role_parent_default')
331 role.dependencies.append('role_default')
332 role.defaults = True
333 role.load = True
334 if 'role_params' in self.features:
335 role.params = dict(findme='role_params')
336 self.roles.append(role)
337
338 elif 'role_default' in self.features:
339 role = Role('role_default')
340 role.defaults = True
341 role.load = True
342 if 'role_params' in self.features:
343 role.params = dict(findme='role_params')
344 self.roles.append(role)
345
346 debug_task = dict(debug='var=findme')
347 test_task = {'assert': dict(that=['findme == "%s"' % self.features[0]])}
348 if 'task_vars' in self.features:
349 test_task['vars'] = dict(findme="task_vars")
350 if 'registered_vars' in self.features:
351 test_task['register'] = 'findme'
352
353 if 'block_vars' in self.features:
354 block_wrapper = [
355 debug_task,
356 {
357 'block': [test_task],
358 'vars': dict(findme="block_vars"),
359 }
360 ]
361 else:
362 block_wrapper = [debug_task, test_task]
363
364 if 'include_params' in self.features:
365 self.tasks.append(dict(name='including tasks', include_tasks='included_tasks.yml', vars=dict(findme='include_params')))
366 else:
367 self.tasks.append(dict(include_tasks='included_tasks.yml'))
368
369 fname = os.path.join(TESTDIR, 'included_tasks.yml')
370 with open(fname, 'w') as f:
371 f.write(yaml.dump(block_wrapper))
372
373 self.write_playbook()
374
375 def run(self):
376 """
377 if self.dynamic_inventory:
378 cmd = 'ansible-playbook -c local -i inventory/hosts site.yml'
379 else:
380 cmd = 'ansible-playbook -c local -i inventory site.yml'
381 """
382 cmd = 'ansible-playbook -c local -i inventory site.yml'
383 if 'extra_vars' in self.features:
384 cmd += ' --extra-vars="findme=extra_vars"'
385 cmd = cmd + ' -vvvvv'
386 self.ansible_command = cmd
387 (rc, so, se) = run_command(cmd, cwd=TESTDIR)
388 self.stdout = so
389
390 if rc != 0:
391 raise Exception("playbook failed (rc=%s), stdout: '%s' stderr: '%s'" % (rc, so, se))
392
393 def show_tree(self):
394 print('## TREE')
395 cmd = 'tree %s' % TESTDIR
396 (rc, so, se) = run_command(cmd)
397 lines = so.split('\n')
398 lines = lines[:-3]
399 print('\n'.join(lines))
400
401 def show_content(self):
402 print('## CONTENT')
403 cmd = 'find %s -type f | xargs tail -n +1' % TESTDIR
404 (rc, so, se) = run_command(cmd)
405 print(so)
406
407 def show_stdout(self):
408 print('## COMMAND')
409 print(self.ansible_command)
410 print('## STDOUT')
411 print(self.stdout)
412
413
414 def main():
415 features = [
416 'extra_vars',
417 'include_params',
418 # 'role_params', # FIXME: we don't yet validate tasks within a role
419 'set_fact',
420 # 'registered_vars', # FIXME: hard to simulate
421 'include_vars',
422 # 'role_dep_params',
423 'task_vars',
424 'block_vars',
425 'role_var',
426 'vars_file',
427 'play_var',
428 # 'host_facts', # FIXME: hard to simulate
429 'pb_host_vars_file',
430 'ini_host_vars_file',
431 'ini_host',
432 'pb_group_vars_file_child',
433 # 'ini_group_vars_file_child', # FIXME: this contradicts documented precedence pb group vars files should override inventory ones
434 'pb_group_vars_file_parent',
435 'ini_group_vars_file_parent',
436 'pb_group_vars_file_all',
437 'ini_group_vars_file_all',
438 'ini_child',
439 'ini_parent',
440 'ini_all',
441 'role_parent_default',
442 'role_default',
443 ]
444
445 parser = OptionParser()
446 parser.add_option('-f', '--feature', action='append')
447 parser.add_option('--use_dynamic_inventory', action='store_true')
448 parser.add_option('--show_tree', action='store_true')
449 parser.add_option('--show_content', action='store_true')
450 parser.add_option('--show_stdout', action='store_true')
451 parser.add_option('--copy_testcases_to_local_dir', action='store_true')
452 (options, args) = parser.parse_args()
453
454 if options.feature:
455 for f in options.feature:
456 if f not in features:
457 print('%s is not a valid feature' % f)
458 sys.exit(1)
459 features = list(options.feature)
460
461 fdesc = {
462 'ini_host': 'host var inside the ini',
463 'script_host': 'host var inside the script _meta',
464 'ini_child': 'child group var inside the ini',
465 'script_child': 'child group var inside the script',
466 'ini_parent': 'parent group var inside the ini',
467 'script_parent': 'parent group var inside the script',
468 'ini_all': 'all group var inside the ini',
469 'script_all': 'all group var inside the script',
470 'ini_host_vars_file': 'var in inventory/host_vars/host',
471 'ini_group_vars_file_parent': 'var in inventory/group_vars/parent',
472 'ini_group_vars_file_child': 'var in inventory/group_vars/child',
473 'ini_group_vars_file_all': 'var in inventory/group_vars/all',
474 'pb_group_vars_file_parent': 'var in playbook/group_vars/parent',
475 'pb_group_vars_file_child': 'var in playbook/group_vars/child',
476 'pb_group_vars_file_all': 'var in playbook/group_vars/all',
477 'pb_host_vars_file': 'var in playbook/host_vars/host',
478 'play_var': 'var set in playbook header',
479 'role_parent_default': 'var in roles/role_parent/defaults/main.yml',
480 'role_default': 'var in roles/role/defaults/main.yml',
481 'role_var': 'var in ???',
482 'include_vars': 'var in included file',
483 'set_fact': 'var made by set_fact',
484 'vars_file': 'var in file added by vars_file',
485 'block_vars': 'vars defined on the block',
486 'task_vars': 'vars defined on the task',
487 'extra_vars': 'var passed via the cli'
488 }
489
490 dinv = options.use_dynamic_inventory
491 if dinv:
492 # some features are specific to ini, so swap those
493 for (idx, x) in enumerate(features):
494 if x.startswith('ini_') and 'vars_file' not in x:
495 features[idx] = x.replace('ini_', 'script_')
496
497 dinv = options.use_dynamic_inventory
498
499 index = 1
500 while features:
501 VTM = VarTestMaker(features, dynamic_inventory=dinv)
502 VTM.build()
503
504 if options.show_tree or options.show_content or options.show_stdout:
505 print('')
506 if options.show_tree:
507 VTM.show_tree()
508 if options.show_content:
509 VTM.show_content()
510
511 try:
512 print("CHECKING: %s (%s)" % (features[0], fdesc.get(features[0], '')))
513 res = VTM.run()
514 if options.show_stdout:
515 VTM.show_stdout()
516
517 features.pop(0)
518
519 if options.copy_testcases_to_local_dir:
520 topdir = 'testcases'
521 if index == 1 and os.path.isdir(topdir):
522 shutil.rmtree(topdir)
523 if not os.path.isdir(topdir):
524 os.makedirs(topdir)
525 thisindex = str(index)
526 if len(thisindex) == 1:
527 thisindex = '0' + thisindex
528 thisdir = os.path.join(topdir, '%s.%s' % (thisindex, res))
529 shutil.copytree(TESTDIR, thisdir)
530
531 except Exception as e:
532 print("ERROR !!!")
533 print(e)
534 print('feature: %s failed' % features[0])
535 sys.exit(1)
536 finally:
537 shutil.rmtree(TESTDIR)
538 index += 1
539
540
541 if __name__ == "__main__":
542 main()