Пример #1
0
 def test_ensure_command_called(self, mock_ems_log):
     ''' calling get_all will raise a KeyError exception '''
     set_module_args({
         'hostname': 'hostname',
         'username': '******',
         'password': '******',
     })
     module = basic.AnsibleModule(
         argument_spec=netapp_utils.na_ontap_host_argument_spec(),
         supports_check_mode=True
     )
     my_obj = my_module(module)
     my_obj.server = MockONTAPConnection('vserver', 'SVMadmin')
     with pytest.raises(KeyError) as exc:
         my_obj.get_all()
     if sys.version_info >= (2, 7):
         msg = 'net-interface-info'
         assert exc.value.args[0] == msg
Пример #2
0
def main():
    # Parsing argument file
    module = basic.AnsibleModule(argument_spec=dict(
        src=dict(required=True, type='str'),
        dest=dict(required=False, type='str'),
        operations=dict(required=True, type='list'),
        backup=dict(required=False, default=False, type='bool'),
        unsafe_writes=dict(required=False, default=False, type='bool'),
        pretty=dict(required=False, default=False, type='bool'),
        create=dict(required=False, default=False, type='bool'),
        create_type=dict(required=False, default='object', type='str'),
    ),
                                 supports_check_mode=True)

    manager = PatchManager(module)
    result = manager.run()

    module.exit_json(**result)
Пример #3
0
    def test_module_utils_basic_ansible_module_set_group_if_different(self):
        from ansible.module_utils import basic

        basic.MODULE_COMPLEX_ARGS = '{}'
        am = basic.AnsibleModule(argument_spec=dict(), )

        self.assertEqual(
            am.set_group_if_different('/path/to/file', None, True), True)
        self.assertEqual(
            am.set_group_if_different('/path/to/file', None, False), False)

        am.user_and_group = MagicMock(return_value=(500, 500))

        with patch('os.lchown', return_value=None) as m:
            self.assertEqual(
                am.set_group_if_different('/path/to/file', 0, False), True)
            m.assert_called_with('/path/to/file', -1, 0)

            def _mock_getgrnam(*args, **kwargs):
                mock_gr = MagicMock()
                mock_gr.gr_gid = 0
                return mock_gr

            m.reset_mock()
            with patch('grp.getgrnam', side_effect=_mock_getgrnam):
                self.assertEqual(
                    am.set_group_if_different('/path/to/file', 'root', False),
                    True)
                m.assert_called_with('/path/to/file', -1, 0)

            with patch('grp.getgrnam', side_effect=KeyError):
                self.assertRaises(SystemExit, am.set_group_if_different,
                                  '/path/to/file', 'root', False)

            m.reset_mock()
            am.check_mode = True
            self.assertEqual(
                am.set_group_if_different('/path/to/file', 0, False), True)
            self.assertEqual(m.called, False)
            am.check_mode = False

        with patch('os.lchown', side_effect=OSError) as m:
            self.assertRaises(SystemExit, am.set_group_if_different,
                              '/path/to/file', 'root', False)
Пример #4
0
    def test_module_utils_basic_ansible_module_set_owner_if_different(self):
        from ansible.module_utils import basic
        reload(basic)

        am = basic.AnsibleModule(argument_spec=dict(), )

        self.assertEqual(
            am.set_owner_if_different('/path/to/file', None, True), True)
        self.assertEqual(
            am.set_owner_if_different('/path/to/file', None, False), False)

        am.user_and_group = MagicMock(return_value=(500, 500))

        with patch('os.lchown', return_value=None) as m:
            self.assertEqual(
                am.set_owner_if_different('/path/to/file', 0, False), True)
            m.assert_called_with('/path/to/file', 0, -1)

            def _mock_getpwnam(*args, **kwargs):
                mock_pw = MagicMock()
                mock_pw.pw_uid = 0
                return mock_pw

            m.reset_mock()
            with patch('pwd.getpwnam', side_effect=_mock_getpwnam):
                self.assertEqual(
                    am.set_owner_if_different('/path/to/file', 'root', False),
                    True)
                m.assert_called_with('/path/to/file', 0, -1)

            with patch('pwd.getpwnam', side_effect=KeyError):
                self.assertRaises(SystemExit, am.set_owner_if_different,
                                  '/path/to/file', 'root', False)

            m.reset_mock()
            am.check_mode = True
            self.assertEqual(
                am.set_owner_if_different('/path/to/file', 0, False), True)
            self.assertEqual(m.called, False)
            am.check_mode = False

        with patch('os.lchown', side_effect=OSError) as m:
            self.assertRaises(SystemExit, am.set_owner_if_different,
                              '/path/to/file', 'root', False)
