def __generate_executable_module(self):
     modname = os.path.basename(self.module_path)
     modname = os.path.splitext(modname)[0]
     try:
         (module_data, module_style, shebang) = \
             module_common.modify_module(
                 modname,
                 self.module_path,
                 self.argument_dict,
                 task_vars={}
             )
     except Exception as e:
         LOG.error("Could not generate executable data for module"
                   ": %s. Error: %s" % (self.module_path, str(e)))
         raise AnsibleExecutableGenerationFailed(
             self.module_path,
             self.executable_module_path,
             str(e)
         )
     if not os.path.exists(os.path.dirname(self.executable_module_path)):
         try:
             os.makedirs(os.path.dirname(self.executable_module_path))
         except OSError as exc:
             if exc.errno != errno.EEXIST:
                 raise
     with open(self.executable_module_path, 'w') as f:
         f.write(module_data)
     os.system("chmod +x %s" % self.executable_module_path)
Esempio n. 2
0
    def _configure_module(self, module_name, module_args):
        '''
        Handles the loading and templating of the module code through the
        modify_module() function.
        '''

        # Search module path(s) for named module.
        module_suffixes = getattr(self._connection, 'default_suffixes', None)
        module_path = self._module_loader.find_plugin(module_name,
                                                      module_suffixes)
        if module_path is None:
            module_path2 = self._module_loader.find_plugin(
                'ping', module_suffixes)
            if module_path2 is not None:
                raise AnsibleError(
                    "The module %s was not found in configured module paths" %
                    (module_name))
            else:
                raise AnsibleError("The module %s was not found in configured module paths. " \
                                   "Additionally, core modules are missing. If this is a checkout, " \
                                   "run 'git submodule update --init --recursive' to correct this problem." % (module_name))

        # insert shared code and arguments into the module
        (module_data, module_style,
         module_shebang) = modify_module(module_path, module_args)

        return (module_style, module_shebang, module_data)
 def __generate_executable_module(self):
     modname = os.path.basename(self.module_path)
     modname = os.path.splitext(modname)[0]
     try:
         (module_data, module_style, shebang) = \
             module_common.modify_module(
                 modname,
                 self.module_path,
                 self.argument_dict,
                 None,
                 task_vars={}
             )
     except Exception as e:
         logger.log(
             "debug",
             self.publisher_id,
             {"message": "Could not generate ansible "
                         "executable data "
                         "for module  : %s. Error: %s" %
                         (self.module_path, str(e))},
             node_id=self.node_id
         )
         raise AnsibleExecutableGenerationFailed(
             module_path=self.module_path,
             err=str(e)
         )
     return module_data
 def __generate_executable_module(self):
     modname = os.path.basename(self.module_path)
     modname = os.path.splitext(modname)[0]
     try:
         (module_data, module_style, shebang) = \
             module_common.modify_module(
                 modname,
                 self.module_path,
                 self.argument_dict,
                 task_vars={}
             )
     except Exception as e:
         LOG.error("Could not generate executable data for module"
                   ": %s. Error: %s" % (self.module_path, str(e)))
         raise AnsibleExecutableGenerationFailed(
             self.module_path,
             self.executable_module_path,
             str(e)
         )
     if not os.path.exists(os.path.dirname(self.executable_module_path)):
         try:
             os.makedirs(os.path.dirname(self.executable_module_path))
         except OSError as exc:
             if exc.errno != errno.EEXIST:
                 raise
     with open(self.executable_module_path, 'w') as f:
         f.write(module_data)
     os.system("chmod +x %s" % self.executable_module_path)
Esempio n. 5
0
 def __generate_executable_module(self):
     modname = os.path.basename(self.module_path)
     modname = os.path.splitext(modname)[0]
     try:
         (module_data, module_style, shebang) = \
             module_common.modify_module(
                 modname,
                 self.module_path,
                 self.argument_dict,
                 task_vars={}
             )
     except Exception as e:
         Event(Message(priority="debug",
                       publisher=self.publisher_id,
                       payload={
                           "message":
                           "Could not generate ansible "
                           "executable data "
                           "for module  : %s. Error: %s" %
                           (self.module_path, str(e))
                       },
                       node_id=self.node_id),
               socket_path=self.socket_path)
         raise AnsibleExecutableGenerationFailed(
             module_path=self.module_path, err=str(e))
     return module_data
