def show_template(host, path, gather_facts=True,
                  inventory_file=None, password_file=None):
    inventory = get_inventory(inventory_file, password_file)
    setup_cache = get_gathered_facts(host, inventory) if gather_facts else {}

    # Show the template
    runner = Runner(
        inventory=inventory,
        setup_cache=setup_cache,
    )
    host_vars = runner.get_inject_vars(host)
    print template_from_file('.', path, host_vars)
Beispiel #2
0
def show_template(host, path, gather_facts=True,
                  inventory_file=None, password_file=None,
                  user=None):
    inventory = get_inventory(inventory_file, password_file)
    setup_cache = get_gathered_facts(
            host, inventory, user) if gather_facts else {}
    # Show the template
    runner = Runner(
        inventory=inventory,
        setup_cache=setup_cache,
    )
    host_vars = runner.get_inject_vars(host)
    print template_from_file('.', path, host_vars)
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        ''' Handler for file load and template operations. '''

        options = self._load_options(module_args, complex_args)
        source = options.get('src', None)
        remote_src = utils.boolean(options.get('remote_src', False))

        if not remote_src:
            if source.endswith('.j2'):
                filepath = self._resolve_file_path(source, 'templates', inject)
                content = template.template_from_file(
                    self.runner.basedir, filepath, inject, vault_password=self.runner.vault_pass)
            else:
                filepath = self._resolve_file_path(source, 'files', inject)
                with open(filepath, 'r') as f:
                    content = f.read()

            module_args = "%s content=%s" % (module_args, pipes.quote(content))

        # propagate checkmode to module
        if self.runner.noop_on_check(inject):
            module_args += " CHECKMODE=True"

        return self.runner._execute_module(
            conn, tmp, 'postgresql_exec', module_args, 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 load and template operations. '''

        options = self._load_options(module_args, complex_args)
        source = options.get('src', None)
        remote_src = utils.boolean(options.get('remote_src', False))

        if not remote_src:
            if source.endswith('.j2'):
                filepath = self._resolve_file_path(source, 'templates', inject)
                content = template.template_from_file(self.runner.basedir,
                        filepath, inject, vault_password=self.runner.vault_pass)
            else:
                filepath = self._resolve_file_path(source, 'files', inject)
                with open(filepath, 'r') as f:
                    content = f.read()

            module_args = "%s content=%s" % (module_args, pipes.quote(content))

        # propagate checkmode to module
        if self.runner.noop_on_check(inject):
            module_args += " CHECKMODE=True"

        return self.runner._execute_module(conn, tmp, 'postgresql_exec', 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):
        ''' handler for template operations '''

        # note: since this module just calls the copy module, the --check mode support
        # can be implemented entirely over there

        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)
Beispiel #6
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        ''' handler for template operations '''

        # note: since this module just calls the copy module, the --check mode support
        # can be implemented entirely over there

        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)
Beispiel #7
0
    def test_template_unicode(self):
        vars = {
            'who': u'wórld',
        }

        res = template2.template_from_file("test", "template-basic", vars)

        assert res == u'hello wórld'
Beispiel #8
0
    def test_template_whitespace(self):
        vars = {
            'who': 'world',
        }

        res = template2.template_from_file("test", "template-whitespace", vars)

        assert res == 'hello world\n'
Beispiel #9
0
    def test_template_basic(self):
        vars = {
            'who': 'world',
        }

        res = template2.template_from_file("test", "template-basic", vars)

        assert res == 'hello world'
Beispiel #10
0
    def test_template_unicode(self):
        vars = {
            'who': u'wórld',
        }

        res = template2.template_from_file("test", "template-basic", vars)

        assert res == u'hello wórld'
Beispiel #11
0
    def test_template_whitespace(self):
        vars = {
            'who': 'world',
        }

        res = template2.template_from_file("test", "template-whitespace", vars)

        assert res == 'hello world\n'
Beispiel #12
0
    def test_template_basic(self):
        vars = {
            'who': 'world',
        }

        res = template2.template_from_file("test", "template-basic", vars)

        assert res == 'hello world'
Beispiel #13
0
    def run(self, terms, inject=None, **kwargs):

        terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject) 

        ret = []
        for term in terms:
            ret.append(template.template_from_file(self.basedir, term, inject))
        return terms
Beispiel #14
0
    def run(self, terms, inject=None, **kwargs):

        terms = utils.listify_lookup_plugin_terms(terms, self.basedir, inject)

        ret = []
        for term in terms:
            ret.append(template.template_from_file(self.basedir, term, inject))
        return ret
    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 #16
0
    def read_config(self, source, inject, config):
        # Only use config if present
        if os.access(source, os.R_OK):
            # template the source data locally & get ready to transfer
            resultant = template.template_from_file(self.runner.basedir,
                                                    source, inject)

            # Read in new results and merge this with the existing config
            fakefile = StringIO(resultant)
            config.readfp(fakefile)
            fakefile.close()
Beispiel #17
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        ''' handler for file transfer operations '''

        # load up options
        options = utils.parse_kv(module_args)
        src = options.get('src', None)

        # template the source data locally & transfer
        try:
            xmldata = template.template_from_file(self.runner.basedir, src, inject)
        except Exception, e:
            result = dict(failed=True, msg=str(e))
            return ReturnData(conn=conn, comm_ok=False, result=result)
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        ''' handler for file transfer operations '''

        # load up options
        options = utils.parse_kv(module_args)
        src = options.get('src', None)

        # template the source data locally & transfer
        try:
            xmldata = template.template_from_file(self.runner.basedir, src, inject)
        except Exception, e:
            result = dict(failed=True, msg='%s (%s)' % (e, src))
            return ReturnData(conn=conn, comm_ok=False, result=result)
        if isinstance(terms, basestring):
            terms = [ terms ]

        ret = []
        for term in terms:
            try:
                r = urllib2.Request(term)
                response = urllib2.urlopen(r)
            except URLError, e:
                utils.warnings("Failed lookup url for %s : %s" % (term, str(e)))
                continue
            except HTTPError, e:
                utils.warnings("Recieved HTTP error for %s : %s" % (term, str(e)))
                continue

            for line in response.read().splitlines():
                ret.append(line)

        tempfile = "/tmp/url"
        f = open(tempfile, 'w')
        for line in ret:
            f.write(line + '\n')
        f.close



        render=(template.template_from_file(self.basedir, tempfile, inject))

        return render
Beispiel #20
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
        )