Пример #5
0
    def test_module_utils_basic_ansible_module_set_mode_if_different(self):
        from ansible.module_utils import basic

        basic.MODULE_COMPLEX_ARGS = '{}'
        am = basic.AnsibleModule(argument_spec=dict(), )

        mock_stat1 = MagicMock()
        mock_stat1.st_mode = 0o444
        mock_stat2 = MagicMock()
        mock_stat2.st_mode = 0o660

        with patch('os.lstat', side_effect=[mock_stat1]):
            self.assertEqual(
                am.set_mode_if_different('/path/to/file', None, True), True)
        with patch('os.lstat', side_effect=[mock_stat1]):
            self.assertEqual(
                am.set_mode_if_different('/path/to/file', None, False), False)

        with patch('os.lstat') as m:
            with patch('os.lchmod', return_value=None, create=True) as m_os:
                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                self.assertEqual(
                    am.set_mode_if_different('/path/to/file', 0o660, False),
                    True)
                m_os.assert_called_with('/path/to/file', 0o660)

                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                am._symbolic_mode_to_octal = MagicMock(return_value=0o660)
                self.assertEqual(
                    am.set_mode_if_different('/path/to/file', 'o+w,g+w,a-r',
                                             False), True)
                m_os.assert_called_with('/path/to/file', 0o660)

                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                am._symbolic_mode_to_octal = MagicMock(side_effect=Exception)
                self.assertRaises(SystemExit, am.set_mode_if_different,
                                  '/path/to/file', 'o+w,g+w,a-r', False)

                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                am.check_mode = True
                self.assertEqual(
                    am.set_mode_if_different('/path/to/file', 0o660, False),
                    True)
                am.check_mode = False
Пример #6
0
    def test_module_utils_basic_ansible_module_set_context_if_different(self):
        from ansible.module_utils import basic
        basic._ANSIBLE_ARGS = None

        am = basic.AnsibleModule(
            argument_spec=dict(),
        )

        basic.HAVE_SELINUX = False

        am.selinux_enabled = MagicMock(return_value=False)
        self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True), True)
        self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), False)

        basic.HAVE_SELINUX = True

        am.selinux_enabled = MagicMock(return_value=True)
        am.selinux_context = MagicMock(return_value=['bar_u', 'bar_r', None, None])
        am.is_special_selinux_path = MagicMock(return_value=(False, None))

        basic.selinux = Mock()
        with patch.dict('sys.modules', {'selinux': basic.selinux}):
            with patch('selinux.lsetfilecon', return_value=0) as m:
                self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True)
                m.assert_called_with('/path/to/file', 'foo_u:foo_r:foo_t:s0')
                m.reset_mock()
                am.check_mode = True
                self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True)
                self.assertEqual(m.called, False)
                am.check_mode = False

            with patch('selinux.lsetfilecon', return_value=1) as m:
                self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True)

            with patch('selinux.lsetfilecon', side_effect=OSError) as m:
                self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True)

            am.is_special_selinux_path = MagicMock(return_value=(True, ['sp_u', 'sp_r', 'sp_t', 's0']))

            with patch('selinux.lsetfilecon', return_value=0) as m:
                self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True)
                m.assert_called_with('/path/to/file', 'sp_u:sp_r:sp_t:s0')

        delattr(basic, 'selinux')
