def lang_env(module):

    if not hasattr(lang_env, 'result'):
        locale = get_best_parsable_locale(module)
        lang_env.result = dict(LANG=locale, LC_ALL=locale, LC_MESSAGES=locale)

    return lang_env.result
Exemple #2
0
def main():
    module = AnsibleModule(argument_spec=dict(), supports_check_mode=True)
    locale = get_best_parsable_locale(module)
    module.run_command_environ_update = dict(LANG=locale, LC_ALL=locale)
    service_modules = (ServiceScanService, SystemctlScanService,
                       AIXScanService, OpenBSDScanService)
    all_services = {}
    incomplete_warning = False
    for svc_module in service_modules:
        svcmod = svc_module(module)
        svc = svcmod.gather_services()
        if svc is not None:
            all_services.update(svc)
            if svcmod.incomplete_warning:
                incomplete_warning = True
    if len(all_services) == 0:
        results = dict(
            skipped=True,
            msg=
            "Failed to find any services. Sometimes this is due to insufficient privileges."
        )
    else:
        results = dict(ansible_facts=dict(services=all_services))
        if incomplete_warning:
            results[
                'msg'] = "WARNING: Could not find status for all services. Sometimes this is due to insufficient privileges."
    module.exit_json(**results)
Exemple #3
0
    def is_unarchived(self):
        cmd = [self.cmd_path, '--diff', '-C', self.b_dest]
        if self.zipflag:
            cmd.append(self.zipflag)
        if self.opts:
            cmd.extend(['--show-transformed-names'] + self.opts)
        if self.file_args['owner']:
            cmd.append('--owner=' + quote(self.file_args['owner']))
        if self.file_args['group']:
            cmd.append('--group=' + quote(self.file_args['group']))
        if self.module.params['keep_newer']:
            cmd.append('--keep-newer-files')
        if self.excludes:
            cmd.extend(['--exclude=' + f for f in self.excludes])
        cmd.extend(['-f', self.src])
        if self.include_files:
            cmd.extend(self.include_files)
        locale = get_best_parsable_locale(self.module)
        rc, out, err = self.module.run_command(cmd,
                                               cwd=self.b_dest,
                                               environ_update=dict(
                                                   LANG=locale,
                                                   LC_ALL=locale,
                                                   LC_MESSAGES=locale))

        # Check whether the differences are in something that we're
        # setting anyway

        # What is different
        unarchived = True
        old_out = out
        out = ''
        run_uid = os.getuid()
        # When unarchiving as a user, or when owner/group/mode is supplied --diff is insufficient
        # Only way to be sure is to check request with what is on disk (as we do for zip)
        # Leave this up to set_fs_attributes_if_different() instead of inducing a (false) change
        for line in old_out.splitlines() + err.splitlines():
            # FIXME: Remove the bogus lines from error-output as well !
            # Ignore bogus errors on empty filenames (when using --split-component)
            if EMPTY_FILE_RE.search(line):
                continue
            if run_uid == 0 and not self.file_args[
                    'owner'] and OWNER_DIFF_RE.search(line):
                out += line + '\n'
            if run_uid == 0 and not self.file_args[
                    'group'] and GROUP_DIFF_RE.search(line):
                out += line + '\n'
            if not self.file_args['mode'] and MODE_DIFF_RE.search(line):
                out += line + '\n'
            if MOD_TIME_DIFF_RE.search(line):
                out += line + '\n'
            if MISSING_FILE_RE.search(line):
                out += line + '\n'
            if INVALID_OWNER_RE.search(line):
                out += line + '\n'
            if INVALID_GROUP_RE.search(line):
                out += line + '\n'
        if out:
            unarchived = False
        return dict(unarchived=unarchived, rc=rc, out=out, err=err, cmd=cmd)
