Beispiel #1
0
    def run(self,
            conn,
            tmp,
            module_name,
            module_args,
            inject,
            complex_args=None,
            **kwargs):

        options = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))

        src = options.get('src', None)
        dest = options.get('dest', None)
        remote_src = utils.boolean(options.get('remote_src', 'no'))

        if src is None:
            result = dict(failed=True, msg="src is required")
            return ReturnData(conn=conn, comm_ok=False, result=result)

        if remote_src:
            return self.runner._execute_module(conn,
                                               tmp,
                                               'patch',
                                               module_args,
                                               inject=inject,
                                               complex_args=complex_args)

        # Source is local
        if '_original_file' in inject:
            src = utils.path_dwim_relative(inject['_original_file'], 'files',
                                           src, self.runner.basedir)
        else:
            src = utils.path_dwim(self.runner.basedir, src)

        if tmp is None or "-tmp-" not in tmp:
            tmp = self.runner._make_tmp_path(conn)

        tmp_src = conn.shell.join_path(tmp, os.path.basename(src))
        conn.put_file(src, tmp_src)

        if self.runner.become and self.runner.become_user != 'root':
            if not self.runner.noop_on_check(inject):
                self.runner._remote_chmod(conn, 'a+r', tmp_src, tmp)

        new_module_args = dict(src=tmp_src, )

        if self.runner.noop_on_check(inject):
            new_module_args['CHECKMODE'] = True

        module_args = utils.merge_module_args(module_args, new_module_args)

        return self.runner._execute_module(conn,
                                           tmp,
                                           'patch',
                                           module_args,
                                           inject=inject,
                                           complex_args=complex_args)
Beispiel #2
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        ''' handler for file transfer operations '''

        # load up options
        options = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))
        source  = options.get('src', None)
        dest    = options.get('dest', None)
        copy    = utils.boolean(options.get('copy', 'yes'))

        if source is None or dest is None:
            result = dict(failed=True, msg="src (or content) and dest are required")
            return ReturnData(conn=conn, result=result)

        dest = os.path.expanduser(dest) # CCTODO: Fix path for Windows hosts.
        source = template.template(self.runner.basedir, os.path.expanduser(source), inject)
        if copy:
            if '_original_file' in inject:
                source = utils.path_dwim_relative(inject['_original_file'], 'files', source, self.runner.basedir)
            else:
                source = utils.path_dwim(self.runner.basedir, source)

        remote_md5 = self.runner._remote_md5(conn, tmp, dest)
        if remote_md5 != '3':
            result = dict(failed=True, msg="dest '%s' must be an existing dir" % dest)
            return ReturnData(conn=conn, result=result)

        if copy:
            # transfer the file to a remote tmp location
            tmp_src = tmp + 'source'
            conn.put_file(source, tmp_src)

        # handle diff mode client side
        # handle check mode client side
        # fix file permissions when the copy is done as a different user
        if copy:
            if self.runner.sudo and self.runner.sudo_user != 'root' or self.runner.su and self.runner.su_user != 'root':
                if not self.runner.noop_on_check(inject):
                    self.runner._remote_chmod(conn, 'a+r', tmp_src, tmp)
            # Build temporary module_args.
            new_module_args = dict(
                src=tmp_src,
                original_basename=os.path.basename(source),
            )

            # make sure checkmod is passed on correctly
            if self.runner.noop_on_check(inject):
                new_module_args['CHECKMODE'] = True

            module_args = utils.merge_module_args(module_args, new_module_args)
        else:
            module_args = "%s original_basename=%s" % (module_args, pipes.quote(os.path.basename(source)))
            # make sure checkmod is passed on correctly
            if self.runner.noop_on_check(inject):
                module_args += " CHECKMODE=True"
        return self.runner._execute_module(conn, tmp, 'unarchive', module_args, inject=inject, complex_args=complex_args)
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        """Run the method"""
        if not self.runner.is_playbook:
            raise errors.AnsibleError("FAILED: `config_templates` are only available in playbooks")

        options = self.grab_options(complex_args, module_args)
        try:
            source = options["src"]
            dest = options["dest"]

            config_overrides = options.get("config_overrides", dict())
            config_type = options["config_type"]
            assert config_type.lower() in ["ini", "json", "yaml"]
        except KeyError as exp:
            result = dict(failed=True, msg=exp)
            return ReturnData(conn=conn, comm_ok=False, result=result)

        source_template = template.template(self.runner.basedir, source, inject)

        if "_original_file" in inject:
            source_file = utils.path_dwim_relative(
                inject["_original_file"], "templates", source_template, self.runner.basedir
            )
        else:
            source_file = utils.path_dwim(self.runner.basedir, source_template)

        # Open the template file and return the data as a string. This is
        #  being done here so that the file can be a vault encrypted file.
        resultant = template.template_from_file(
            self.runner.basedir, source_file, inject, vault_password=self.runner.vault_pass
        )

        if config_overrides:
            type_merger = getattr(self, CONFIG_TYPES.get(config_type))
            resultant = type_merger(config_overrides=config_overrides, resultant=resultant)

        # Retemplate the resultant object as it may have new data within it
        #  as provided by an override variable.
        template.template_from_string(basedir=self.runner.basedir, data=resultant, vars=inject, fail_on_undefined=True)

        # Access to protected method is unavoidable in Ansible 1.x.
        new_module_args = dict(
            src=self.runner._transfer_str(conn, tmp, "source", resultant),
            dest=dest,
            original_basename=os.path.basename(source),
            follow=True,
        )

        module_args_tmp = utils.merge_module_args(module_args, new_module_args)

        # Remove data types that are not available to the copy module
        complex_args.pop("config_overrides")
        complex_args.pop("config_type")

        # Return the copy module status. Access to protected method is
        #  unavoidable in Ansible 1.x.
        return self.runner._execute_module(conn, tmp, "copy", module_args_tmp, inject=inject, complex_args=complex_args)
