コード例 #1
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)
コード例 #2
0
def test():
    try:
        loader = DataLoader()
        ds = loader.load(get_values())

        inventory = InventoryManager(loader=loader)
        if ds is not None:
            for key, value in ds.items():
                inventory.groups['all'].set_variable(key, value)

        variable_manager = VariableManager(
            loader=loader,
            inventory=inventory,
            version_info=CLI.version_info(gitinfo=False))
        templar = Templar(loader=loader)
        templar.available_variables = variable_manager.get_vars(host=Host(
            name='all'))
        try:
            rendered = templar.template(get_template(),
                                        convert_data=False,
                                        cache=False)
        except Exception as e:
            rendered = "Template rendering failed: {0}".format(e)
    except Exception as e:
        rendered = "Template syntax error: {0}".format(e)

    result = {"result": str(rendered)}

    return json.dumps(result)
コード例 #3
0
ファイル: module_utils.py プロジェクト: jjpryor/linchpin
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)
コード例 #4
0
def uncrypted(data, script):
    import imp
    from ansible.parsing.vault import VaultLib

    vault_pass = imp.load_source('vault_pass', script)
    password = vault_pass.get_password()

    vault = VaultLib(password)
    uncrypt = vault.decrypt(data)

    loader = DataLoader()
    result = loader.load(data=uncrypt)

    return result
コード例 #5
0
ファイル: test-module.py プロジェクト: mrlesmithjr/ansible-1
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)
コード例 #6
0
import ansible_runner
from ansible.parsing.dataloader import DataLoader

loader = DataLoader()

inv = loader.load(str({"all": {"hosts": "localhost"}}))
inv1 = str({"all": {"hosts": {"10.20.2.98": ''}}})
extravars = {'ansible_connection': 'local'}
extravars1 = {
    'ansible_ssh_common_args':
    '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ProxyCommand="ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -W %h:%p [email protected]"',
    'become': True,
    'become_method': 'sudo',
    'ansible_user': '******',
    'become_user': '******'
}
with open('/home/centos/poc/abc.pem', 'r') as file:
    ssh_data = file.read()

playbiik_path = '/home/centos/xpvishwanath/ansible-workspace/project-lemp/hello.yml'
r = ansible_runner.run(
    extravars=extravars1,
    private_data_dir='/home/centos/xpvishwanath/ansible-workspace',
    playbook=playbiik_path,
    inventory=inv1,
    ssh_key=ssh_data)

print("{}: {}".format(r.status, r.rc))
# successful: 0
for each_host_event in r.events:
    print(each_host_event['event'])
コード例 #7
0
    def execAnsibleAction(self, request):
        """
        Execute action
        """

        params = request['data']['parameters']

        options_dict = params['options']

        Options = namedtuple('Options', options_dict.keys())

        options = Options(**options_dict)

        # initialize needed objects
        loader = DataLoader()

        play_source = loader.load(params['playbook'])

        passwords = dict(params.get('passwords', {}))

        # Instantiate our ResultCallback for handling results as they come in
        results_callback = CallbackModule()

        # create inventory and pass to var manager
        inventory = InventoryManager(loader=loader,
                                     sources=params.get('hosts'))
        variable_manager = VariableManager(loader=loader, inventory=inventory)

        for c_name, c_value in params['constants'].items():
            C.set_constant(c_name, c_value)

        summary = {}

        try:
            for play_item in play_source:

                play = Play().load(play_item,
                                   variable_manager=variable_manager,
                                   loader=loader)

                # actually run it
                tqm = None
                try:
                    tqm = TaskQueueManager(inventory=inventory,
                                           variable_manager=variable_manager,
                                           loader=loader,
                                           options=options,
                                           passwords=passwords,
                                           stdout_callback=results_callback)
                    tqm.run(play)
                finally:
                    if tqm is not None:
                        tqm.cleanup()

                hosts = sorted(tqm._stats.processed.keys())

                for h in hosts:
                    s = tqm._stats.summarize(h)

                    if s['unreachable'] > 0 or s['failures'] > 0:
                        raise AnsiblesCommandExecution

                    summary[h] = s

            self.sendNotify(request,
                            data={
                                'result': json.dumps(summary),
                                'get': request['data']['get']
                            })
        except AnsiblesCommandExecution:
            self.sendError(request,
                           data={
                               'error': 'Wrong ansible response',
                               'get': request['data']['get']
                           })
            self.sendNotify(request,
                            data={
                                'result':
                                json.dumps({'error': results_callback.results},
                                           sort_keys=True,
                                           indent=4),
                                'get':
                                request['data']['get']
                            })