Пример #7
0
    def test_module_utils_basic_ansible_module_is_special_selinux_path(self):
        from ansible.module_utils import basic

        args = json.dumps(dict(ANSIBLE_MODULE_ARGS={'_ansible_selinux_special_fs': "nfs,nfsd,foos",
                                                    '_ansible_remote_tmp': "/tmp",
                                                    '_ansible_keep_remote_files': False}))

        with swap_stdin_and_argv(stdin_data=args):
            basic._ANSIBLE_ARGS = None
            am = basic.AnsibleModule(
                argument_spec=dict(),
            )

            def _mock_find_mount_point(path):
                if path.startswith('/some/path'):
                    return '/some/path'
                elif path.startswith('/weird/random/fstype'):
                    return '/weird/random/fstype'
                return '/'

            am.find_mount_point = MagicMock(side_effect=_mock_find_mount_point)
            am.selinux_context = MagicMock(return_value=['foo_u', 'foo_r', 'foo_t', 's0'])

            m = mock_open()
            m.side_effect = OSError

            with patch.object(builtins, 'open', m, create=True):
                self.assertEqual(am.is_special_selinux_path('/some/path/that/should/be/nfs'), (False, None))

            mount_data = [
                '/dev/disk1 / ext4 rw,seclabel,relatime,data=ordered 0 0\n',
                '1.1.1.1:/path/to/nfs /some/path nfs ro 0 0\n',
                'whatever /weird/random/fstype foos rw 0 0\n',
            ]

            # mock_open has a broken readlines() implementation apparently...
            # this should work by default but doesn't, so we fix it
            m = mock_open(read_data=''.join(mount_data))
            m.return_value.readlines.return_value = mount_data

            with patch.object(builtins, 'open', m, create=True):
                self.assertEqual(am.is_special_selinux_path('/some/random/path'), (False, None))
                self.assertEqual(am.is_special_selinux_path('/some/path/that/should/be/nfs'), (True, ['foo_u', 'foo_r', 'foo_t', 's0']))
                self.assertEqual(am.is_special_selinux_path('/weird/random/fstype/path'), (True, ['foo_u', 'foo_r', 'foo_t', 's0']))
Пример #8
0
    def test_module_utils_basic_safe_eval(self):
        from ansible.module_utils import basic

        args = json.dumps(
            dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={}))

        with swap_stdin_and_argv(stdin_data=args):
            reload(basic)
            am = basic.AnsibleModule(argument_spec=dict(), )

            # test some basic usage
            # string (and with exceptions included), integer, bool
            self.assertEqual(am.safe_eval("'a'"), 'a')
            self.assertEqual(am.safe_eval("'a'", include_exceptions=True),
                             ('a', None))
            self.assertEqual(am.safe_eval("1"), 1)
            self.assertEqual(am.safe_eval("True"), True)
            self.assertEqual(am.safe_eval("False"), False)
            self.assertEqual(am.safe_eval("{}"), {})
            # not passing in a string to convert
            self.assertEqual(am.safe_eval({'a': 1}), {'a': 1})
            self.assertEqual(am.safe_eval({'a': 1}, include_exceptions=True),
                             ({
                                 'a': 1
                             }, None))
            # invalid literal eval
            self.assertEqual(am.safe_eval("a=1"), "a=1")
            res = am.safe_eval("a=1", include_exceptions=True)
            self.assertEqual(res[0], "a=1")
            self.assertEqual(type(res[1]), SyntaxError)
            self.assertEqual(am.safe_eval("a.foo()"), "a.foo()")
            res = am.safe_eval("a.foo()", include_exceptions=True)
            self.assertEqual(res[0], "a.foo()")
            self.assertEqual(res[1], None)
            self.assertEqual(am.safe_eval("import foo"), "import foo")
            res = am.safe_eval("import foo", include_exceptions=True)
            self.assertEqual(res[0], "import foo")
            self.assertEqual(res[1], None)
            self.assertEqual(am.safe_eval("__import__('foo')"),
                             "__import__('foo')")
            res = am.safe_eval("__import__('foo')", include_exceptions=True)
            self.assertEqual(res[0], "__import__('foo')")
            self.assertEqual(type(res[1]), ValueError)
Пример #9
0
    def test_module_utils_basic_ansible_module_selinux_mls_enabled(self):
        from ansible.module_utils import basic
        basic._ANSIBLE_ARGS = None

        am = basic.AnsibleModule(
            argument_spec=dict(),
        )

        basic.HAVE_SELINUX = False
        self.assertEqual(am.selinux_mls_enabled(), False)

        basic.HAVE_SELINUX = True
        basic.selinux = Mock()
        with patch.dict('sys.modules', {'selinux': basic.selinux}):
            with patch('selinux.is_selinux_mls_enabled', return_value=0):
                self.assertEqual(am.selinux_mls_enabled(), False)
            with patch('selinux.is_selinux_mls_enabled', return_value=1):
                self.assertEqual(am.selinux_mls_enabled(), True)
        delattr(basic, 'selinux')