Esempio n. 6
0
def test_shebang_task_vars(fake_old_module_open):
    task_vars = {'ansible_python_interpreter': '/usr/bin/python3'}

    (data, style, shebang) = modify_module('fake_module',
                                           'fake_path', {},
                                           task_vars=task_vars)
    assert shebang == '#!/usr/bin/python3'
Esempio n. 7
0
    def _configure_module(self, module_name, module_args, task_vars=None):
        '''
        Handles the loading and templating of the module code through the
        modify_module() function.
        '''
        if task_vars is None:
            task_vars = dict()

        # Search module path(s) for named module.
        for mod_type in self._connection.module_implementation_preferences:
            # Check to determine if PowerShell modules are supported, and apply
            # some fixes (hacks) to module name + args.
            if mod_type == '.ps1':
                # win_stat, win_file, and win_copy are not just like their
                # python counterparts but they are compatible enough for our
                # internal usage
                if module_name in ('stat', 'file', 'copy') and self._task.action != module_name:
                    module_name = 'win_%s' % module_name

                # Remove extra quotes surrounding path parameters before sending to module.
                if module_name in ('win_stat', 'win_file', 'win_copy', 'slurp') and module_args and hasattr(self._connection._shell, '_unquote'):
                    for key in ('src', 'dest', 'path'):
                        if key in module_args:
                            module_args[key] = self._connection._shell._unquote(module_args[key])

            module_path = self._shared_loader_obj.module_loader.find_plugin(module_name, mod_type)
            if module_path:
                break
        else:  # This is a for-else: http://bit.ly/1ElPkyg
            # Use Windows version of ping module to check module paths when
            # using a connection that supports .ps1 suffixes. We check specifically
            # for win_ping here, otherwise the code would look for ping.ps1
            if '.ps1' in self._connection.module_implementation_preferences:
                ping_module = 'win_ping'
            else:
                ping_module = 'ping'
            module_path2 = self._shared_loader_obj.module_loader.find_plugin(ping_module, self._connection.module_implementation_preferences)
            if module_path2 is not None:
                raise AnsibleError("The module %s was not found in configured module paths" % (module_name))
            else:
                raise AnsibleError("The module %s was not found in configured module paths. "
                                   "Additionally, core modules are missing. If this is a checkout, "
                                   "run 'git pull --rebase' to correct this problem." % (module_name))

        # insert shared code and arguments into the module
        final_environment = dict()
        self._compute_environment_string(final_environment)

        (module_data, module_style, module_shebang) = modify_module(module_name, module_path, module_args, self._templar,
                                                                    task_vars=task_vars,
                                                                    module_compression=self._play_context.module_compression,
                                                                    async_timeout=self._task.async_val,
                                                                    become=self._play_context.become,
                                                                    become_method=self._play_context.become_method,
                                                                    become_user=self._play_context.become_user,
                                                                    become_password=self._play_context.become_pass,
                                                                    become_flags=self._play_context.become_flags,
                                                                    environment=final_environment)

        return (module_style, module_shebang, module_data, module_path)
Esempio n. 8
0
    def _configure_module(self, module_name, module_args, task_vars=None):
        '''
        Handles the loading and templating of the module code through the
        modify_module() function.
        '''
        if task_vars is None:
            task_vars = dict()

        # Search module path(s) for named module.
        for mod_type in self._connection.module_implementation_preferences:
            # Check to determine if PowerShell modules are supported, and apply
            # some fixes (hacks) to module name + args.
            if mod_type == '.ps1':
                # win_stat, win_file, and win_copy are not just like their
                # python counterparts but they are compatible enough for our
                # internal usage
                if module_name in ('stat', 'file', 'copy') and self._task.action != module_name:
                    module_name = 'win_%s' % module_name

                # Remove extra quotes surrounding path parameters before sending to module.
                if module_name in ('win_stat', 'win_file', 'win_copy', 'slurp') and module_args and hasattr(self._connection._shell, '_unquote'):
                    for key in ('src', 'dest', 'path'):
                        if key in module_args:
                            module_args[key] = self._connection._shell._unquote(module_args[key])

            module_path = self._shared_loader_obj.module_loader.find_plugin(module_name, mod_type)
            if module_path:
                break
        else:  # This is a for-else: http://bit.ly/1ElPkyg
            # Use Windows version of ping module to check module paths when
            # using a connection that supports .ps1 suffixes. We check specifically
            # for win_ping here, otherwise the code would look for ping.ps1
            if '.ps1' in self._connection.module_implementation_preferences:
                ping_module = 'win_ping'
            else:
                ping_module = 'ping'
            module_path2 = self._shared_loader_obj.module_loader.find_plugin(ping_module, self._connection.module_implementation_preferences)
            if module_path2 is not None:
                raise AnsibleError("The module %s was not found in configured module paths" % (module_name))
            else:
                raise AnsibleError("The module %s was not found in configured module paths. "
                                   "Additionally, core modules are missing. If this is a checkout, "
                                   "run 'git pull --rebase' to correct this problem." % (module_name))

        # insert shared code and arguments into the module
        final_environment = dict()
        self._compute_environment_string(final_environment)

        (module_data, module_style, module_shebang) = modify_module(module_name, module_path, module_args, self._templar,
                                                                    task_vars=task_vars,
                                                                    module_compression=self._play_context.module_compression,
                                                                    async_timeout=self._task.async_val,
                                                                    become=self._play_context.become,
                                                                    become_method=self._play_context.become_method,
                                                                    become_user=self._play_context.become_user,
                                                                    become_password=self._play_context.become_pass,
                                                                    become_flags=self._play_context.become_flags,
                                                                    environment=final_environment)

        return (module_style, module_shebang, module_data, module_path)