Beispiel #4
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        ''' handler for file transfer operations '''

        # load up options
        options = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))
        source  = options.get('src', None)
        dest    = options.get('dest', None)
        copy    = utils.boolean(options.get('copy', 'yes'))

        if source is None or dest is None:
            result = dict(failed=True, msg="src (or content) and dest are required")
            return ReturnData(conn=conn, result=result)

        dest = os.path.expanduser(dest) # CCTODO: Fix path for Windows hosts.
        source = template.template(self.runner.basedir, os.path.expanduser(source), inject)
        if copy:
            if '_original_file' in inject:
                source = utils.path_dwim_relative(inject['_original_file'], 'files', source, self.runner.basedir)
            else:
                source = utils.path_dwim(self.runner.basedir, source)

        remote_md5 = self.runner._remote_md5(conn, tmp, dest)
        if remote_md5 != '3':
            result = dict(failed=True, msg="dest '%s' must be an existing dir" % dest)
            return ReturnData(conn=conn, result=result)

        if copy:
            # transfer the file to a remote tmp location
            tmp_src = tmp + 'source'
            conn.put_file(source, tmp_src)

        # handle diff mode client side
        # handle check mode client side
        # fix file permissions when the copy is done as a different user
        if copy:
            if self.runner.sudo and self.runner.sudo_user != 'root' or self.runner.su and self.runner.su_user != 'root':
                self.runner._remote_chmod(conn, 'a+r', tmp_src, tmp)
            # Build temporary module_args.
            new_module_args = dict(
                src=tmp_src,
                original_basename=os.path.basename(source),
            )
            module_args = utils.merge_module_args(module_args, new_module_args)
        else:
            module_args = "%s original_basename=%s" % (module_args, pipes.quote(os.path.basename(source)))
        return self.runner._execute_module(conn, tmp, 'unarchive', module_args, inject=inject, complex_args=complex_args)
Beispiel #5
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):

        options  = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))

        src = options.get('src', None)
        dest = options.get('dest', None)
        remote_src = utils.boolean(options.get('remote_src', 'no'))

        if src is None:
            result = dict(failed=True, msg="src is required")
            return ReturnData(conn=conn, comm_ok=False, result=result)

        if remote_src:
            return self.runner._execute_module(conn, tmp, 'patch', module_args, inject=inject, complex_args=complex_args)

        # Source is local
        if '_original_file' in inject:
            src = utils.path_dwim_relative(inject['_original_file'], 'files', src, self.runner.basedir)
        else:
            src = utils.path_dwim(self.runner.basedir, src)

        tmp_path = self.runner._make_tmp_path(conn)
        tmp_src = tmp_path + 'patch_source'
        conn.put_file(src, tmp_src)

        if self.runner.become and self.runner.become_user != 'root':
            if not self.runner.noop_on_check(inject):
                self.runner._remote_chmod(conn, 'a+r', tmp_src, tmp_path)

        new_module_args = dict(
            src=tmp_src,
        )

        if self.runner.noop_on_check(inject):
            new_module_args['CHECKMODE'] = True

        module_args = utils.merge_module_args(module_args, new_module_args)

        data = self.runner._execute_module(conn, tmp, 'patch', module_args, inject=inject, complex_args=complex_args)
        if not C.DEFAULT_KEEP_REMOTE_FILES:
            self.runner._remove_tmp_path(conn, tmp_path)

        return data
Beispiel #6
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):

        options = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))

        src = options.get("src", None)
        dest = options.get("dest", None)
        remote_src = utils.boolean(options.get("remote_src", "no"))

        if src is None:
            result = dict(failed=True, msg="src is required")
            return ReturnData(conn=conn, comm_ok=False, result=result)

        if remote_src:
            return self.runner._execute_module(
                conn, tmp, "patch", module_args, inject=inject, complex_args=complex_args
            )

        # Source is local
        if "_original_file" in inject:
            src = utils.path_dwim_relative(inject["_original_file"], "files", src, self.runner.basedir)
        else:
            src = utils.path_dwim(self.runner.basedir, src)

        if tmp is None or "-tmp-" not in tmp:
            tmp = self.runner._make_tmp_path(conn)

        tmp_src = conn.shell.join_path(tmp, os.path.basename(src))
        conn.put_file(src, tmp_src)

        if self.runner.become and self.runner.become_user != "root":
            if not self.runner.noop_on_check(inject):
                self.runner._remote_chmod(conn, "a+r", tmp_src, tmp)

        new_module_args = dict(src=tmp_src)

        if self.runner.noop_on_check(inject):
            new_module_args["CHECKMODE"] = True

        module_args = utils.merge_module_args(module_args, new_module_args)

        return self.runner._execute_module(conn, tmp, "patch", module_args, inject=inject, complex_args=complex_args)