Пример #10
0
    def test_exit_json_removes_values(self):
        self.maxDiff = None
        for args, return_val, expected in self.dataset:
            params = dict(ANSIBLE_MODULE_ARGS=args)
            params = json.dumps(params)

            with swap_stdin_and_argv(stdin_data=params):
                with swap_stdout():
                    basic._ANSIBLE_ARGS = None
                    module = basic.AnsibleModule(
                        argument_spec=dict(
                            username=dict(),
                            password=dict(no_log=True),
                            token=dict(no_log=True),
                        ),
                    )
                    with self.assertRaises(SystemExit) as ctx:
                        self.assertEquals(module.exit_json(**return_val), expected)
                    self.assertEquals(json.loads(sys.stdout.getvalue()), expected)
Пример #11
0
    def setUp(self):
        self.complex_args_token = basic.MODULE_COMPLEX_ARGS
        basic.MODULE_COMPLEX_ARGS = '{}'
        self.am = basic.AnsibleModule(
            argument_spec = dict(),
        )

        self.has_journal = basic.has_journal
        basic.has_journal = True
        self.module_patcher = None

        # In case systemd-python is not installed
        if not self.has_journal:
            self.module_patcher = patch.dict('sys.modules', {'systemd': MagicMock(), 'systemd.journal': MagicMock()})
            self.module_patcher.start()
            try:
                reload(basic)
            except NameError:
                self._fake_out_reload(basic)
Пример #12
0
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update({
        "hostname": {
            "required": True,
            "type": "str"
        },
        "username": {
            "required": True,
            "type": "str"
        },
        "password": {
            "required": True,
            "type": "str",
            "no_log": True
        },
        "datacenter": {
            "required": True,
            "type": "str"
        },
        "cluster": {
            "required": True,
            "type": "str"
        },
        "folder": {
            "required": True,
            "type": "str"
        },
        "state": {
            "default": "present",
            "choices": ["present", "absent"],
            "type": "str",
        },
    })

    module = basic.AnsibleModule(argument_spec=argument_spec,
                                 supports_check_mode=True)

    if not HAS_PYVMOMI:
        module.fail_json(msg='pyvmomi is required for this module')

    vmware_folder = VMwareFolder(module)
    vmware_folder.process_state()
Пример #13
0
    def resource_factory(cls):
        params = basic._load_params()
        storage_data = cls._pop_param(common.STORAGE_DATA)

        specs = {'resource': {'choices': list(cls.RESOURCES.keys())},
                 'provider': {'type': 'str', 'choices': ['cinderlib',
                                                         'cinderclient']},
                 'backend': {'type': 'str'}}

        resource = params.get('resource')
        resource_class = cls.RESOURCES.get(resource)
        if resource_class and resource_class.STATES:
            specs['state'] = {'choices': resource_class.STATES,
                              'default': resource_class.DEFAULT_STATE}

        module = basic.AnsibleModule(specs,
                                     check_invalid_arguments=False,
                                     supports_check_mode=False)
        resource = cls.RESOURCES[resource](module, storage_data)
        return resource
Пример #14
0
    def _validate(self, size_required=False, require_id=False, **kwargs):
        specs = self.module.argument_spec.copy()
        specs.update(name={'type': 'str'},
                     id={'type': 'str'},
                     size={
                         'type': 'int',
                         'required': size_required
                     },
                     host={
                         'type': 'str',
                         'default': ''
                     },
                     **kwargs)

        required_one_of = []
        if require_id:
            required_one_of.append(('name', 'id'))
        self.module = basic.AnsibleModule(specs,
                                          check_invalid_arguments=True,
                                          required_one_of=required_one_of)