Esempio n. 9
0
 def __generate_executable_module(self):
     modname = os.path.basename(self.module_path)
     modname = os.path.splitext(modname)[0]
     try:
         task_vars = {}
         task_vars['ansible_python_interpreter'] = sys.executable if \
             sys.executable else '/usr/bin/python'
         (module_data, module_style, shebang) = \
             module_common.modify_module(
                 modname,
                 self.module_path,
                 self.argument_dict,
                 Templar(loader=DataLoader()),
                 task_vars=task_vars
             )
     except Exception as e:
         logger.log(
             "debug",
             self.publisher_id,
             {"message": "Could not generate ansible "
                         "executable data "
                         "for module  : %s. Error: %s" %
                         (self.module_path, str(e))},
             node_id=self.node_id
         )
         raise AnsibleExecutableGenerationFailed(
             module_path=self.module_path,
             err=str(e)
         )
     return module_data
Esempio n. 10
0
def test_shebang_task_vars(fake_old_module_open, templar):
    task_vars = {
        'ansible_python_interpreter': '/usr/bin/python3'
    }

    (data, style, shebang) = modify_module('fake_module', 'fake_path', {}, templar, task_vars=task_vars)
    assert shebang == '#!/usr/bin/python3'
Esempio n. 11
0
def boilerplate_module(modfile, args, interpreter, check, destfile):
    """ simulate what ansible does with new style modules """

    loader = DataLoader()

    complex_args = {}
    if args.startswith("@"):
        # Argument is a YAML file (JSON is a subset of YAML)
        complex_args = utils_vars.combine_vars(complex_args,
                                               loader.load_from_file(args[1:]))
        args = ''
    elif args.startswith("{"):
        # Argument is a YAML document (not a file)
        complex_args = utils_vars.combine_vars(complex_args, loader.load(args))
        args = ''

    if args:
        parsed_args = parse_kv(args)
        complex_args = utils_vars.combine_vars(complex_args, parsed_args)

    task_vars = {}
    if interpreter:
        if '=' not in interpreter:
            print("interpreter must by in the form of \
                   ansible_python_interpreter=/usr/bin/python")
            sys.exit(1)
        interpreter_type, interpreter_path = interpreter.split('=')
        if not interpreter_type.startswith('ansible_'):
            interpreter_type = 'ansible_%s' % interpreter_type
        if not interpreter_type.endswith('_interpreter'):
            interpreter_type = '%s_interpreter' % interpreter_type
        task_vars[interpreter_type] = interpreter_path

    if check:
        complex_args['_ansible_check_mode'] = True

    modname = os.path.basename(modfile)
    modname = os.path.splitext(modname)[0]
    (module_data, module_style, shebang) = module_common.modify_module(
        modname,
        modfile,
        complex_args,
        task_vars=task_vars
    )

    if module_style == 'new' \
       and 'ZIPLOADER_WRAPPER = True' in module_data:
        module_style = 'ziploader'

    modfile2_path = os.path.expanduser(destfile)
    print("* including generated source,\
           if any, saving to: %s" % modfile2_path)
    if module_style not in ('ziploader', 'old'):
        print("* this may offset any line numbers in tracebacks/debuggers!")
    modfile2 = open(modfile2_path, 'w')
    modfile2.write(module_data)
    modfile2.close()
    modfile = modfile2_path

    return (modfile2_path, modname, module_style)