Beispiel #7
0
                if raw:
                    # Continue to next iteration if raw is defined.
                    continue

                # Run the copy module

                # src and dest here come after original and override them
                # we pass dest only to make sure it includes trailing slash in case of recursive copy
                new_module_args = dict(src=tmp_src,
                                       dest=dest,
                                       original_basename=source_rel)

                if self.runner.no_log:
                    new_module_args['NO_LOG'] = True

                module_args_tmp = utils.merge_module_args(
                    module_args, new_module_args)

                module_return = self.runner._execute_module(
                    conn,
                    tmp_path,
                    'copy',
                    module_args_tmp,
                    inject=inject,
                    complex_args=complex_args,
                    delete_remote_tmp=delete_remote_tmp)
                module_executed = True

            else:
                # no need to transfer the file, already correct md5, but still need to call
                # the file module in case we want to change attributes
                self._remove_tempfile_if_content_defined(
    def run(self, conn, tmp, module_name, module_args, inject,
            complex_args=None, **kwargs):

        if not self.runner.is_playbook:
            raise errors.AnsibleError("in current versions of ansible, "
                                      "aeriscloud_service is only usable "
                                      "in playbooks")

        # load up options
        options = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))

        res = self.create_aeriscloud_directory(conn, tmp, inject)
        if not res.is_successful():
            return res

        data = {
            'services': []
        }

        for service in options['services']:
            if 'when' in service \
                    and not utils.check_conditional(service['when'],
                                                    self.runner.basedir,
                                                    inject):
                continue
            if 'path' in service and 'protocol' not in service:
                service['protocol'] = 'http'
            if 'path' not in service:
                service['path'] = ''
            if 'protocol' not in service:
                service['protocol'] = 'tcp'
            data['services'].append(service)

        template = jinja2.Template("""{%- for service in services -%}
{{ service['name'] }},{{ service['port'] }},{{ service['path'] }},{{ service['protocol'] }}
{% endfor %}""")

        resultant = template.render(data)

        dest = os.path.join('/etc/aeriscloud.d', options['name'])
        module_args = ''
        options = {
            'path': dest,
            'mode': 0644,
            'owner': 'root',
            'group': 'root',
            'state': 'file'
        }

        local_checksum = utils.checksum_s(resultant)
        remote_checksum = self.runner._remote_checksum(conn, tmp, dest, inject)

        if remote_checksum in ('0', '2', '3', '4'):
            # Note: 1 means the file is not present which is fine; template
            # will create it
            result = dict(failed=True, msg="failed to checksum remote file."
                                           " Checksum error code: %s" % remote_checksum)
            return ReturnData(conn=conn, comm_ok=True, result=result)

        if local_checksum != remote_checksum:

            # template is different from the remote value

            # if showing diffs, we need to get the remote value
            dest_contents = ''

            if self.runner.diff:
                # using persist_files to keep the temp directory around to avoid needing to grab another
                dest_result = self.runner._execute_module(conn, tmp, 'slurp',
                                                          "path=%s" % dest,
                                                          inject=inject,
                                                          persist_files=True)
                if 'content' in dest_result.result:
                    dest_contents = dest_result.result['content']
                    if dest_result.result['encoding'] == 'base64':
                        dest_contents = base64.b64decode(dest_contents)
                    else:
                        raise Exception(
                            "unknown encoding, failed: %s" % dest_result.result)

            xfered = self.runner._transfer_str(conn, tmp, 'source', resultant)

            # fix file permissions when the copy is done as a different user
            if self.runner.become and self.runner.become_user != 'root':
                self.runner._remote_chmod(conn, 'a+r', xfered, tmp)

            # run the copy module
            new_module_args = dict(
                src=xfered,
                dest=dest,
                follow=True,
            )
            module_args_tmp = utils.merge_module_args(module_args,
                                                      new_module_args)

            if self.runner.noop_on_check(inject):
                return ReturnData(conn=conn, comm_ok=True,
                                  result=dict(changed=True),
                                  diff=dict(before_header=dest,
                                            after_header='',
                                            before=dest_contents,
                                            after=resultant))
            else:
                res = self.runner._execute_module(conn, tmp, 'copy',
                                                  module_args_tmp,
                                                  inject=inject,
                                                  complex_args=None)
                if res.result.get('changed', False):
                    res.diff = dict(before=dest_contents, after=resultant)
                return res
        else:
            # when running the file module based on the template data, we do
            # not want the source filename (the name of the template) to be used,
            # since this would mess up links, so we clear the src param and tell
            # the module to follow links.  When doing that, we have to set
            # original_basename to the template just in case the dest is
            # a directory.
            module_args = ''
            new_module_args = dict(
                src=None,
                follow=True,
            )
            # be sure to inject the check mode param into the module args and
            # rely on the file module to report its changed status
            if self.runner.noop_on_check(inject):
                new_module_args['CHECKMODE'] = True
            options.update(new_module_args)
            return self.runner._execute_module(conn, tmp, 'file', module_args,
                                               inject=inject,
                                               complex_args=options)
Beispiel #9
0
                # Run the copy module

                # src and dest here come after original and override them
                # we pass dest only to make sure it includes trailing slash in case of recursive copy
                new_module_args = dict(
                    src=tmp_src,
                    dest=dest,
                    original_basename=source_rel
                )
                if self.runner.noop_on_check(inject):
                    new_module_args['CHECKMODE'] = True
                if self.runner.no_log:
                    new_module_args['NO_LOG'] = True

                module_args_tmp = utils.merge_module_args(module_args, new_module_args)

                module_return = self.runner._execute_module(conn, tmp_path, 'copy', module_args_tmp, inject=inject, complex_args=complex_args, delete_remote_tmp=delete_remote_tmp)
                module_executed = True

            else:
                # no need to transfer the file, already correct hash, but still need to call
                # the file module in case we want to change attributes
                self._remove_tempfile_if_content_defined(content, content_tempfile)

                if raw:
                    # Continue to next iteration if raw is defined.
                    # self.runner._remove_tmp_path(conn, tmp_path)
                    continue

                tmp_src = tmp_path + source_rel
