def main(): module = AssibleModule( argument_spec=dict( name=dict(required=True), selection=dict(choices=['install', 'hold', 'deinstall', 'purge'], required=True)), supports_check_mode=True, ) dpkg = module.get_bin_path('dpkg', True) name = module.params['name'] selection = module.params['selection'] # Get current settings. rc, out, err = module.run_command([dpkg, '--get-selections', name], check_rc=True) if not out: current = 'not present' else: current = out.split()[1] changed = current != selection if module.check_mode or not changed: module.exit_json(changed=changed, before=current, after=selection) module.run_command([dpkg, '--set-selections'], data="%s %s" % (name, selection), check_rc=True) module.exit_json(changed=changed, before=current, after=selection)
def main(): module = AssibleModule( argument_spec=dict( database=dict(type='str', required=True), key=dict(type='str'), service=dict(type='str'), split=dict(type='str'), fail_key=dict(type='bool', default=True), ), supports_check_mode=True, ) colon = ['passwd', 'shadow', 'group', 'gshadow'] database = module.params['database'] key = module.params.get('key') split = module.params.get('split') service = module.params.get('service') fail_key = module.params.get('fail_key') getent_bin = module.get_bin_path('getent', True) if key is not None: cmd = [getent_bin, database, key] else: cmd = [getent_bin, database] if service is not None: cmd.extend(['-s', service]) if split is None and database in colon: split = ':' try: rc, out, err = module.run_command(cmd) except Exception as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) msg = "Unexpected failure!" dbtree = 'getent_%s' % database results = {dbtree: {}} if rc == 0: for line in out.splitlines(): record = line.split(split) results[dbtree][record[0]] = record[1:] module.exit_json(assible_facts=results) elif rc == 1: msg = "Missing arguments, or database unknown." elif rc == 2: msg = "One or more supplied key could not be found in the database." if not fail_key: results[dbtree][key] = None module.exit_json(assible_facts=results, msg=msg) elif rc == 3: msg = "Enumeration not supported on this database." module.fail_json(msg=msg)
def main(): module = AssibleModule(argument_spec=dict(desc=dict(type='str'), ), ) results = dict(msg="you just ran me.mycoll2.module1", desc=module.params.get('desc')) module.exit_json(**results)
def do_echo(): p = _load_params() d = json.loads(basic._ASSIBLE_ARGS) d['ASSIBLE_MODULE_ARGS'] = {} basic._ASSIBLE_ARGS = json.dumps(d).encode('utf-8') module = AssibleModule(argument_spec={}) module.exit_json(args_in=p)
def main(): module = AssibleModule(argument_spec=dict(), supports_check_mode=True) module.run_command_environ_update = dict(LANG="C", LC_ALL="C") service_modules = (ServiceScanService, SystemctlScanService, AIXScanService) all_services = {} incomplete_warning = False for svc_module in service_modules: svcmod = svc_module(module) svc = svcmod.gather_services() if svc is not None: all_services.update(svc) if svcmod.incomplete_warning: incomplete_warning = True if len(all_services) == 0: results = dict( skipped=True, msg= "Failed to find any services. Sometimes this is due to insufficient privileges." ) else: results = dict(assible_facts=dict(services=all_services)) if incomplete_warning: results[ 'msg'] = "WARNING: Could not find status for all services. Sometimes this is due to insufficient privileges." module.exit_json(**results)
def main(): argument_spec = cs_argument_spec() argument_spec.update( dict( uuid=dict(aliases=['id']), name=dict(required=True), description=dict(), role_type=dict( choices=['User', 'DomainAdmin', 'ResourceAdmin', 'Admin'], default='User'), state=dict(choices=['present', 'absent'], default='present'), )) module = AssibleModule(argument_spec=argument_spec, required_together=cs_required_together(), supports_check_mode=True) acs_role = AssibleCloudStackRole(module) state = module.params.get('state') if state == 'absent': role = acs_role.absent_role() else: role = acs_role.present_role() result = acs_role.get_result(role) module.exit_json(**result)
def main(): module = AssibleModule(argument_spec=dict( state=dict(type='str', default='file', choices=['file', 'directory']), path=dict(type='path'), prefix=dict(type='str', default='assible.'), suffix=dict(type='str', default=''), ), ) try: if module.params['state'] == 'file': handle, path = mkstemp( prefix=module.params['prefix'], suffix=module.params['suffix'], dir=module.params['path'], ) close(handle) elif module.params['state'] == 'directory': path = mkdtemp( prefix=module.params['prefix'], suffix=module.params['suffix'], dir=module.params['path'], ) module.exit_json(changed=True, path=path) except Exception as e: module.fail_json(msg=to_native(e), exception=format_exc())
def main(): argument_spec = cs_argument_spec() argument_spec.update( dict( role=dict(required=True), name=dict(required=True), permission=dict(choices=['allow', 'deny'], default='deny'), description=dict(), state=dict(choices=['present', 'absent'], default='present'), parent=dict(), )) module = AssibleModule(argument_spec=argument_spec, required_together=cs_required_together(), mutually_exclusive=(['permission', 'parent'], ), supports_check_mode=True) acs_role_perm = AssibleCloudStackRolePermission(module) state = module.params.get('state') if state in ['absent']: role_permission = acs_role_perm.remove_role_perm() else: role_permission = acs_role_perm.create_or_update_role_perm() result = acs_role_perm.get_result(role_permission) module.exit_json(**result)
def main(): module = AssibleModule(argument_spec=dict( number=dict(type='int'), )) module.log('My number is: (%d)' % module.params['number']) module.exit_json()
def main(): module = AssibleModule({}) this_module = sys.modules[__name__] module.exit_json( failed=not getattr(this_module, 'AssibleModule', False) )
def main(): module = AssibleModule( argument_spec=dict(name=dict(type='str', required=True), use=dict(type='str', choices=STRATS.keys())), supports_check_mode=True, ) hostname = Hostname(module) name = module.params['name'] current_hostname = hostname.get_current_hostname() permanent_hostname = hostname.get_permanent_hostname() changed = hostname.update_current_and_permanent_hostname() if name != current_hostname: name_before = current_hostname elif name != permanent_hostname: name_before = permanent_hostname kw = dict(changed=changed, name=name, assible_facts=dict(assible_hostname=name.split('.')[0], assible_nodename=name, assible_fqdn=socket.getfqdn(), assible_domain='.'.join( socket.getfqdn().split('.')[1:]))) if changed: kw['diff'] = { 'after': 'hostname = ' + name + '\n', 'before': 'hostname = ' + name_before + '\n' } module.exit_json(**kw)
def main(): module = AssibleModule(argument_spec={}) module.exit_json(**dict( found=bool(paramiko or assible_paramiko), paramiko=bool(paramiko), assible_paramiko=bool(assible_paramiko), ))
def main(): if "--interactive" in sys.argv: import assible.module_utils.basic assible.module_utils.basic._ASSIBLE_ARGS = json.dumps( dict(ASSIBLE_MODULE_ARGS=dict(fail_mode="graceful"))) module = AssibleModule(argument_spec=dict( fail_mode=dict(type='list', default=['success']))) result = dict(changed=True) fail_mode = module.params['fail_mode'] try: if 'leading_junk' in fail_mode: print("leading junk before module output") if 'graceful' in fail_mode: module.fail_json(msg="failed gracefully") if 'exception' in fail_mode: raise Exception('failing via exception') if 'stderr' in fail_mode: print('printed to stderr', file=sys.stderr) module.exit_json(**result) finally: if 'trailing_junk' in fail_mode: print("trailing junk after module output")
def main(): module = AssibleModule( argument_spec=dict( state=dict(default="present", choices=["present", "latest", "absent"], required=False), name=dict(aliases=["pkg"], required=True, type='list'), cached=dict(default=False, type='bool'), annotation=dict(default="", required=False), pkgsite=dict(default="", required=False), rootdir=dict(default="", required=False, type='path'), chroot=dict(default="", required=False, type='path'), jail=dict(default="", required=False, type='str'), autoremove=dict(default=False, type='bool')), supports_check_mode=True, mutually_exclusive=[["rootdir", "chroot", "jail"]]) pkgng_path = module.get_bin_path('pkg', True) p = module.params pkgs = p["name"] changed = False msgs = [] dir_arg = "" if p["rootdir"] != "": old_pkgng = pkgng_older_than(module, pkgng_path, [1, 5, 0]) if old_pkgng: module.fail_json(msg="To use option 'rootdir' pkg version must be 1.5 or greater") else: dir_arg = "--rootdir %s" % (p["rootdir"]) if p["chroot"] != "": dir_arg = '--chroot %s' % (p["chroot"]) if p["jail"] != "": dir_arg = '--jail %s' % (p["jail"]) if p["state"] in ("present", "latest"): _changed, _msg = install_packages(module, pkgng_path, pkgs, p["cached"], p["pkgsite"], dir_arg, p["state"]) changed = changed or _changed msgs.append(_msg) elif p["state"] == "absent": _changed, _msg = remove_packages(module, pkgng_path, pkgs, dir_arg) changed = changed or _changed msgs.append(_msg) if p["autoremove"]: _changed, _msg = autoremove_packages(module, pkgng_path, dir_arg) changed = changed or _changed msgs.append(_msg) if p["annotation"]: _changed, _msg = annotate_packages(module, pkgng_path, pkgs, p["annotation"], dir_arg) changed = changed or _changed msgs.append(_msg) module.exit_json(changed=changed, msg=", ".join(msgs))
def main(): module = AssibleModule(argument_spec=dict(), supports_check_mode=True) result = dict( two=two(), three=my_util3.three(), ) module.exit_json(**result)
def main(): module = AssibleModule( argument_spec=dict( test=dict(type='str'), ), ) module.exit_json()
def main(): module = AssibleModule( argument_spec=dict(filter=dict(choices=['result', 'status']), ), supports_check_mode=True, ) facts = gather_cloud_init_data_facts(module) result = dict(changed=False, assible_facts=facts, **facts) module.exit_json(**result)
def main(): """main entry point for module execution """ argument_spec = dict( commands=dict(type="list", required=True), wait_for=dict(type="list", aliases=["waitfor"]), match=dict(default="all", choices=["all", "any"]), retries=dict(default=10, type="int"), interval=dict(default=1, type="int"), ) argument_spec.update(ios_argument_spec) module = AssibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() result = {"changed": False, "warnings": warnings} commands = parse_commands(module, warnings) wait_for = module.params["wait_for"] or list() try: conditionals = [Conditional(c) for c in wait_for] except AttributeError as exc: module.fail_json(msg=to_text(exc)) retries = module.params["retries"] interval = module.params["interval"] match = module.params["match"] while retries > 0: responses = run_commands(module, commands) for item in list(conditionals): if item(responses): if match == "any": conditionals = list() break conditionals.remove(item) if not conditionals: break time.sleep(interval) retries -= 1 if conditionals: failed_conditions = [item.raw for item in conditionals] msg = "One or more conditional statements have not been satisfied" module.fail_json(msg=msg, failed_conditions=failed_conditions) result.update({ "stdout": responses, "stdout_lines": list(to_lines(responses)) }) module.exit_json(**result)
def main(): module_args = dict( username=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), ) module = AssibleModule( argument_spec=module_args, required_together=[('username', 'password')], ) # Debugging purposes, get the Kerberos version. On platforms like OpenSUSE this may not be on the PATH. try: process = subprocess.Popen(['krb5-config', '--version'], stdout=subprocess.PIPE) stdout, stderr = process.communicate() version = to_text(stdout) except OSError as e: if e.errno != errno.ENOENT: raise version = 'Unknown (no krb5-config)' # Heimdal has a few quirks that we want to paper over in this module # 1. KRB5_TRACE does not work in any released version (<=7.7), we need to use a custom krb5.config to enable it # 2. When reading the password it reads from the pty not stdin by default causing an issue with subprocess. We # can control that behaviour with '--password-file=STDIN' is_heimdal = os.uname()[0] in ['Darwin', 'FreeBSD'] kinit_args = ['kinit'] config = {} if is_heimdal: kinit_args.append('--password-file=STDIN') config['logging'] = {'krb5': 'FILE:/dev/stdout'} kinit_args.append( to_text(module.params['username'], errors='surrogate_or_strict')) with krb5_conf(module, config): # Weirdly setting KRB5_CONFIG in the modules environment block does not work unless we pass it in explicitly. # Take a copy of the existing environment to make sure the process has the same env vars as ours. Also set # KRB5_TRACE to output and debug logs helping to identify problems when calling kinit with MIT. kinit_env = os.environ.copy() kinit_env['KRB5_TRACE'] = '/dev/stdout' process = subprocess.Popen(kinit_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=kinit_env) stdout, stderr = process.communicate( to_bytes(module.params['password'], errors='surrogate_or_strict') + b'\n') rc = process.returncode module.exit_json(changed=True, stdout=to_text(stdout), stderr=to_text(stderr), rc=rc, version=version)
def main(): module = AssibleModule(argument_spec=dict( data=dict(type='dict', required=True), capitalize_first=dict(type='bool', default=False), ), ) result = snake_dict_to_camel_dict(module.params['data'], module.params['capitalize_first']) module.exit_json(data=result)
def main(): result = dict(changed=False) module = AssibleModule(argument_spec=dict( facts=dict(type=dict, default={}))) result['assible_facts'] = module.params['facts'] result['running_python_interpreter'] = sys.executable module.exit_json(**result)
def main(): module = AssibleModule(argument_spec=dict(data=dict(required=False, default=None), ), supports_check_mode=True) result = dict(ping='pong') if module.params['data']: if module.params['data'] == 'crash': raise Exception("boom") result['ping'] = module.params['data'] result['location'] = 'role: bar' module.exit_json(**result)
def main(): module = AssibleModule(argument_spec=dict(data=dict(type='str', default='pong'), ), supports_check_mode=True) if module.params['data'] == 'crash': raise Exception("boom") result = dict(ping=module.params['data'], ) module.exit_json(**result)
def main(): module = AssibleModule( argument_spec=dict(), ) result = { 'selinux_special_fs': module._selinux_special_fs, 'tmpdir': module._tmpdir, 'keep_remote_files': module._keep_remote_files, 'version': module.assible_version, } module.exit_json(**result)
def main(): module = AssibleModule(argument_spec=dict( data=dict(type='dict', required=True), reversible=dict(type='bool', default=False), ignore_list=dict(type='list', default=[]), ), ) result = camel_dict_to_snake_dict(module.params['data'], module.params['reversible'], module.params['ignore_list']) module.exit_json(data=result)
def main(): module = AssibleModule( argument_spec=dict( name=dict(required=True, type="str"), ), supports_check_mode=True, ) if not HAS_PSUTIL: module.fail_json(msg="Missing required 'psutil' python module. Try installing it with: pip install psutil") name = module.params["name"] response = dict(pids=get_pid(name)) module.exit_json(**response)
def main(): module = AssibleModule(argument_spec={ 'name': { 'default': 'світ' }, }, ) name = module.params['name'] module.exit_json( msg='Greeting {name} completed.'.format(name=name.title()), greeting='Привіт, {name}!'.format(name=name), )
def main(): module = AssibleModule(argument_spec=dict( name=dict(required=True, type='str', aliases=['host']), key=dict(required=False, type='str'), path=dict(default="~/.ssh/known_hosts", type='path'), hash_host=dict(required=False, type='bool', default=False), state=dict(default='present', choices=['absent', 'present']), ), supports_check_mode=True) results = enforce_state(module, module.params) module.exit_json(**results)
def main(): module = AssibleModule(argument_spec=dict( at_the_top=dict(type='str', default='some string'), last_one=dict(type='str', default='some string'), egress=dict(type='list', elements='dict', options=dict(port=dict(type='int', required=True), )), ingress=dict(type='list', elements='dict', options=dict(port=dict(type='int', required=True), )), ), ) module.exit_json()
def main(): module = AssibleModule( argument_spec=dict() ) rlimit_nofile = resource.getrlimit(resource.RLIMIT_NOFILE) try: maxfd = subprocess.MAXFD except AttributeError: maxfd = -1 module.exit_json(rlimit_nofile=rlimit_nofile, maxfd=maxfd, infinity=resource.RLIM_INFINITY)