Esempio n. 12
0
def boilerplate_module(modfile, args, interpreter, check, destfile):
    """ simulate what ansible does with new style modules """

    loader = DataLoader()

    complex_args = {}
    if args.startswith("@"):
        # Argument is a YAML file (JSON is a subset of YAML)
        complex_args = utils_vars.combine_vars(complex_args,
                                               loader.load_from_file(args[1:]))
        args = ''
    elif args.startswith("{"):
        # Argument is a YAML document (not a file)
        complex_args = utils_vars.combine_vars(complex_args, loader.load(args))
        args = ''

    if args:
        parsed_args = parse_kv(args)
        complex_args = utils_vars.combine_vars(complex_args, parsed_args)

    task_vars = {}
    if interpreter:
        if '=' not in interpreter:
            print("interpreter must by in the form of \
                   ansible_python_interpreter=/usr/bin/python")
            sys.exit(1)
        interpreter_type, interpreter_path = interpreter.split('=')
        if not interpreter_type.startswith('ansible_'):
            interpreter_type = 'ansible_%s' % interpreter_type
        if not interpreter_type.endswith('_interpreter'):
            interpreter_type = '%s_interpreter' % interpreter_type
        task_vars[interpreter_type] = interpreter_path

    if check:
        complex_args['_ansible_check_mode'] = True

    modname = os.path.basename(modfile)
    modname = os.path.splitext(modname)[0]
    (module_data, module_style,
     shebang) = module_common.modify_module(modname,
                                            modfile,
                                            complex_args,
                                            task_vars=task_vars)

    if module_style == 'new' \
       and 'ZIPLOADER_WRAPPER = True' in module_data:
        module_style = 'ziploader'

    modfile2_path = os.path.expanduser(destfile)
    print("* including generated source,\
           if any, saving to: %s" % modfile2_path)
    if module_style not in ('ziploader', 'old'):
        print("* this may offset any line numbers in tracebacks/debuggers!")
    modfile2 = open(modfile2_path, 'w')
    modfile2.write(module_data)
    modfile2.close()
    modfile = modfile2_path

    return (modfile2_path, modname, module_style)
Esempio n. 13
0
    def _configure_module(self, module_name, module_args, task_vars=None):
        '''
        Handles the loading and templating of the module code through the
        modify_module() function.
        '''
        if task_vars is None:
            task_vars = dict()

        # Search module path(s) for named module.
        for mod_type in self._connection.module_implementation_preferences:
            # Check to determine if PowerShell modules are supported, and apply
            # some fixes (hacks) to module name + args.
            if mod_type == '.ps1':
                # win_stat, win_file, and win_copy are not just like their
                # python counterparts but they are compatible enough for our
                # internal usage
                if module_name in ('stat', 'file', 'copy') and self._task.action != module_name:
                    module_name = 'win_%s' % module_name

                # Remove extra quotes surrounding path parameters before sending to module.
                if module_name in ('win_stat', 'win_file', 'win_copy', 'slurp') and module_args and hasattr(self._connection._shell, '_unquote'):
                    for key in ('src', 'dest', 'path'):
                        if key in module_args:
                            module_args[key] = self._connection._shell._unquote(module_args[key])

            module_path = self._shared_loader_obj.module_loader.find_plugin(module_name, mod_type)
            if module_path:
                break
        else:  # This is a for-else: http://bit.ly/1ElPkyg
            # Use Windows version of ping module to check module paths when
            # using a connection that supports .ps1 suffixes. We check specifically
            # for win_ping here, otherwise the code would look for ping.ps1
            if '.ps1' in self._connection.module_implementation_preferences:
                ping_module = 'win_ping'
            else:
                ping_module = 'ping'
            module_path2 = self._shared_loader_obj.module_loader.find_plugin(ping_module, self._connection.module_implementation_preferences)
            if module_path2 is not None:
                raise AnsibleError("The module %s was not found in configured module paths" % (module_name))
            else:
                raise AnsibleError("The module %s was not found in configured module paths. "
                                   "Additionally, core modules are missing. If this is a checkout, "
                                   "run 'git pull --rebase' to correct this problem." % (module_name))

        # insert shared code and arguments into the module
        (module_data, module_style, module_shebang) = modify_module(module_name, module_path, module_args,
                task_vars=task_vars, module_compression=self._play_context.module_compression)

        # FUTURE: we'll have to get fancier about this to support powershell over SSH on Windows...
        if self._connection.transport == "winrm":
            # WinRM always pipelines, so we need to build up a fancier module payload...
            module_data = build_windows_module_payload(module_name=module_name, module_path=module_path,
                                                   b_module_data=module_data, module_args=module_args,
                                                   task_vars=task_vars, task=self._task,
                                                   play_context=self._play_context)

        return (module_style, module_shebang, module_data, module_path)