Beispiel #10
0
class ActionModule(object):

    TRANSFERS_FILES = True

    def __init__(self, runner):
        self.runner = runner

    def run(self,
            conn,
            tmp,
            module_name,
            module_args,
            inject,
            complex_args=None,
            **kwargs):
        ''' handler for template operations '''

        if not self.runner.is_playbook:
            raise errors.AnsibleError(
                "in current versions of ansible, templates are only usable in playbooks"
            )

        # load up options
        options = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))

        source = options.get('src', None)
        dest = options.get('dest', None)

        if (source is None
                and 'first_available_file' not in inject) or dest is None:
            result = dict(failed=True, msg="src and dest are required")
            return ReturnData(conn=conn, comm_ok=False, result=result)

        # if we have first_available_file in our vars
        # look up the files and use the first one we find as src

        if 'first_available_file' in inject:
            found = False
            for fn in self.runner.module_vars.get('first_available_file'):
                fn_orig = fn
                fnt = template.template(self.runner.basedir, fn, inject)
                fnd = utils.path_dwim(self.runner.basedir, fnt)
                if not os.path.exists(fnd) and '_original_file' in inject:
                    fnd = utils.path_dwim_relative(inject['_original_file'],
                                                   'templates',
                                                   fnt,
                                                   self.runner.basedir,
                                                   check=False)
                if os.path.exists(fnd):
                    source = fnd
                    found = True
                    break
            if not found:
                result = dict(
                    failed=True,
                    msg="could not find src in first_available_file list")
                return ReturnData(conn=conn, comm_ok=False, result=result)
        else:
            source = template.template(self.runner.basedir, source, inject)

            if '_original_file' in inject:
                source = utils.path_dwim_relative(inject['_original_file'],
                                                  'templates', source,
                                                  self.runner.basedir)
            else:
                source = utils.path_dwim(self.runner.basedir, source)

        if dest.endswith("/"):  # CCTODO: Fix path for Windows hosts.
            base = os.path.basename(source)
            dest = os.path.join(dest, base)

        # template the source data locally & get ready to transfer
        try:
            resultant = template.template_from_file(
                self.runner.basedir,
                source,
                inject,
                vault_password=self.runner.vault_pass)
        except Exception, e:
            result = dict(failed=True, msg=type(e).__name__ + ": " + str(e))
            return ReturnData(conn=conn, comm_ok=False, result=result)

        local_md5 = utils.md5s(resultant)
        remote_md5 = self.runner._remote_md5(conn, tmp, dest)

        if local_md5 != remote_md5:

            # template is different from the remote value

            # if showing diffs, we need to get the remote value
            dest_contents = ''

            if self.runner.diff:
                # using persist_files to keep the temp directory around to avoid needing to grab another
                dest_result = self.runner._execute_module(conn,
                                                          tmp,
                                                          'slurp',
                                                          "path=%s" % dest,
                                                          inject=inject,
                                                          persist_files=True)
                if 'content' in dest_result.result:
                    dest_contents = dest_result.result['content']
                    if dest_result.result['encoding'] == 'base64':
                        dest_contents = base64.b64decode(dest_contents)
                    else:
                        raise Exception("unknown encoding, failed: %s" %
                                        dest_result.result)

            xfered = self.runner._transfer_str(conn, tmp, 'source', resultant)

            # fix file permissions when the copy is done as a different user
            if self.runner.sudo and self.runner.sudo_user != 'root' or self.runner.su and self.runner.su_user != 'root':
                self.runner._remote_chmod(conn, 'a+r', xfered, tmp)

            # run the copy module
            new_module_args = dict(
                src=xfered,
                dest=dest,
                original_basename=os.path.basename(source),
                follow=True,
            )
            module_args_tmp = utils.merge_module_args(module_args,
                                                      new_module_args)

            if self.runner.noop_on_check(inject):
                return ReturnData(conn=conn,
                                  comm_ok=True,
                                  result=dict(changed=True),
                                  diff=dict(before_header=dest,
                                            after_header=source,
                                            before=dest_contents,
                                            after=resultant))
            else:
                res = self.runner._execute_module(conn,
                                                  tmp,
                                                  'copy',
                                                  module_args_tmp,
                                                  inject=inject,
                                                  complex_args=complex_args)
                if res.result.get('changed', False):
                    res.diff = dict(before=dest_contents, after=resultant)
                return res
        else:
            # when running the file module based on the template data, we do
            # not want the source filename (the name of the template) to be used,
            # since this would mess up links, so we clear the src param and tell
            # the module to follow links.  When doing that, we have to set
            # original_basename to the template just in case the dest is
            # a directory.
            new_module_args = dict(
                src=None,
                original_basename=os.path.basename(source),
                follow=True,
            )
            # be sure to inject the check mode param into the module args and
            # rely on the file module to report its changed status
            if self.runner.noop_on_check(inject):
                new_module_args['CHECKMODE'] = True
            module_args = utils.merge_module_args(module_args, new_module_args)
            return self.runner._execute_module(conn,
                                               tmp,
                                               'file',
                                               module_args,
                                               inject=inject,
                                               complex_args=complex_args)