Пример #15
0
def test_distribution_version(testcase):
    """tests the distribution parsing code of the Facts class

    testsets have
    * a name (for output/debugging only)
    * input files that are faked
      * those should be complete and also include "irrelevant" files that might be mistaken as coming from other distributions
      * all files that are not listed here are assumed to not exist at all
    * the output of pythons platform.dist()
    * results for the ansible variables distribution* and os_family
    """

    from ansible.module_utils import basic

    args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
    with swap_stdin_and_argv(stdin_data=args):
        basic._ANSIBLE_ARGS = None
        module = basic.AnsibleModule(argument_spec=dict())

        _test_one_distribution(facts, module, testcase)
    def test_set_cwd(self, monkeypatch):
        '''make sure /tmp is used'''
        def mock_getcwd():
            return '/tmp'

        def mock_access(path, perm):
            return True

        def mock_chdir(path):
            pass

        monkeypatch.setattr(os, 'getcwd', mock_getcwd)
        monkeypatch.setattr(os, 'access', mock_access)
        monkeypatch.setattr(basic, '_ANSIBLE_ARGS',
                            to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': {}})))
        with patch('time.time', return_value=42):
            am = basic.AnsibleModule(argument_spec={})

        result = am._set_cwd()
        assert result == '/tmp'
Пример #17
0
    def test_module_utils_basic_ansible_module_selinux_default_context(self):
        from ansible.module_utils import basic

        basic.MODULE_COMPLEX_ARGS = '{}'
        basic.MODULE_CONSTANTS = '{}'
        am = basic.AnsibleModule(argument_spec=dict(), )

        am.selinux_initial_context = MagicMock(
            return_value=[None, None, None, None])
        am.selinux_enabled = MagicMock(return_value=True)

        # we first test the cases where the python selinux lib is not installed
        basic.HAVE_SELINUX = False
        self.assertEqual(am.selinux_default_context(path='/foo/bar'),
                         [None, None, None, None])

        # all following tests assume the python selinux bindings are installed
        basic.HAVE_SELINUX = True

        basic.selinux = Mock()

        with patch.dict('sys.modules', {'selinux': basic.selinux}):
            # next, we test with a mocked implementation of selinux.matchpathcon to simulate
            # an actual context being found
            with patch('selinux.matchpathcon',
                       return_value=[0, 'unconfined_u:object_r:default_t:s0']):
                self.assertEqual(
                    am.selinux_default_context(path='/foo/bar'),
                    ['unconfined_u', 'object_r', 'default_t', 's0'])

            # we also test the case where matchpathcon returned a failure
            with patch('selinux.matchpathcon', return_value=[-1, '']):
                self.assertEqual(am.selinux_default_context(path='/foo/bar'),
                                 [None, None, None, None])

            # finally, we test where an OSError occurred during matchpathcon's call
            with patch('selinux.matchpathcon', side_effect=OSError):
                self.assertEqual(am.selinux_default_context(path='/foo/bar'),
                                 [None, None, None, None])

        delattr(basic, 'selinux')
Пример #18
0
 def test_exit_json_removes_values(self):
     self.maxDiff = None
     for args, return_val, expected in self.dataset:
         sys.stdout = BytesIO()
         params = dict(ANSIBLE_MODULE_ARGS=args, ANSIBLE_MODULE_CONSTANTS={})
         params = json.dumps(params)
         if PY3:
             sys.stdin = StringIO(params)
             sys.stdin.buffer = BytesIO(to_bytes(params))
         else:
             sys.stdin = BytesIO(to_bytes(params))
         module = basic.AnsibleModule(
             argument_spec = dict(
                 username=dict(),
                 password=dict(no_log=True),
                 token=dict(no_log=True),
                 ),
             )
         with self.assertRaises(SystemExit) as ctx:
             self.assertEquals(module.exit_json(**return_val), expected)
         self.assertEquals(json.loads(sys.stdout.getvalue()), expected)
Пример #19
0
 def test_fail_json_removes_values(self):
     self.maxDiff = None
     for args, return_val, expected in self.dataset:
         expected = copy.deepcopy(expected)
         del expected['changed']
         expected['failed'] = True
         params = dict(ANSIBLE_MODULE_ARGS=args,
                       ANSIBLE_MODULE_CONSTANTS={})
         params = json.dumps(params)
         with swap_stdin_and_argv(stdin_data=params):
             with swap_stdout():
                 module = basic.AnsibleModule(argument_spec=dict(
                     username=dict(),
                     password=dict(no_log=True),
                     token=dict(no_log=True),
                 ), )
                 with self.assertRaises(SystemExit) as ctx:
                     self.assertEquals(module.fail_json(**return_val),
                                       expected)
                 self.assertEquals(json.loads(sys.stdout.getvalue()),
                                   expected)
def main():
    consumer_config = {common.CONSUMER_CONFIG: {'type': 'dict'}}
    module = basic.AnsibleModule(
        argument_spec={
            'resource': {
                'required': True,
                'choices': ('node', 'volume')
            },
            common.STORAGE_DATA: {
                'type': 'dict',
                'options': consumer_config
            },
        },
        supports_check_mode=False,
        check_invalid_arguments=False,
    )

    _set_priv_helper('sudo')

    method = globals()[module.params['resource']]
    module.exit_json(**method(module))
Пример #21
0
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        dict(datacenter=dict(required=True, type='str'),
             cluster=dict(required=True, type='str'),
             folder=dict(required=True, type='str'),
             hostname=dict(required=True, type='str'),
             username=dict(required=True, type='str'),
             password=dict(required=True, type='str', no_log=True),
             state=dict(default='present',
                        choices=['present', 'absent'],
                        type='str')))

    module = basic.AnsibleModule(argument_spec=argument_spec,
                                 supports_check_mode=True)

    if not HAS_PYVMOMI:
        module.fail_json(msg='pyvmomi is required for this module')

    vmware_folder = VMwareFolder(module)
    vmware_folder.process_state()