Esempio n. 14
0
    def _configure_module(self, module_name, module_args, task_vars=dict()):
        '''
        Handles the loading and templating of the module code through the
        modify_module() function.
        '''

        # Search module path(s) for named module.
        module_suffixes = getattr(self._connection, 'default_suffixes', None)

        # Check to determine if PowerShell modules are supported, and apply
        # some fixes (hacks) to module name + args.
        if module_suffixes and '.ps1' in module_suffixes:
            # Use Windows versions of stat/file/copy modules when called from
            # within other action plugins.
            if module_name in ('stat', 'file',
                               'copy') and self._task.action != module_name:
                module_name = 'win_%s' % module_name
            # Remove extra quotes surrounding path parameters before sending to module.
            if module_name in ('win_stat', 'win_file', 'win_copy',
                               'slurp') and module_args and hasattr(
                                   self._connection._shell, '_unquote'):
                for key in ('src', 'dest', 'path'):
                    if key in module_args:
                        module_args[key] = self._connection._shell._unquote(
                            module_args[key])

        module_path = self._shared_loader_obj.module_loader.find_plugin(
            module_name, module_suffixes)
        if module_path is None:
            # Use Windows version of ping module to check module paths when
            # using a connection that supports .ps1 suffixes.
            if module_suffixes and '.ps1' in module_suffixes:
                ping_module = 'win_ping'
            else:
                ping_module = 'ping'
            module_path2 = self._shared_loader_obj.module_loader.find_plugin(
                ping_module, module_suffixes)
            if module_path2 is not None:
                raise AnsibleError(
                    "The module %s was not found in configured module paths" %
                    (module_name))
            else:
                raise AnsibleError("The module %s was not found in configured module paths. " \
                                   "Additionally, core modules are missing. If this is a checkout, " \
                                   "run 'git submodule update --init --recursive' to correct this problem." % (module_name))

        # insert shared code and arguments into the module
        (module_data, module_style,
         module_shebang) = modify_module(module_path,
                                         module_args,
                                         task_vars=task_vars)

        return (module_style, module_shebang, module_data)
Esempio n. 15
0
    def _configure_module(self, module_name, module_args, task_vars=dict()):
        '''
        Handles the loading and templating of the module code through the
        modify_module() function.
        '''

        # Search module path(s) for named module.
        for mod_type in self._connection.module_implementation_preferences:
            # Check to determine if PowerShell modules are supported, and apply
            # some fixes (hacks) to module name + args.
            if mod_type == '.ps1':
                # win_stat, win_file, and win_copy are not just like their
                # python counterparts but they are compatible enough for our
                # internal usage
                if module_name in ('stat', 'file', 'copy') and self._task.action != module_name:
                    module_name = 'win_%s' % module_name

                # Remove extra quotes surrounding path parameters before sending to module.
                if module_name in ('win_stat', 'win_file', 'win_copy', 'slurp') and module_args and hasattr(self._connection._shell, '_unquote'):
                    for key in ('src', 'dest', 'path'):
                        if key in module_args:
                            module_args[key] = self._connection._shell._unquote(module_args[key])

            module_path = self._shared_loader_obj.module_loader.find_plugin(module_name, mod_type)
            if module_path:
                break
        else: # This is a for-else: http://bit.ly/1ElPkyg
            # FIXME: Why is it necessary to look for the windows version?
            # Shouldn't all modules be installed?
            #
            # Use Windows version of ping module to check module paths when
            # using a connection that supports .ps1 suffixes.
            if '.ps1' in self._connection.module_implementation_preferences:
                ping_module = 'win_ping'
            else:
                ping_module = 'ping'
            module_path2 = self._shared_loader_obj.module_loader.find_plugin(ping_module, self._connection.module_implementation_preferences)
            if module_path2 is not None:
                raise AnsibleError("The module %s was not found in configured module paths" % (module_name))
            else:
                raise AnsibleError("The module %s was not found in configured module paths. " \
                                   "Additionally, core modules are missing. If this is a checkout, " \
                                   "run 'git submodule update --init --recursive' to correct this problem." % (module_name))

        # insert shared code and arguments into the module
        (module_data, module_style, module_shebang) = modify_module(module_path, module_args, task_vars=task_vars)

        return (module_style, module_shebang, module_data)