Exemple #4
0
    def populate(self, collected_facts=None):
        hardware_facts = {}
        locale = get_best_parsable_locale(self.module)
        self.module.run_command_environ_update = {
            'LANG': locale,
            'LC_ALL': locale,
            'LC_NUMERIC': locale
        }

        cpu_facts = self.get_cpu_facts(collected_facts=collected_facts)
        memory_facts = self.get_memory_facts()
        dmi_facts = self.get_dmi_facts()
        device_facts = self.get_device_facts()
        uptime_facts = self.get_uptime_facts()
        lvm_facts = self.get_lvm_facts()

        mount_facts = {}
        try:
            mount_facts = self.get_mount_facts()
        except timeout.TimeoutError:
            self.module.warn("No mount facts were gathered due to timeout.")

        hardware_facts.update(cpu_facts)
        hardware_facts.update(memory_facts)
        hardware_facts.update(dmi_facts)
        hardware_facts.update(device_facts)
        hardware_facts.update(uptime_facts)
        hardware_facts.update(lvm_facts)
        hardware_facts.update(mount_facts)

        return hardware_facts
Exemple #5
0
 def unarchive(self):
     cmd = [self.cmd_path, '--extract', '-C', self.b_dest]
     if self.zipflag:
         cmd.append(self.zipflag)
     if self.opts:
         cmd.extend(['--show-transformed-names'] + self.opts)
     if self.file_args['owner']:
         cmd.append('--owner=' + quote(self.file_args['owner']))
     if self.file_args['group']:
         cmd.append('--group=' + quote(self.file_args['group']))
     if self.module.params['keep_newer']:
         cmd.append('--keep-newer-files')
     if self.excludes:
         cmd.extend(['--exclude=' + f for f in self.excludes])
     cmd.extend(['-f', self.src])
     if self.include_files:
         cmd.extend(self.include_files)
     locale = get_best_parsable_locale(self.module)
     rc, out, err = self.module.run_command(cmd,
                                            cwd=self.b_dest,
                                            environ_update=dict(
                                                LANG=locale,
                                                LC_ALL=locale,
                                                LC_MESSAGES=locale,
                                                LANGUAGE=locale))
     return dict(cmd=cmd, rc=rc, out=out, err=err)
 def list_installed(self):
     locale = get_best_parsable_locale(module)
     rc, out, err = module.run_command([self._cli, '-Qi'],
                                       environ_update=dict(LC_ALL=locale))
     if rc != 0 or err:
         raise Exception("Unable to list packages rc=%s : %s" % (rc, err))
     return out.split("\n\n")[:-1]
Exemple #7
0
    def populate(self, collected_facts=None):
        hardware_facts = {}

        # FIXME: could pass to run_command(environ_update), but it also tweaks the env
        #        of the parent process instead of altering an env provided to Popen()
        # Use C locale for hardware collection helpers to avoid locale specific number formatting (#24542)
        locale = get_best_parsable_locale(self.module)
        self.module.run_command_environ_update = {
            'LANG': locale,
            'LC_ALL': locale,
            'LC_NUMERIC': locale
        }

        cpu_facts = self.get_cpu_facts()
        memory_facts = self.get_memory_facts()
        dmi_facts = self.get_dmi_facts()
        device_facts = self.get_device_facts()
        uptime_facts = self.get_uptime_facts()

        mount_facts = {}
        try:
            mount_facts = self.get_mount_facts()
        except timeout.TimeoutError:
            pass

        hardware_facts.update(cpu_facts)
        hardware_facts.update(memory_facts)
        hardware_facts.update(dmi_facts)
        hardware_facts.update(device_facts)
        hardware_facts.update(uptime_facts)
        hardware_facts.update(mount_facts)

        return hardware_facts
Exemple #8
0
def clear_facls(path):
    setfacl = get_bin_path('setfacl')
    # FIXME "setfacl -b" is available on Linux and FreeBSD. There is "setfacl -D e" on z/OS. Others?
    acl_command = [setfacl, '-b', path]
    b_acl_command = [to_bytes(x) for x in acl_command]
    locale = get_best_parsable_locale(module)
    rc, out, err = module.run_command(b_acl_command, environ_update=dict(LANG=locale, LC_ALL=locale, LC_MESSAGES=locale))
    if rc != 0:
        raise RuntimeError('Error running "{0}": stdout: "{1}"; stderr: "{2}"'.format(' '.join(b_acl_command), out, err))
