Browse code

Ship constants to the modules via internal module params rather than a secondary dict.

Toshio Kuratomi authored on 2016/05/13 12:30:05
Showing 11 changed files
... ...
@@ -388,12 +388,6 @@ def _get_shebang(interpreter, task_vars, args=tuple()):
388 388
 
389 389
     return (shebang, interpreter)
390 390
 
391
-def _get_facility(task_vars):
392
-    facility = C.DEFAULT_SYSLOG_FACILITY
393
-    if 'ansible_syslog_facility' in task_vars:
394
-        facility = task_vars['ansible_syslog_facility']
395
-    return facility
396
-
397 391
 def recursive_finder(name, data, py_module_names, py_module_cache, zf):
398 392
     """
399 393
     Using ModuleDepFinder, make sure we have all of the module_utils files that
... ...
@@ -532,15 +526,7 @@ def _find_snippet_imports(module_name, module_data, module_path, module_args, ta
532 532
     py_module_names = set()
533 533
 
534 534
     if module_substyle == 'python':
535
-        # ziploader for new-style python classes
536
-        constants = dict(
537
-                SELINUX_SPECIAL_FS=C.DEFAULT_SELINUX_SPECIAL_FS,
538
-                SYSLOG_FACILITY=_get_facility(task_vars),
539
-                ANSIBLE_VERSION=__version__,
540
-                )
541
-        params = dict(ANSIBLE_MODULE_ARGS=module_args,
542
-                ANSIBLE_MODULE_CONSTANTS=constants,
543
-                )
535
+        params = dict(ANSIBLE_MODULE_ARGS=module_args,)
544 536
         python_repred_params = to_bytes(repr(json.dumps(params)), errors='strict')
545 537
 
546 538
         try:
... ...
@@ -690,7 +676,7 @@ def _find_snippet_imports(module_name, module_data, module_path, module_args, ta
690 690
         # The main event -- substitute the JSON args string into the module
691 691
         module_data = module_data.replace(REPLACER_JSONARGS, module_args_json)
692 692
 
693
-        facility = b'syslog.' + to_bytes(_get_facility(task_vars), errors='strict')
693
+        facility = b'syslog.' + to_bytes(task_vars.get('ansible_syslog_facility', C.DEFAULT_SYSLOG_FACILITY), errors='strict')
694 694
         module_data = module_data.replace(b'syslog.LOG_USER', facility)
695 695
 
696 696
     return (module_data, module_style, shebang)
... ...
@@ -558,7 +558,7 @@ class AnsibleModule(object):
558 558
         self.run_command_environ_update = {}
559 559
 
560 560
         self.aliases = {}
561
-        self._legal_inputs = ['_ansible_check_mode', '_ansible_no_log', '_ansible_debug', '_ansible_diff', '_ansible_verbosity']
561
+        self._legal_inputs = ['_ansible_check_mode', '_ansible_no_log', '_ansible_debug', '_ansible_diff', '_ansible_verbosity', '_ansible_selinux_special_fs', '_ansible_version', '_ansible_syslog_facility']
562 562
 
563 563
         if add_file_common_args:
564 564
             for k, v in FILE_COMMON_ARGUMENTS.items():
... ...
@@ -782,7 +782,7 @@ class AnsibleModule(object):
782 782
             (device, mount_point, fstype, options, rest) = line.split(' ', 4)
783 783
 
784 784
             if path_mount_point == mount_point:
785
-                for fs in self.constants['SELINUX_SPECIAL_FS']:
785
+                for fs in self._selinux_special_fs:
786 786
                     if fs in fstype:
787 787
                         special_context = self.selinux_context(path_mount_point)
788 788
                         return (True, special_context)
... ...
@@ -1175,7 +1175,8 @@ class AnsibleModule(object):
1175 1175
         return aliases_results
1176 1176
 
1177 1177
     def _check_arguments(self, check_invalid_arguments):
1178
-        for (k,v) in self.params.items():
1178
+        self._syslog_facility = 'LOG_USER'
1179
+        for (k,v) in list(self.params.items()):
1179 1180
 
1180 1181
             if k == '_ansible_check_mode' and v:
1181 1182
                 if not self.supports_check_mode:
... ...
@@ -1194,6 +1195,15 @@ class AnsibleModule(object):
1194 1194
             elif k == '_ansible_verbosity':
1195 1195
                 self._verbosity = v
1196 1196
 
1197
+            elif k == '_ansible_selinux_special_fs':
1198
+                self._selinux_special_fs = v
1199
+
1200
+            elif k == '_ansible_syslog_facility':
1201
+                self._syslog_facility = v
1202
+
1203
+            elif k == '_ansible_version':
1204
+                self.ansible_version = v
1205
+
1197 1206
             elif check_invalid_arguments and k not in self._legal_inputs:
1198 1207
                 self.fail_json(msg="unsupported parameter for module: %s" % k)
1199 1208
 
... ...
@@ -1505,7 +1515,6 @@ class AnsibleModule(object):
1505 1505
 
1506 1506
         try:
1507 1507
             self.params = params['ANSIBLE_MODULE_ARGS']
1508
-            self.constants = params['ANSIBLE_MODULE_CONSTANTS']
1509 1508
         except KeyError:
1510 1509
             # This helper used too early for fail_json to work.
1511 1510
             print('\n{"msg": "Error: Module unable to locate ANSIBLE_MODULE_ARGS and ANSIBLE_MODULE_CONSTANTS in json data from stdin.  Unable to figure out what parameters were passed", "failed": true}')
... ...
@@ -1514,7 +1523,7 @@ class AnsibleModule(object):
1514 1514
     def _log_to_syslog(self, msg):
1515 1515
         if HAS_SYSLOG:
1516 1516
             module = 'ansible-%s' % os.path.basename(__file__)
1517
-            facility = getattr(syslog, self.constants.get('SYSLOG_FACILITY', 'LOG_USER'), syslog.LOG_USER)
1517
+            facility = getattr(syslog, self._syslog_facility, syslog.LOG_USER)
1518 1518
             syslog.openlog(str(module), 0, facility)
1519 1519
             syslog.syslog(syslog.LOG_INFO, msg)
1520 1520
 
... ...
@@ -263,7 +263,7 @@ def rax_required_together():
263 263
 
264 264
 def setup_rax_module(module, rax_module, region_required=True):
265 265
     """Set up pyrax in a standard way for all modules"""
266
-    rax_module.USER_AGENT = 'ansible/%s %s' % (module.constants['ANSIBLE_VERSION'],
266
+    rax_module.USER_AGENT = 'ansible/%s %s' % (module.ansible_version,
267 267
                                                rax_module.USER_AGENT)
268 268
 
269 269
     api_key = module.params.get('api_key')
... ...
@@ -35,6 +35,7 @@ from ansible.compat.six import binary_type, text_type, iteritems, with_metaclass
35 35
 from ansible import constants as C
36 36
 from ansible.errors import AnsibleError, AnsibleConnectionFailure
37 37
 from ansible.executor.module_common import modify_module
38
+from ansible.release import __version__
38 39
 from ansible.parsing.utils.jsonify import jsonify
39 40
 from ansible.utils.unicode import to_bytes, to_unicode
40 41
 
... ...
@@ -570,6 +571,15 @@ class ActionBase(with_metaclass(ABCMeta, object)):
570 570
         # let module know our verbosity
571 571
         module_args['_ansible_verbosity'] = display.verbosity
572 572
 
573
+        # give the module information about the ansible version
574
+        module_args['_ansible_version'] = __version__
575
+
576
+        # set the syslog facility to be used in the module
577
+        module_args['_ansible_syslog_facility'] = task_vars.get('ansible_syslog_facility', C.DEFAULT_SYSLOG_FACILITY)
578
+
579
+        # let module know about filesystems that selinux treats specially
580
+        module_args['_ansible_selinux_special_fs'] = C.DEFAULT_SELINUX_SPECIAL_FS
581
+
573 582
         (module_style, shebang, module_data) = self._configure_module(module_name=module_name, module_args=module_args, task_vars=task_vars)
574 583
         if not shebang:
575 584
             raise AnsibleError("module (%s) is missing interpreter line" % module_name)
... ...
@@ -36,7 +36,6 @@ class TestModuleUtilsBasic(unittest.TestCase):
36 36
             dict(
37 37
                 ANSIBLE_MODULE_ARGS=dict(
38 38
                     foo=False, bar=[1,2,3], bam="bam", baz=u'baz'),
39
-                ANSIBLE_MODULE_CONSTANTS=dict()
40 39
                 ))):
41 40
             from ansible.module_utils import basic
42 41
 
... ...
@@ -35,7 +35,7 @@ empty_invocation = {u'module_args': {}}
35 35
 @unittest.skipIf(sys.version_info[0] >= 3, "Python 3 is not supported on targets (yet)")
36 36
 class TestAnsibleModuleExitJson(unittest.TestCase):
37 37
     def setUp(self):
38
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
38
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
39 39
         self.stdin_swap_ctx = swap_stdin_and_argv(stdin_data=args)
40 40
         self.stdin_swap_ctx.__enter__()
41 41
 
... ...
@@ -120,7 +120,7 @@ class TestAnsibleModuleExitValuesRemoved(unittest.TestCase):
120 120
     def test_exit_json_removes_values(self):
121 121
         self.maxDiff = None
122 122
         for args, return_val, expected in self.dataset:
123
-            params = dict(ANSIBLE_MODULE_ARGS=args, ANSIBLE_MODULE_CONSTANTS={})
123
+            params = dict(ANSIBLE_MODULE_ARGS=args)
124 124
             params = json.dumps(params)
125 125
 
126 126
             with swap_stdin_and_argv(stdin_data=params):
... ...
@@ -143,7 +143,7 @@ class TestAnsibleModuleExitValuesRemoved(unittest.TestCase):
143 143
             expected = copy.deepcopy(expected)
144 144
             del expected['changed']
145 145
             expected['failed'] = True
146
-            params = dict(ANSIBLE_MODULE_ARGS=args, ANSIBLE_MODULE_CONSTANTS={})
146
+            params = dict(ANSIBLE_MODULE_ARGS=args)
147 147
             params = json.dumps(params)
148 148
             with swap_stdin_and_argv(stdin_data=params):
149 149
                 with swap_stdout():
... ...
@@ -43,7 +43,7 @@ except ImportError:
43 43
 
44 44
 class TestAnsibleModuleSysLogSmokeTest(unittest.TestCase):
45 45
     def setUp(self):
46
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
46
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
47 47
 
48 48
         # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
49 49
         self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
... ...
@@ -80,7 +80,7 @@ class TestAnsibleModuleSysLogSmokeTest(unittest.TestCase):
80 80
 class TestAnsibleModuleJournaldSmokeTest(unittest.TestCase):
81 81
 
82 82
     def setUp(self):
83
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
83
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
84 84
 
85 85
         # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
86 86
         self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
... ...
@@ -129,7 +129,7 @@ class TestAnsibleModuleLogSyslog(unittest.TestCase):
129 129
             }
130 130
 
131 131
     def setUp(self):
132
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
132
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
133 133
         # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
134 134
         self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
135 135
         self.stdin_swap.__enter__()
... ...
@@ -190,7 +190,7 @@ class TestAnsibleModuleLogJournal(unittest.TestCase):
190 190
 
191 191
     # overriding run lets us use context managers for setup/teardown-esque behavior
192 192
     def setUp(self):
193
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
193
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
194 194
         # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
195 195
         self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
196 196
         self.stdin_swap.__enter__()
... ...
@@ -62,7 +62,7 @@ class TestAnsibleModuleRunCommand(unittest.TestCase):
62 62
             if path == '/inaccessible':
63 63
                 raise OSError(errno.EPERM, "Permission denied: '/inaccessible'")
64 64
 
65
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
65
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
66 66
         # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
67 67
         self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
68 68
         self.stdin_swap.__enter__()
... ...
@@ -31,7 +31,7 @@ class TestAnsibleModuleExitJson(unittest.TestCase):
31 31
     def test_module_utils_basic_safe_eval(self):
32 32
         from ansible.module_utils import basic
33 33
 
34
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
34
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
35 35
 
36 36
         with swap_stdin_and_argv(stdin_data=args):
37 37
             basic._ANSIBLE_ARGS = None
... ...
@@ -41,7 +41,7 @@ realimport = builtins.__import__
41 41
 class TestModuleUtilsBasic(unittest.TestCase):
42 42
 
43 43
     def setUp(self):
44
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
44
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
45 45
         # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually
46 46
         self.stdin_swap = swap_stdin_and_argv(stdin_data=args)
47 47
         self.stdin_swap.__enter__()
... ...
@@ -288,7 +288,7 @@ class TestModuleUtilsBasic(unittest.TestCase):
288 288
         req_to = (('bam', 'baz'),)
289 289
 
290 290
         # should test ok
291
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"foo": "hello"}, ANSIBLE_MODULE_CONSTANTS={}))
291
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"foo": "hello"}))
292 292
 
293 293
         with swap_stdin_and_argv(stdin_data=args):
294 294
             basic._ANSIBLE_ARGS = None
... ...
@@ -305,7 +305,7 @@ class TestModuleUtilsBasic(unittest.TestCase):
305 305
         # FIXME: add asserts here to verify the basic config
306 306
 
307 307
         # fail, because a required param was not specified
308
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
308
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
309 309
 
310 310
         with swap_stdin_and_argv(stdin_data=args):
311 311
             basic._ANSIBLE_ARGS = None
... ...
@@ -322,7 +322,7 @@ class TestModuleUtilsBasic(unittest.TestCase):
322 322
             )
323 323
 
324 324
         # fail because of mutually exclusive parameters
325
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"foo":"hello", "bar": "bad", "bam": "bad"}, ANSIBLE_MODULE_CONSTANTS={}))
325
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"foo":"hello", "bar": "bad", "bam": "bad"}))
326 326
 
327 327
         with swap_stdin_and_argv(stdin_data=args):
328 328
             self.assertRaises(
... ...
@@ -338,7 +338,7 @@ class TestModuleUtilsBasic(unittest.TestCase):
338 338
             )
339 339
 
340 340
         # fail because a param required due to another param was not specified
341
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"bam": "bad"}, ANSIBLE_MODULE_CONSTANTS={}))
341
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={"bam": "bad"}))
342 342
 
343 343
         with swap_stdin_and_argv(stdin_data=args):
344 344
             self.assertRaises(
... ...
@@ -550,14 +550,13 @@ class TestModuleUtilsBasic(unittest.TestCase):
550 550
         from ansible.module_utils import basic
551 551
         basic._ANSIBLE_ARGS = None
552 552
 
553
-        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={"SELINUX_SPECIAL_FS": "nfs,nfsd,foos"}))
553
+        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={'_ansible_selinux_special_fs': "nfs,nfsd,foos"}))
554 554
 
555 555
         with swap_stdin_and_argv(stdin_data=args):
556 556
 
557 557
             am = basic.AnsibleModule(
558 558
                 argument_spec = dict(),
559 559
             )
560
-            print(am.constants)
561 560
 
562 561
             def _mock_find_mount_point(path):
563 562
                 if path.startswith('/some/path'):
... ...
@@ -327,7 +327,7 @@ def test_distribution_version():
327 327
 
328 328
     from ansible.module_utils import basic
329 329
 
330
-    args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))
330
+    args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
331 331
     with swap_stdin_and_argv(stdin_data=args):
332 332
         module = basic.AnsibleModule(argument_spec=dict())
333 333