Esempio n. 16
0
    def __generate_executable_module(self):
        modname = os.path.basename(self.module_path)
        modname = os.path.splitext(modname)[0]
        try:
            (module_data, module_style,
             shebang) = module_common.modify_module(modname,
                                                    self.module_path,
                                                    self.argument_dict,
                                                    task_vars={})
        except Exception as e:
            raise AnsibleExecutableGenerationFailed(
                self.module_path, self.executable_module_path, str(e))

        with open(self.executable_module_path, 'w') as f:
            f.write(module_data)
        os.system("chmod +x %s" % self.executable_module_path)
Esempio n. 17
0
    def _configure_module(self, module_name, module_args, task_vars=dict()):
        '''
        Handles the loading and templating of the module code through the
        modify_module() function.
        '''

        # Search module path(s) for named module.
        module_suffixes = getattr(self._connection, 'default_suffixes', None)

        # Check to determine if PowerShell modules are supported, and apply
        # some fixes (hacks) to module name + args.
        if module_suffixes and '.ps1' in module_suffixes:
            # Use Windows versions of stat/file/copy modules when called from
            # within other action plugins.
            if module_name in ('stat', 'file', 'copy') and self._task.action != module_name:
                module_name = 'win_%s' % module_name
            # Remove extra quotes surrounding path parameters before sending to module.
            if module_name in ('win_stat', 'win_file', 'win_copy', 'slurp') and module_args and hasattr(self._connection._shell, '_unquote'):
                for key in ('src', 'dest', 'path'):
                    if key in module_args:
                        module_args[key] = self._connection._shell._unquote(module_args[key])

        module_path = self._shared_loader_obj.module_loader.find_plugin(module_name, module_suffixes)
        if module_path is None:
            # Use Windows version of ping module to check module paths when
            # using a connection that supports .ps1 suffixes.
            if module_suffixes and '.ps1' in module_suffixes:
                ping_module = 'win_ping'
            else:
                ping_module = 'ping'
            module_path2 = self._shared_loader_obj.module_loader.find_plugin(ping_module, module_suffixes)
            if module_path2 is not None:
                raise AnsibleError("The module %s was not found in configured module paths" % (module_name))
            else:
                raise AnsibleError("The module %s was not found in configured module paths. " \
                                   "Additionally, core modules are missing. If this is a checkout, " \
                                   "run 'git submodule update --init --recursive' to correct this problem." % (module_name))

        # insert shared code and arguments into the module
        (module_data, module_style, module_shebang) = modify_module(module_path, module_args, task_vars=task_vars)

        return (module_style, module_shebang, module_data)
Esempio n. 18
0
def make_task(module_path, task_dir):
  "This makes a task that will read arguments from stdin from an ansible module"

  try:
    doc = load_metadata(module_path)
    module_name = doc['module']
    print "making %s task" % module_name
  except:
    sys.stderr.write("failed to build module %s couldn't find it's name\n" % module_path)
    return

  taskfile = os.path.join(task_dir, '%s.py' % module_name)
  metadatafile = os.path.join(task_dir, '%s.json' % module_name)

  metadata = make_metadata(doc)

  sigil = "&@SIGIL@&"
  ball = modify_module(module_name, module_path, sigil)[0]
  # Replace the sigil
  find = '\'{"ANSIBLE_MODULE_ARGS": "' + sigil + '"}\''
  replace = 'json.dumps({"ANSIBLE_MODULE_ARGS": json.load(sys.stdin)})'

  # Some modules are just metadata stubs. Don't make the tast if there aren't
  # ANSIBALLZ_PARAMS to set.
  if ball.find(find) == -1:
    sys.stderr.write("failed to build module %s couldn't find ANSIBALLZ_PARAMS.\n" % module_name)
    return
  else:
    ball = ball.replace(find, replace)

  find = 'import base64'
  replace = 'import base64\nimport json'
  ball = ball.replace(find, replace)

  with open(taskfile, 'w') as fh:
    fh.write(ball)
  os.chmod(taskfile, 0755)
  with open(metadatafile, 'w') as fh:
    json.dump(metadata, fh, indent=2)