Exemple #9
0
    def files_in_archive(self):
        if self._files_in_archive:
            return self._files_in_archive

        cmd = [self.cmd_path, '--list', '-C', self.b_dest]
        if self.zipflag:
            cmd.append(self.zipflag)
        if self.opts:
            cmd.extend(['--show-transformed-names'] + self.opts)
        if self.excludes:
            cmd.extend(['--exclude=' + f for f in self.excludes])
        cmd.extend(['-f', self.src])
        if self.include_files:
            cmd.extend(self.include_files)

        locale = get_best_parsable_locale(self.module)
        rc, out, err = self.module.run_command(cmd,
                                               cwd=self.b_dest,
                                               environ_update=dict(
                                                   LANG=locale,
                                                   LC_ALL=locale,
                                                   LC_MESSAGES=locale,
                                                   LANGUAGE=locale))
        if rc != 0:
            raise UnarchiveError('Unable to list files in the archive: %s' %
                                 err)

        for filename in out.splitlines():
            # Compensate for locale-related problems in gtar output (octal unicode representation) #11348
            # filename = filename.decode('string_escape')
            filename = to_native(codecs.escape_decode(filename)[0])

            # We don't allow absolute filenames.  If the user wants to unarchive rooted in "/"
            # they need to use "dest: '/'".  This follows the defaults for gtar, pax, etc.
            # Allowing absolute filenames here also causes bugs: https://github.com/ansible/ansible/issues/21397
            if filename.startswith('/'):
                filename = filename[1:]

            exclude_flag = False
            if self.excludes:
                for exclude in self.excludes:
                    if fnmatch.fnmatch(filename, exclude):
                        exclude_flag = True
                        break

            if not exclude_flag:
                self._files_in_archive.append(to_native(filename))

        return self._files_in_archive
Exemple #10
0
def _get_packages(module, pip, chdir):
    '''Return results of pip command to get packages.'''
    # Try 'pip list' command first.
    command = pip + ['list', '--format=freeze']
    locale = get_best_parsable_locale(module)
    lang_env = {'LANG': locale, 'LC_ALL': locale, 'LC_MESSAGES': locale}
    rc, out, err = module.run_command(command, cwd=chdir, environ_update=lang_env)

    # If there was an error (pip version too old) then use 'pip freeze'.
    if rc != 0:
        command = pip + ['freeze']
        rc, out, err = module.run_command(command, cwd=chdir)
        if rc != 0:
            _fail(module, command, out, err)

    return ' '.join(command), out, err
def main():
    module = AnsibleModule(argument_spec=dict(), supports_check_mode=True)
    locale = get_best_parsable_locale(module)
    module.run_command_environ_update = dict(LANG=locale, LC_ALL=locale)
    service_modules = (ServiceScanService, SystemctlScanService,
                       AIXScanService, OpenBSDScanService)
    all_services = {}
    for svc_module in service_modules:
        svcmod = svc_module(module)
        svc = svcmod.gather_services()
        if svc:
            all_services.update(svc)
    if len(all_services) == 0:
        results = dict(
            skipped=True,
            msg=
            "Failed to find any services. This can be due to privileges or some other configuration issue."
        )
    else:
        results = dict(ansible_facts=dict(services=all_services))
    module.exit_json(**results)
 def test_finding_C_on_no_match(self):
     self.mock_module.run_command = MagicMock(return_value=(0, "fr_FR.UTF8\nMINE\n", ''))
     locale = get_best_parsable_locale(self.mock_module)
     assert locale == 'C'
 def test_finding_prefered(self):
     self.mock_module.run_command = MagicMock(return_value=(0, "es_ES.utf8\nMINE\nC\nPOSIX\n", ''))
     locale = get_best_parsable_locale(self.mock_module, preferences=['MINE', 'C.utf8'])
     assert locale == 'MINE'
 def test_finding_middle(self):
     self.mock_module.run_command = MagicMock(return_value=(0, "fr_FR.utf8\nen_US.utf8\nC\nPOSIX\n", ''))
     locale = get_best_parsable_locale(self.mock_module)
     assert locale == 'en_US.utf8'