Beispiel #11
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        ''' handler for file transfer operations '''

        # load up options
        options = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))
        source  = options.get('src', None)
        dest    = options.get('dest', None)
        copy    = utils.boolean(options.get('copy', 'yes'))
        creates = options.get('creates', None)

        if source is None or dest is None:
            result = dict(failed=True, msg="src (or content) and dest are required")
            return ReturnData(conn=conn, result=result)

        if creates:
            # do not run the command if the line contains creates=filename
            # and the filename already exists. This allows idempotence
            # of command executions.
            module_args_tmp = ""
            complex_args_tmp = dict(path=creates, get_md5=False, get_checksum=False)
            module_return = self.runner._execute_module(conn, tmp, 'stat', module_args_tmp, inject=inject,
                                                        complex_args=complex_args_tmp, persist_files=True)
            stat = module_return.result.get('stat', None)
            if stat and stat.get('exists', False):
                return ReturnData(
	            conn=conn,
                    comm_ok=True,
                    result=dict(
                        skipped=True,
                        changed=False,
                        msg=("skipped, since %s exists" % creates)
                    )
                )

        dest = self.runner._remote_expand_user(conn, dest, tmp) # CCTODO: Fix path for Windows hosts.
        source = template.template(self.runner.basedir, os.path.expanduser(source), inject)
        if copy:
            if '_original_file' in inject:
                source = utils.path_dwim_relative(inject['_original_file'], 'files', source, self.runner.basedir)
            else:
                source = utils.path_dwim(self.runner.basedir, source)

        remote_checksum = self.runner._remote_checksum(conn, tmp, dest, inject)
        if remote_checksum == '4':
            result = dict(failed=True, msg="python isn't present on the system.  Unable to compute checksum")
            return ReturnData(conn=conn, result=result)
        if remote_checksum != '3':
            result = dict(failed=True, msg="dest '%s' must be an existing dir" % dest)
            return ReturnData(conn=conn, result=result)

        if copy:
            # transfer the file to a remote tmp location
            tmp_src = tmp + 'source'
            conn.put_file(source, tmp_src)

        # handle diff mode client side
        # handle check mode client side
        # fix file permissions when the copy is done as a different user
        if copy:
            if self.runner.sudo and self.runner.sudo_user != 'root' or self.runner.su and self.runner.su_user != 'root':
                if not self.runner.noop_on_check(inject):
                    self.runner._remote_chmod(conn, 'a+r', tmp_src, tmp)
            # Build temporary module_args.
            new_module_args = dict(
                src=tmp_src,
                original_basename=os.path.basename(source),
            )

            # make sure checkmod is passed on correctly
            if self.runner.noop_on_check(inject):
                new_module_args['CHECKMODE'] = True

            module_args = utils.merge_module_args(module_args, new_module_args)
        else:
            module_args = "%s original_basename=%s" % (module_args, pipes.quote(os.path.basename(source)))
            # make sure checkmod is passed on correctly
            if self.runner.noop_on_check(inject):
                module_args += " CHECKMODE=True"
        return self.runner._execute_module(conn, tmp, 'unarchive', module_args, inject=inject, complex_args=complex_args)
Beispiel #12
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):

        # load up options
        options  = {}
        if complex_args:
            options.update(complex_args)

        options.update(utils.parse_kv(module_args))

        src = options.get('src', None)
        dest = options.get('dest', None)
        delimiter = options.get('delimiter', None)
        remote_src = utils.boolean(options.get('remote_src', 'yes'))
        regexp = options.get('regexp', None)


        if src is None or dest is None:
            result = dict(failed=True, msg="src and dest are required")
            return ReturnData(conn=conn, comm_ok=False, result=result)

        if remote_src:
            return self.runner._execute_module(conn, tmp, 'assemble', module_args, inject=inject, complex_args=complex_args)
        elif '_original_file' in inject:
            src = utils.path_dwim_relative(inject['_original_file'], 'files', src, self.runner.basedir)
        else:
            # the source is local, so expand it here
            src = os.path.expanduser(src)

        _re = None
        if regexp is not None:
            _re = re.compile(regexp)

        # Does all work assembling the file
        path = self._assemble_from_fragments(src, delimiter, _re)

        pathmd5 = utils.md5s(path)
        remote_md5 = self.runner._remote_md5(conn, tmp, dest)

        if pathmd5 != remote_md5:
            resultant = file(path).read()
            if self.runner.diff:
                dest_result = self.runner._execute_module(conn, tmp, 'slurp', "path=%s" % dest, inject=inject, persist_files=True)
                if 'content' in dest_result.result:
                    dest_contents = dest_result.result['content']
                    if dest_result.result['encoding'] == 'base64':
                        dest_contents = base64.b64decode(dest_contents)
                    else:
                        raise Exception("unknown encoding, failed: %s" % dest_result.result)
            xfered = self.runner._transfer_str(conn, tmp, 'src', resultant)

            # fix file permissions when the copy is done as a different user
            if self.runner.sudo and self.runner.sudo_user != 'root' or self.runner.su and self.runner.su_user != 'root':
                self.runner._remote_chmod(conn, 'a+r', xfered, tmp)

            # run the copy module
            new_module_args = dict(
                src=xfered,
                dest=dest,
                original_basename=os.path.basename(src),
            )
            module_args_tmp = utils.merge_module_args(module_args, new_module_args)

            if self.runner.noop_on_check(inject):
                return ReturnData(conn=conn, comm_ok=True, result=dict(changed=True), diff=dict(before_header=dest, after_header=src, after=resultant))
            else:
                res = self.runner._execute_module(conn, tmp, 'copy', module_args_tmp, inject=inject)
                res.diff = dict(after=resultant)
                return res
        else:
            new_module_args = dict(
                src=xfered,
                dest=dest,
                original_basename=os.path.basename(src),
            )
            module_args_tmp = utils.merge_module_args(module_args, new_module_args)

            return self.runner._execute_module(conn, tmp, 'file', module_args_tmp, inject=inject)