Esempio n. 19
0
    def _configure_module(self, module_name, module_args):
        '''
        Handles the loading and templating of the module code through the
        modify_module() function.
        '''

        # Search module path(s) for named module.
        module_suffixes = getattr(self._connection, 'default_suffixes', None)
        module_path = self._module_loader.find_plugin(module_name, module_suffixes, transport=self._connection.get_transport())
        if module_path is None:
            module_path2 = self._module_loader.find_plugin('ping', module_suffixes)
            if module_path2 is not None:
                raise AnsibleError("The module %s was not found in configured module paths" % (module_name))
            else:
                raise AnsibleError("The module %s was not found in configured module paths. " \
                                   "Additionally, core modules are missing. If this is a checkout, " \
                                   "run 'git submodule update --init --recursive' to correct this problem." % (module_name))

        # insert shared code and arguments into the module
        (module_data, module_style, module_shebang) = modify_module(module_path, module_args)

        return (module_style, module_shebang, module_data)
    def _configure_module(self, module_name, module_args, task_vars=None):
        """
        Handles the loading and templating of the module code through the
        modify_module() function.
        """
        if task_vars is None:
            task_vars = dict()

        # Search module path(s) for named module.
        for mod_type in self._connection.module_implementation_preferences:
            # Check to determine if PowerShell modules are supported, and apply
            # some fixes (hacks) to module name + args.
            if mod_type == ".ps1":
                # win_stat, win_file, and win_copy are not just like their
                # python counterparts but they are compatible enough for our
                # internal usage
                if module_name in ("stat", "file", "copy") and self._task.action != module_name:
                    module_name = "win_%s" % module_name

                # Remove extra quotes surrounding path parameters before sending to module.
                if (
                    module_name in ("win_stat", "win_file", "win_copy", "slurp")
                    and module_args
                    and hasattr(self._connection._shell, "_unquote")
                ):
                    for key in ("src", "dest", "path"):
                        if key in module_args:
                            module_args[key] = self._connection._shell._unquote(module_args[key])

            module_path = self._shared_loader_obj.module_loader.find_plugin(module_name, mod_type)
            if module_path:
                break
        else:  # This is a for-else: http://bit.ly/1ElPkyg
            # Use Windows version of ping module to check module paths when
            # using a connection that supports .ps1 suffixes. We check specifically
            # for win_ping here, otherwise the code would look for ping.ps1
            if ".ps1" in self._connection.module_implementation_preferences:
                ping_module = "win_ping"
            else:
                ping_module = "ping"
            module_path2 = self._shared_loader_obj.module_loader.find_plugin(
                ping_module, self._connection.module_implementation_preferences
            )
            if module_path2 is not None:
                raise AnsibleError("The module %s was not found in configured module paths" % (module_name))
            else:
                raise AnsibleError(
                    "The module %s was not found in configured module paths. "
                    "Additionally, core modules are missing. If this is a checkout, "
                    "run 'git submodule update --init --recursive' to correct this problem." % (module_name)
                )

        # insert shared code and arguments into the module
        (module_data, module_style, module_shebang) = modify_module(
            module_name,
            module_path,
            module_args,
            task_vars=task_vars,
            module_compression=self._play_context.module_compression,
        )

        return (module_style, module_shebang, module_data, module_path)
Esempio n. 21
0
def test_shebang(fake_old_module_open):
    (data, style, shebang) = modify_module('fake_module', 'fake_path', {})
    assert shebang == '#!/usr/bin/python'
Esempio n. 22
0
def test_shebang(fake_old_module_open, templar):
    (data, style, shebang) = modify_module('fake_module', 'fake_path', {}, templar)
    assert shebang == '#!/usr/bin/python'