def main():
    module = AnsibleModule(
        argument_spec=dict(
            dest=dict(type='path'),
            repo=dict(type='str',
                      required=True,
                      aliases=['name', 'repository']),
            revision=dict(type='str',
                          default='HEAD',
                          aliases=['rev', 'version']),
            force=dict(type='bool', default=False),
            username=dict(type='str'),
            password=dict(type='str', no_log=True),
            executable=dict(type='path'),
            export=dict(type='bool', default=False),
            checkout=dict(type='bool', default=True),
            update=dict(type='bool', default=True),
            switch=dict(type='bool', default=True),
            in_place=dict(type='bool', default=False),
            validate_certs=dict(type='bool', default=False),
        ),
        supports_check_mode=True,
    )

    dest = module.params['dest']
    repo = module.params['repo']
    revision = module.params['revision']
    force = module.params['force']
    username = module.params['username']
    password = module.params['password']
    svn_path = module.params['executable'] or module.get_bin_path('svn', True)
    export = module.params['export']
    switch = module.params['switch']
    checkout = module.params['checkout']
    update = module.params['update']
    in_place = module.params['in_place']
    validate_certs = module.params['validate_certs']

    # We screenscrape a huge amount of svn commands so use C locale anytime we
    # call run_command()
    locale = get_best_parsable_locale(module)
    module.run_command_environ_update = dict(LANG=locale, LC_MESSAGES=locale)

    if not dest and (checkout or update or export):
        module.fail_json(
            msg=
            "the destination directory must be specified unless checkout=no, update=no, and export=no"
        )

    svn = Subversion(module, dest, repo, revision, username, password,
                     svn_path, validate_certs)

    if not export and not update and not checkout:
        module.exit_json(changed=False, after=svn.get_remote_revision())
    if export or not os.path.exists(dest):
        before = None
        local_mods = False
        if module.check_mode:
            module.exit_json(changed=True)
        elif not export and not checkout:
            module.exit_json(changed=False)
        if not export and checkout:
            svn.checkout()
            files_changed = True
        else:
            svn.export(force=force)
            files_changed = True
    elif svn.is_svn_repo():
        # Order matters. Need to get local mods before switch to avoid false
        # positives. Need to switch before revert to ensure we are reverting to
        # correct repo.
        if not update:
            module.exit_json(changed=False)
        if module.check_mode:
            if svn.has_local_mods() and not force:
                module.fail_json(
                    msg="ERROR: modified files exist in the repository.")
            check, before, after = svn.needs_update()
            module.exit_json(changed=check, before=before, after=after)
        files_changed = False
        before = svn.get_revision()
        local_mods = svn.has_local_mods()
        if switch:
            files_changed = svn.switch() or files_changed
        if local_mods:
            if force:
                files_changed = svn.revert() or files_changed
            else:
                module.fail_json(
                    msg="ERROR: modified files exist in the repository.")
        files_changed = svn.update() or files_changed
    elif in_place:
        before = None
        svn.checkout(force=True)
        files_changed = True
        local_mods = svn.has_local_mods()
        if local_mods and force:
            svn.revert()
    else:
        module.fail_json(
            msg=
            "ERROR: %s folder already exists, but its not a subversion repository."
            % (dest, ))

    if export:
        module.exit_json(changed=True)
    else:
        after = svn.get_revision()
        changed = files_changed or local_mods
        module.exit_json(changed=changed, before=before, after=after)