Пример #22
0
    def test_module_utils_basic_ansible_module_is_special_selinux_path(self):
        from ansible.module_utils import basic

        basic.MODULE_COMPLEX_ARGS = '{}'
        basic.SELINUX_SPECIAL_FS = 'nfs,nfsd,foos'
        am = basic.AnsibleModule(
            argument_spec = dict(),
        )

        def _mock_find_mount_point(path):
            if path.startswith('/some/path'):
                return '/some/path'
            elif path.startswith('/weird/random/fstype'):
                return '/weird/random/fstype'
            return '/'

        am.find_mount_point = MagicMock(side_effect=_mock_find_mount_point)
        am.selinux_context = MagicMock(return_value=['foo_u', 'foo_r', 'foo_t', 's0'])

        m = mock_open()
        m.side_effect = OSError

        with patch('__builtin__.open', m, create=True):
            self.assertEqual(am.is_special_selinux_path('/some/path/that/should/be/nfs'), (False, None))

        mount_data = [
            '/dev/disk1 / ext4 rw,seclabel,relatime,data=ordered 0 0\n',
            '1.1.1.1:/path/to/nfs /some/path nfs ro 0 0\n',
            'whatever /weird/random/fstype foos rw 0 0\n',
        ]

        # mock_open has a broken readlines() implementation apparently...
        # this should work by default but doesn't, so we fix it
        m = mock_open(read_data=''.join(mount_data))
        m.return_value.readlines.return_value = mount_data

        with patch('__builtin__.open', m, create=True):
            self.assertEqual(am.is_special_selinux_path('/some/random/path'), (False, None))
            self.assertEqual(am.is_special_selinux_path('/some/path/that/should/be/nfs'), (True, ['foo_u', 'foo_r', 'foo_t', 's0']))
            self.assertEqual(am.is_special_selinux_path('/weird/random/fstype/path'), (True, ['foo_u', 'foo_r', 'foo_t', 's0']))
    def run(self, tmp=None, task_vars=None):
        ''' handler for cli operations '''

        if task_vars is None:
            task_vars = dict()

        result = super(ActionModule, self).run(tmp, task_vars)
        del tmp  # tmp no longer has any effect

        try:
            spec = self._task.args['spec']
        except KeyError as exc:
            raise AnsibleModuleError(to_text(exc))

        if not spec:
            raise AnsibleModuleError('missing required argument: spec')

        spec_fp = os.path.join(task_vars['role_path'], 'meta/%s' % spec)
        display.vvv('using role spec %s' % spec_fp)
        spec = self._loader.load_from_file(spec_fp)

        argument_spec = spec.get('argument_spec') or {}

        args = {}
        self._handle_options(task_vars, args, argument_spec)

        basic._ANSIBLE_ARGS = to_bytes(
            json.dumps({'ANSIBLE_MODULE_ARGS': args}))
        basic.AnsibleModule.fail_json = self.fail_json

        spec = dict([(k, v) for k, v in iteritems(spec)
                     if k in self.VALID_MODULE_KWARGS])
        validated_spec = basic.AnsibleModule(**spec)

        result['role_params'] = validated_spec.params
        result['changed'] = False
        self._remove_tmp_path(self._connection._shell.tmpdir)

        return result
    def test_set_cwd_unreadable_use_gettempdir(self, monkeypatch):
        '''fallback to tempfile.gettempdir'''

        thisdir = None

        def mock_getcwd():
            return '/tmp'

        def mock_access(path, perm):
            if path in ['/tmp', '/tmp2', '/home/foobar'] and perm == 4:
                return False
            return True

        def mock_expandvars(var):
            if var == '$HOME':
                return '/home/foobar'
            return var

        def mock_gettempdir():
            return '/tmp3'

        def mock_chdir(path):
            if path == '/tmp':
                raise Exception()
            thisdir = path

        monkeypatch.setattr(os, 'getcwd', mock_getcwd)
        monkeypatch.setattr(os, 'chdir', mock_chdir)
        monkeypatch.setattr(os, 'access', mock_access)
        monkeypatch.setattr(os.path, 'expandvars', mock_expandvars)
        monkeypatch.setattr(basic, '_ANSIBLE_ARGS',
                            to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': {}})))
        with patch('time.time', return_value=42):
            am = basic.AnsibleModule(argument_spec={})

        am._tmpdir = '/tmp2'
        monkeypatch.setattr(tempfile, 'gettempdir', mock_gettempdir)
        result = am._set_cwd()
        assert result == '/tmp3'
Пример #25
0
    def test_module_utils_basic_ansible_module__symbolic_mode_to_octal(self):

        from ansible.module_utils import basic
        basic._ANSIBLE_ARGS = None

        am = basic.AnsibleModule(
            argument_spec = dict(),
        )

        mock_stat = MagicMock()

        # FIXME: trying many more combinations here would be good
        # directory, give full perms to all, then one group at a time
        mock_stat.st_mode = 0o040000
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'a+rwx'), 0o0777)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'u+rwx,g+rwx,o+rwx'), 0o0777)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'o+rwx'), 0o0007)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'g+rwx'), 0o0070)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'u+rwx'), 0o0700)

        # same as above, but in reverse so removing permissions
        mock_stat.st_mode = 0o040777
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'a-rwx'), 0o0000)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'u-rwx,g-rwx,o-rwx'), 0o0000)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'o-rwx'), 0o0770)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'g-rwx'), 0o0707)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'u-rwx'), 0o0077)

        # now using absolute assignment
        mock_stat.st_mode = 0o040000
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'a=rwx'), 0o0777)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'u=rwx,g=rwx,o=rwx'), 0o0777)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'o=rwx'), 0o0007)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'g=rwx'), 0o0070)
        self.assertEqual(am._symbolic_mode_to_octal(mock_stat, 'u=rwx'), 0o0700)

        # invalid modes
        mock_stat.st_mode = 0o0400000
        self.assertRaises(ValueError, am._symbolic_mode_to_octal, mock_stat, 'a=foo')