Beispiel #13
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        ''' handler for file transfer operations '''

        options = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))

        crt = options.get('crt', None)
        copy = utils.boolean(options.get('copy', 'yes'))
        creates = options.get('creates', None)


        # this module requires at least the crt= to be present
        if crt is None:
            result = dict(failed=True, msg="crt is required")
            return ReturnData(conn=conn, result=result)


        # skip if creates= is added to the module and the destination file already exists
        if creates:
            stat_module_args = ""
            stat_complex_args = dict(path=creates, get_md5=False, get_checksum=False)
            stat_module = self.runner._execute_module(
                conn,
                tmp,
                'stat',
                stat_module_args,
                complex_args=stat_complex_args,
                inject=inject,
                persist_files=True
            )
            stat = stat_module.result.get('stat', None)
            if stat and stat.get('exists', False):
                return ReturnData(
                    conn=conn,
                    comm_ok=True,
                    result=dict(
                        skipped=True,
                        changed=False,
                        msg=("skipped, since %s exists" % creates)
                    )
                )

        crt = utils.template.template(self.runner.basedir, os.path.expanduser(crt), inject)

        # copy files
        if copy:
            source = utils.path_dwim(self.runner.basedir, crt)
            dest = tmp + os.path.basename(crt)
            conn.put_file(source, dest)

            if self.runner.become and self.runner.become_user != 'root':
                if not self.runner.noop_on_check(inject):
                    self.runner._remote_chmod(conn, 'a+r', dest, tmp)

            new_module_args = dict(crt=dest)
            if self.runner.noop_on_check(inject):
                new_module_args['CHECKMODE'] = True

            module_args = utils.merge_module_args(module_args, new_module_args)
        else:
            if self.runner.noop_on_check(inject):
                module_args += " CHECKMODE=True"


        # run keystore module
        return self.runner._execute_module(conn, tmp, 'keystore', module_args, complex_args=complex_args, inject=inject)
Beispiel #14
0
    def run(self,
            conn,
            tmp,
            module_name,
            module_args,
            inject,
            complex_args=None,
            **kwargs):
        ''' handler for file transfer operations '''

        options = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))

        crt = options.get('crt', None)
        copy = utils.boolean(options.get('copy', 'yes'))
        creates = options.get('creates', None)

        # this module requires at least the crt= to be present
        if crt is None:
            result = dict(failed=True, msg="crt is required")
            return ReturnData(conn=conn, result=result)

        # skip if creates= is added to the module and the destination file already exists
        if creates:
            stat_module_args = ""
            stat_complex_args = dict(path=creates,
                                     get_md5=False,
                                     get_checksum=False)
            stat_module = self.runner._execute_module(
                conn,
                tmp,
                'stat',
                stat_module_args,
                complex_args=stat_complex_args,
                inject=inject,
                persist_files=True)
            stat = stat_module.result.get('stat', None)
            if stat and stat.get('exists', False):
                return ReturnData(conn=conn,
                                  comm_ok=True,
                                  result=dict(skipped=True,
                                              changed=False,
                                              msg=("skipped, since %s exists" %
                                                   creates)))

        crt = utils.template.template(self.runner.basedir,
                                      os.path.expanduser(crt), inject)

        # copy files
        if copy:
            source = utils.path_dwim(self.runner.basedir, crt)
            dest = tmp + os.path.basename(crt)
            conn.put_file(source, dest)

            if self.runner.become and self.runner.become_user != 'root':
                if not self.runner.noop_on_check(inject):
                    self.runner._remote_chmod(conn, 'a+r', dest, tmp)

            new_module_args = dict(crt=dest)
            if self.runner.noop_on_check(inject):
                new_module_args['CHECKMODE'] = True

            module_args = utils.merge_module_args(module_args, new_module_args)
        else:
            if self.runner.noop_on_check(inject):
                module_args += " CHECKMODE=True"

        # run keystore module
        return self.runner._execute_module(conn,
                                           tmp,
                                           'keystore',
                                           module_args,
                                           complex_args=complex_args,
                                           inject=inject)
    def materialize_results(self,
                            dest,
                            resultant,
                            conn,
                            tmp,
                            module_name,
                            module_args,
                            inject,
                            complex_args=None,
                            **kwargs):
        '''
        Place resultant in-memory output string text "resultant" at target destination dir "dest" in target file "resultant_basename".
        '''
        dest = os.path.abspath(os.path.expanduser(dest))
        (dest_path, dest_basename) = os.path.split(dest)
        # ensure dest directory exists
        vv("ensuring ssh config target directory {0} exists".format(dest_path))
        file_module_args = dict(
            path=dest_path,
            state="directory",
        )
        if self.runner.noop_on_check(inject):
            file_module_args['CHECKMODE'] = True
        file_module_args = utils.merge_module_args("", file_module_args)
        res = self.runner._execute_module(conn,
                                          tmp,
                                          'file',
                                          file_module_args,
                                          inject=inject,
                                          delete_remote_tmp=False)

        # compare resultant string with current contents of destination
        vv("comparing checksums")
        local_checksum = utils.checksum_s(resultant)
        remote_checksum = self.runner._remote_checksum(conn, tmp, dest, inject)

        if local_checksum != remote_checksum:

            # template is different from the remote value
            vv("checksums differ")

            # if showing diffs, we need to get the remote value
            dest_contents = ''

            if self.runner.diff:
                # using persist_files to keep the temp directory around to avoid needing to grab another
                dest_result = self.runner._execute_module(conn,
                                                          tmp,
                                                          'slurp',
                                                          "path=%s" % dest,
                                                          inject=inject,
                                                          persist_files=True)
                if 'content' in dest_result.result:
                    dest_contents = dest_result.result['content']
                    if dest_result.result['encoding'] == 'base64':
                        dest_contents = base64.b64decode(dest_contents)
                    else:
                        raise Exception("unknown encoding, failed: %s" %
                                        dest_result.result)

            vv("transfering {0}, {1}, {2}, {3}".format(conn, tmp, 'source',
                                                       resultant))
            xfered = self.runner._transfer_str(conn, tmp, 'source', resultant)
            vv("transfer successful!!")

            # fix file permissions when the copy is done as a different user

            # ansible pre-1.9.4 uses "sudo" & "sudo_user" or "su" & "su_user"
            sudo_18 = getattr(self.runner, "sudo", False)
            su_18 = getattr(self.runner, "su", False)
            # ansible 1.9.4-1 uses "become" & "become_user"
            become_1941 = getattr(self.runner, "become", False)

            if sudo_18 and self.runner.sudo_user != 'root' or su_18 and self.runner.su_user != 'root' or become_1941 and self.runner.become_user != 'root':
                self.runner._remote_chmod(conn, 'a+r', xfered, tmp)

            # run the copy module
            vv("running copy module")
            new_module_args = dict(
                src=xfered,
                dest=dest,
                original_basename=dest_basename,
                follow=True,
            )
            module_args_tmp = utils.merge_module_args(module_args,
                                                      new_module_args)
            res = self.runner._execute_module(conn,
                                              tmp,
                                              'copy',
                                              module_args_tmp,
                                              inject=inject,
                                              delete_remote_tmp=False,
                                              complex_args=None)
            if res.result.get('changed', False):
                res.diff = dict(before=dest_contents, after=resultant)
            return res

        else:
            vv("checksums match, using file module to fix up file parameters")

            # when running the file module based on the template data, we do
            # not want the source filename (the name of the template) to be used,
            # since this would mess up links, so we clear the src param and tell
            # the module to follow links.  When doing that, we have to set
            # original_basename to the template just in case the dest is
            # a directory.
            new_module_args = dict(
                src=None,
                dest=dest,
                original_basename=dest_basename,
                follow=True,
            )
            # be sure to inject the check mode param into the module args and
            # rely on the file module to report its changed status
            if self.runner.noop_on_check(inject):
                new_module_args['CHECKMODE'] = True
            file_module_args = utils.merge_module_args(module_args,
                                                       new_module_args)
            file_module_complex_args = complex_args
            for stripkey in ["identity_file", "user", "bastion_user"]:
                if stripkey in file_module_complex_args:
                    del file_module_complex_args[
                        stripkey]  # not supported or needed by file module
            return self.runner._execute_module(
                conn,
                tmp,
                'file',
                file_module_args,
                inject=inject,
                delete_remote_tmp=False,
                complex_args=file_module_complex_args)