Esempio n. 23
0
def boilerplate_module(modfile, args, interpreters, check, destfile):
    """ simulate what ansible does with new style modules """

    # module_fh = open(modfile)
    # module_data = module_fh.read()
    # module_fh.close()

    # replacer = module_common.ModuleReplacer()
    loader = DataLoader()

    # included_boilerplate = module_data.find(module_common.REPLACER) != -1 or module_data.find("import ansible.module_utils") != -1

    complex_args = {}

    # default selinux fs list is pass in as _ansible_selinux_special_fs arg
    complex_args['_ansible_selinux_special_fs'] = C.DEFAULT_SELINUX_SPECIAL_FS
    complex_args['_ansible_tmpdir'] = C.DEFAULT_LOCAL_TMP
    complex_args['_ansible_keep_remote_files'] = C.DEFAULT_KEEP_REMOTE_FILES
    complex_args['_ansible_version'] = __version__

    if args.startswith("@"):
        # Argument is a YAML file (JSON is a subset of YAML)
        complex_args = utils_vars.combine_vars(complex_args,
                                               loader.load_from_file(args[1:]))
        args = ''
    elif args.startswith("{"):
        # Argument is a YAML document (not a file)
        complex_args = utils_vars.combine_vars(complex_args, loader.load(args))
        args = ''

    if args:
        parsed_args = parse_kv(args)
        complex_args = utils_vars.combine_vars(complex_args, parsed_args)

    task_vars = interpreters

    if check:
        complex_args['_ansible_check_mode'] = True

    modname = os.path.basename(modfile)
    modname = os.path.splitext(modname)[0]
    (module_data, module_style,
     shebang) = module_common.modify_module(modname,
                                            modfile,
                                            complex_args,
                                            Templar(loader=loader),
                                            task_vars=task_vars)

    if module_style == 'new' and '_ANSIBALLZ_WRAPPER = True' in to_native(
            module_data):
        module_style = 'ansiballz'

    modfile2_path = os.path.expanduser(destfile)
    print("* including generated source, if any, saving to: %s" %
          modfile2_path)
    if module_style not in ('ansiballz', 'old'):
        print("* this may offset any line numbers in tracebacks/debuggers!")
    modfile2 = open(modfile2_path, 'wb')
    modfile2.write(module_data)
    modfile2.close()
    modfile = modfile2_path

    return (modfile2_path, modname, module_style)
Esempio n. 24
0
    def _configure_module(self, module_name, module_args, task_vars=dict()):
        '''
        Handles the loading and templating of the module code through the
        modify_module() function.
        '''

        # Search module path(s) for named module.
        for mod_type in self._connection.module_implementation_preferences:
            # Check to determine if PowerShell modules are supported, and apply
            # some fixes (hacks) to module name + args.
            if mod_type == '.ps1':
                # win_stat, win_file, and win_copy are not just like their
                # python counterparts but they are compatible enough for our
                # internal usage
                if module_name in ('stat', 'file', 'copy'
                                   ) and self._task.action != module_name:
                    module_name = 'win_%s' % module_name

                # Remove extra quotes surrounding path parameters before sending to module.
                if module_name in ('win_stat', 'win_file', 'win_copy',
                                   'slurp') and module_args and hasattr(
                                       self._connection._shell, '_unquote'):
                    for key in ('src', 'dest', 'path'):
                        if key in module_args:
                            module_args[
                                key] = self._connection._shell._unquote(
                                    module_args[key])

            module_path = self._shared_loader_obj.module_loader.find_plugin(
                module_name, mod_type)
            if module_path:
                break
        else:  # This is a for-else: http://bit.ly/1ElPkyg
            # FIXME: Why is it necessary to look for the windows version?
            # Shouldn't all modules be installed?
            #
            # Use Windows version of ping module to check module paths when
            # using a connection that supports .ps1 suffixes.
            if '.ps1' in self._connection.module_implementation_preferences:
                ping_module = 'win_ping'
            else:
                ping_module = 'ping'
            module_path2 = self._shared_loader_obj.module_loader.find_plugin(
                ping_module,
                self._connection.module_implementation_preferences)
            if module_path2 is not None:
                raise AnsibleError(
                    "The module %s was not found in configured module paths" %
                    (module_name))
            else:
                raise AnsibleError("The module %s was not found in configured module paths. " \
                                   "Additionally, core modules are missing. If this is a checkout, " \
                                   "run 'git submodule update --init --recursive' to correct this problem." % (module_name))

        # insert shared code and arguments into the module
        (module_data, module_style,
         module_shebang) = modify_module(module_path,
                                         module_args,
                                         task_vars=task_vars)

        return (module_style, module_shebang, module_data)