Пример #26
0
    def test_module_utils_basic_safe_eval(self):
        from ansible.module_utils import basic

        basic.MODULE_COMPLEX_ARGS = '{}'
        am = basic.AnsibleModule(argument_spec=dict(), )

        # test some basic usage
        # string (and with exceptions included), integer, bool
        self.assertEqual(am.safe_eval("'a'"), 'a')
        self.assertEqual(am.safe_eval("'a'", include_exceptions=True),
                         ('a', None))
        self.assertEqual(am.safe_eval("1"), 1)
        self.assertEqual(am.safe_eval("True"), True)
        self.assertEqual(am.safe_eval("False"), False)
        self.assertEqual(am.safe_eval("{}"), {})
        # not passing in a string to convert
        self.assertEqual(am.safe_eval({'a': 1}), {'a': 1})
        self.assertEqual(am.safe_eval({'a': 1}, include_exceptions=True),
                         ({
                             'a': 1
                         }, None))
        # invalid literal eval
        self.assertEqual(am.safe_eval("a=1"), "a=1")
        res = am.safe_eval("a=1", include_exceptions=True)
        self.assertEqual(res[0], "a=1")
        self.assertEqual(type(res[1]), SyntaxError)
        self.assertEqual(am.safe_eval("a.foo()"), "a.foo()")
        res = am.safe_eval("a.foo()", include_exceptions=True)
        self.assertEqual(res[0], "a.foo()")
        self.assertEqual(res[1], None)
        self.assertEqual(am.safe_eval("import foo"), "import foo")
        res = am.safe_eval("import foo", include_exceptions=True)
        self.assertEqual(res[0], "import foo")
        self.assertEqual(res[1], None)
        self.assertEqual(am.safe_eval("__import__('foo')"),
                         "__import__('foo')")
        res = am.safe_eval("__import__('foo')", include_exceptions=True)
        self.assertEqual(res[0], "__import__('foo')")
        self.assertEqual(type(res[1]), ValueError)