Beispiel #16
0
    def run(self,
            conn,
            tmp,
            module_name,
            module_args,
            inject,
            complex_args=None,
            **kwargs):
        ''' handler for file transfer operations '''

        # load up options
        options = {}
        if complex_args:
            options.update(complex_args)
        options.update(utils.parse_kv(module_args))
        source = options.get('src', None)
        dest = options.get('dest', None)
        copy = utils.boolean(options.get('copy', 'yes'))
        creates = options.get('creates', None)

        if source is None or dest is None:
            result = dict(failed=True,
                          msg="src (or content) and dest are required")
            return ReturnData(conn=conn, result=result)

        if creates:
            # do not run the command if the line contains creates=filename
            # and the filename already exists. This allows idempotence
            # of command executions.
            module_args_tmp = "path=%s" % creates
            module_return = self.runner._execute_module(
                conn,
                tmp,
                'stat',
                module_args_tmp,
                inject=inject,
                complex_args=complex_args,
                persist_files=True)
            stat = module_return.result.get('stat', None)
            if stat and stat.get('exists', False):
                return ReturnData(conn=conn,
                                  comm_ok=True,
                                  result=dict(skipped=True,
                                              changed=False,
                                              msg=("skipped, since %s exists" %
                                                   creates)))

        dest = self.runner._remote_expand_user(
            conn, dest, tmp)  # CCTODO: Fix path for Windows hosts.
        source = template.template(self.runner.basedir,
                                   os.path.expanduser(source), inject)
        if copy:
            if '_original_file' in inject:
                source = utils.path_dwim_relative(inject['_original_file'],
                                                  'files', source,
                                                  self.runner.basedir)
            else:
                source = utils.path_dwim(self.runner.basedir, source)

        remote_checksum = self.runner._remote_checksum(conn, tmp, dest, inject)
        if remote_checksum == '4':
            result = dict(
                failed=True,
                msg=
                "python isn't present on the system.  Unable to compute checksum"
            )
            return ReturnData(conn=conn, result=result)
        if remote_checksum != '3':
            result = dict(failed=True,
                          msg="dest '%s' must be an existing dir" % dest)
            return ReturnData(conn=conn, result=result)

        if copy:
            # transfer the file to a remote tmp location
            tmp_src = tmp + 'source'
            conn.put_file(source, tmp_src)

        # handle diff mode client side
        # handle check mode client side
        # fix file permissions when the copy is done as a different user
        if copy:
            if self.runner.sudo and self.runner.sudo_user != 'root' or self.runner.su and self.runner.su_user != 'root':
                if not self.runner.noop_on_check(inject):
                    self.runner._remote_chmod(conn, 'a+r', tmp_src, tmp)
            # Build temporary module_args.
            new_module_args = dict(
                src=tmp_src,
                original_basename=os.path.basename(source),
            )

            # make sure checkmod is passed on correctly
            if self.runner.noop_on_check(inject):
                new_module_args['CHECKMODE'] = True

            module_args = utils.merge_module_args(module_args, new_module_args)
        else:
            module_args = "%s original_basename=%s" % (
                module_args, pipes.quote(os.path.basename(source)))
            # make sure checkmod is passed on correctly
            if self.runner.noop_on_check(inject):
                module_args += " CHECKMODE=True"
        return self.runner._execute_module(conn,
                                           tmp,
                                           'unarchive',
                                           module_args,
                                           inject=inject,
                                           complex_args=complex_args)
Beispiel #17
0
    def run(self,
            conn,
            tmp,
            module_name,
            module_args,
            inject,
            complex_args=None,
            **kwargs):

        # load up options
        options = {}
        if complex_args:
            options.update(complex_args)

        options.update(utils.parse_kv(module_args))

        src = options.get('src', None)
        dest = options.get('dest', None)
        delimiter = options.get('delimiter', None)
        remote_src = utils.boolean(options.get('remote_src', 'yes'))
        regexp = options.get('regexp', None)

        if src is None or dest is None:
            result = dict(failed=True, msg="src and dest are required")
            return ReturnData(conn=conn, comm_ok=False, result=result)

        if remote_src:
            return self.runner._execute_module(conn,
                                               tmp,
                                               'assemble',
                                               module_args,
                                               inject=inject,
                                               complex_args=complex_args)
        elif '_original_file' in inject:
            src = utils.path_dwim_relative(inject['_original_file'], 'files',
                                           src, self.runner.basedir)
        else:
            # the source is local, so expand it here
            src = os.path.expanduser(src)

        _re = None
        if regexp is not None:
            _re = re.compile(regexp)

        # Does all work assembling the file
        path = self._assemble_from_fragments(src, delimiter, _re)

        path_checksum = utils.checksum_s(path)
        dest = self.runner._remote_expand_user(conn, dest, tmp)
        remote_checksum = self.runner._remote_checksum(conn, tmp, dest, inject)

        if path_checksum != remote_checksum:
            resultant = file(path).read()
            if self.runner.diff:
                dest_result = self.runner._execute_module(conn,
                                                          tmp,
                                                          'slurp',
                                                          "path=%s" % dest,
                                                          inject=inject,
                                                          persist_files=True)
                if 'content' in dest_result.result:
                    dest_contents = dest_result.result['content']
                    if dest_result.result['encoding'] == 'base64':
                        dest_contents = base64.b64decode(dest_contents)
                    else:
                        raise Exception("unknown encoding, failed: %s" %
                                        dest_result.result)
            xfered = self.runner._transfer_str(conn, tmp, 'src', resultant)

            # fix file permissions when the copy is done as a different user
            if self.runner.sudo and self.runner.sudo_user != 'root' or self.runner.su and self.runner.su_user != 'root':
                self.runner._remote_chmod(conn, 'a+r', xfered, tmp)

            # run the copy module
            new_module_args = dict(
                src=xfered,
                dest=dest,
                original_basename=os.path.basename(src),
            )
            module_args_tmp = utils.merge_module_args(module_args,
                                                      new_module_args)

            if self.runner.noop_on_check(inject):
                return ReturnData(conn=conn,
                                  comm_ok=True,
                                  result=dict(changed=True),
                                  diff=dict(before_header=dest,
                                            after_header=src,
                                            after=resultant))
            else:
                res = self.runner._execute_module(conn,
                                                  tmp,
                                                  'copy',
                                                  module_args_tmp,
                                                  inject=inject)
                res.diff = dict(after=resultant)
                return res
        else:
            new_module_args = dict(
                src=xfered,
                dest=dest,
                original_basename=os.path.basename(src),
            )

            # make sure checkmod is passed on correctly
            if self.runner.noop_on_check(inject):
                new_module_args['CHECKMODE'] = True

            module_args_tmp = utils.merge_module_args(module_args,
                                                      new_module_args)

            return self.runner._execute_module(conn,
                                               tmp,
                                               'file',
                                               module_args_tmp,
                                               inject=inject)
Beispiel #18
0
    def run(self, conn, tmp, module_name, module_args, inject,
            complex_args=None, **kwargs):
        """Run the method"""
        if not self.runner.is_playbook:
            raise errors.AnsibleError(
                'FAILED: `config_templates` are only available in playbooks'
            )

        options = self.grab_options(complex_args, module_args)
        try:
            source = options['src']
            dest = options['dest']

            config_overrides = options.get('config_overrides', dict())
            config_type = options['config_type']
            assert config_type.lower() in ['ini', 'json', 'yaml']
        except KeyError as exp:
            result = dict(failed=True, msg=exp)
            return ReturnData(conn=conn, comm_ok=False, result=result)

        source_template = template.template(
            self.runner.basedir,
            source,
            inject
        )

        if '_original_file' in inject:
            source_file = utils.path_dwim_relative(
                inject['_original_file'],
                'templates',
                source_template,
                self.runner.basedir
            )
        else:
            source_file = utils.path_dwim(self.runner.basedir, source_template)

        # Open the template file and return the data as a string. This is
        #  being done here so that the file can be a vault encrypted file.
        resultant = template.template_from_file(
            self.runner.basedir,
            source_file,
            inject,
            vault_password=self.runner.vault_pass
        )

        if config_overrides:
            type_merger = getattr(self, CONFIG_TYPES.get(config_type))
            resultant = type_merger(
                config_overrides=config_overrides,
                resultant=resultant
            )

        # Retemplate the resultant object as it may have new data within it
        #  as provided by an override variable.
        template.template_from_string(
            basedir=self.runner.basedir,
            data=resultant,
            vars=inject,
            fail_on_undefined=True
        )

        # Access to protected method is unavoidable in Ansible 1.x.
        new_module_args = dict(
            src=self.runner._transfer_str(conn, tmp, 'source', resultant),
            dest=dest,
            original_basename=os.path.basename(source),
            follow=True,
        )

        module_args_tmp = utils.merge_module_args(
            module_args,
            new_module_args
        )

        # Remove data types that are not available to the copy module
        complex_args.pop('config_overrides')
        complex_args.pop('config_type')

        # Return the copy module status. Access to protected method is
        #  unavoidable in Ansible 1.x.
        return self.runner._execute_module(
            conn,
            tmp,
            'copy',
            module_args_tmp,
            inject=inject,
            complex_args=complex_args
        )