Пример #27
0
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update({
        "hostname": {"required": True, "type": "str"},
        "username": {"required": True, "type": "str"},
        "password": {"required": True, "type": "str", "no_log": True},
        "datacenter": {"required": True, "type": "str"},
        "cluster": {"required": True, "type": "str"},
        "resource_pool": {"required": True, "type": "str"},
        "mem_shares": {
            "type": "str", "default": "normal",
            "choices": ["high", "custom", "normal", "low"],
        },
        "mem_limit": {"type": "int", "default": "-1"},
        "mem_reservation": {"type": "int", "default": "0"},
        "mem_expandable_reservations": {"type": "bool", "default": "True"},
        "cpu_shares": {
            "type": "str", "default": "normal",
            "choices": ["high", "custom", "normal", "low"]
        },
        "cpu_limit": {"type": "int", "default": "-1"},
        "cpu_reservation": {"type": "int", "default": "0"},
        "cpu_expandable_reservations": {"type": "bool", "default": "True"},
        "state": {
            "default": "present",
            "choices": ["present", "absent"],
            "type": "str",
        },
    })

    module = basic.AnsibleModule(
        argument_spec=argument_spec, supports_check_mode=True)

    if not HAS_PYVMOMI:
        module.fail_json(msg='pyvmomi is required for this module')

    vmware_rp = VMwareResourcePool(module)
    vmware_rp.process_state()
Пример #28
0
    def test_module_utils_basic_ansible_module_set_directory_attributes_if_different(self):
        from ansible.module_utils import basic
        basic._ANSIBLE_ARGS = None

        am = basic.AnsibleModule(
            argument_spec=dict(),
        )

        file_args = {
            'path': '/path/to/file',
            'mode': None,
            'owner': None,
            'group': None,
            'seuser': None,
            'serole': None,
            'setype': None,
            'selevel': None,
            'secontext': [None, None, None],
            'attributes': None,
        }

        self.assertEqual(am.set_directory_attributes_if_different(file_args, True), True)
        self.assertEqual(am.set_directory_attributes_if_different(file_args, False), False)
Пример #29
0
 def get_info_mock_object(self, kind=None):
     """
     Helper method to return an na_ontap_info object
     """
     argument_spec = netapp_utils.na_ontap_host_argument_spec()
     argument_spec.update(dict(
         state=dict(type='str', default='info', choices=['info']),
         gather_subset=dict(default=['all'], type='list'),
         vserver=dict(type='str', default=None, required=False),
         max_records=dict(type='int', default=1024, required=False)
     ))
     module = basic.AnsibleModule(
         argument_spec=argument_spec,
         supports_check_mode=True
     )
     max_records = module.params['max_records']
     obj = info_module(module, max_records)
     obj.netapp_info = dict()
     if kind is None:
         obj.server = MockONTAPConnection()
     else:
         obj.server = MockONTAPConnection(kind)
     return obj
Пример #30
0
def test_distribution_version():
    """tests the distribution parsing code of the Facts class

    testsets have
    * a name (for output/debugging only)
    * input files that are faked
      * those should be complete and also include "irrelevant" files that might be mistaken as coming from other distributions
      * all files that are not listed here are assumed to not exist at all
    * the output of pythons platform.dist()
    * results for the ansible variables distribution*
    """

    from ansible.module_utils import basic

    args = json.dumps(dict(ANSIBLE_MODULE_ARGS={}))
    with swap_stdin_and_argv(stdin_data=args):
        module = basic.AnsibleModule(argument_spec=dict())

        for t in TESTSETS:
            # run individual tests via generator
            # set nicer stdout output for nosetest
            _test_one_distribution.description = "check distribution_version for %s" % t['name']
            yield _test_one_distribution, facts, module, t