def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True), port=dict(default=623, type='int'), state=dict(required=True, choices=['on', 'off', 'shutdown', 'reset', 'boot']), user=dict(required=True, no_log=True), password=dict(required=True, no_log=True), timeout=dict(default=300, type='int'), ), supports_check_mode=True, ) if command is None: module.fail_json(msg=missing_required_lib('pyghmi'), exception=PYGHMI_IMP_ERR) name = module.params['name'] port = module.params['port'] user = module.params['user'] password = module.params['password'] state = module.params['state'] timeout = module.params['timeout'] # --- run command --- try: ipmi_cmd = command.Command( bmc=name, userid=user, password=password, port=port ) module.debug('ipmi instantiated - name: "%s"' % name) current = ipmi_cmd.get_power() if current['powerstate'] != state: response = {'powerstate': state} if module.check_mode else ipmi_cmd.set_power(state, wait=timeout) changed = True else: response = current changed = False if 'error' in response: module.fail_json(msg=response['error']) module.exit_json(changed=changed, **response) except Exception as e: module.fail_json(msg=str(e))
def main(): module = AnsibleModule( argument_spec=dict(name=dict(required=True), port=dict(default=623, type='int'), user=dict(required=True, no_log=True), password=dict(required=True, no_log=True), state=dict(default='present', choices=['present', 'absent']), bootdev=dict(required=True, choices=[ 'network', 'hd', 'floppy', 'safe', 'optical', 'setup', 'default' ]), persistent=dict(default=False, type='bool'), uefiboot=dict(default=False, type='bool')), supports_check_mode=True, ) if command is None: module.fail_json(msg=missing_required_lib('pyghmi'), exception=PYGHMI_IMP_ERR) name = module.params['name'] port = module.params['port'] user = module.params['user'] password = module.params['password'] state = module.params['state'] bootdev = module.params['bootdev'] persistent = module.params['persistent'] uefiboot = module.params['uefiboot'] request = dict() if state == 'absent' and bootdev == 'default': module.fail_json( msg="The bootdev 'default' cannot be used with state 'absent'.") # --- run command --- try: ipmi_cmd = command.Command(bmc=name, userid=user, password=password, port=port) module.debug('ipmi instantiated - name: "%s"' % name) current = ipmi_cmd.get_bootdev() # uefimode may not supported by BMC, so use desired value as default current.setdefault('uefimode', uefiboot) if state == 'present' and current != dict( bootdev=bootdev, persistent=persistent, uefimode=uefiboot): request = dict(bootdev=bootdev, uefiboot=uefiboot, persist=persistent) elif state == 'absent' and current['bootdev'] == bootdev: request = dict(bootdev='default') else: module.exit_json(changed=False, **current) if module.check_mode: response = dict(bootdev=request['bootdev']) else: response = ipmi_cmd.set_bootdev(**request) if 'error' in response: module.fail_json(msg=response['error']) if 'persist' in request: response['persistent'] = request['persist'] if 'uefiboot' in request: response['uefimode'] = request['uefiboot'] module.exit_json(changed=True, **response) except Exception as e: module.fail_json(msg=str(e))
def main(): module = AnsibleModule(argument_spec=dict( name=dict(type='list', required=True), state=dict( type='str', default='present', choices=['absent', 'installed', 'latest', 'present', 'removed']), build=dict(type='bool', default=False), ports_dir=dict(type='path', default='/usr/ports'), quick=dict(type='bool', default=False), clean=dict(type='bool', default=False), ), supports_check_mode=True) name = module.params['name'] state = module.params['state'] build = module.params['build'] ports_dir = module.params['ports_dir'] rc = 0 stdout = '' stderr = '' result = {} result['name'] = name result['state'] = state result['build'] = build # The data structure used to keep track of package information. pkg_spec = {} if build is True: if not os.path.isdir(ports_dir): module.fail_json( msg="the ports source directory %s does not exist" % (ports_dir)) # build sqlports if its not installed yet parse_package_name(['sqlports'], pkg_spec, module) get_package_state(['sqlports'], pkg_spec, module) if not pkg_spec['sqlports']['installed_state']: module.debug("main(): installing 'sqlports' because build=%s" % module.params['build']) package_present(['sqlports'], pkg_spec, module) asterisk_name = False for n in name: if n == '*': if len(name) != 1: module.fail_json( msg="the package name '*' can not be mixed with other names" ) asterisk_name = True if asterisk_name: if state != 'latest': module.fail_json( msg="the package name '*' is only valid when using state=latest" ) else: # Perform an upgrade of all installed packages. upgrade_packages(pkg_spec, module) else: # Parse package names and put results in the pkg_spec dictionary. parse_package_name(name, pkg_spec, module) # Not sure how the branch syntax is supposed to play together # with build mode. Disable it for now. for n in name: if pkg_spec[n]['branch'] and module.params['build'] is True: module.fail_json( msg= "the combination of 'branch' syntax and build=%s is not supported: %s" % (module.params['build'], n)) # Get state for all package names. get_package_state(name, pkg_spec, module) # Perform requested action. if state in ['installed', 'present']: package_present(name, pkg_spec, module) elif state in ['absent', 'removed']: package_absent(name, pkg_spec, module) elif state == 'latest': package_latest(name, pkg_spec, module) # The combined changed status for all requested packages. If anything # is changed this is set to True. combined_changed = False # The combined failed status for all requested packages. If anything # failed this is set to True. combined_failed = False # We combine all error messages in this comma separated string, for example: # "msg": "Can't find nmapp\n, Can't find nmappp\n" combined_error_message = '' # Loop over all requested package names and check if anything failed or # changed. for n in name: if pkg_spec[n]['rc'] != 0: combined_failed = True if pkg_spec[n]['stderr']: if combined_error_message: combined_error_message += ", %s" % pkg_spec[n]['stderr'] else: combined_error_message = pkg_spec[n]['stderr'] else: if combined_error_message: combined_error_message += ", %s" % pkg_spec[n]['stdout'] else: combined_error_message = pkg_spec[n]['stdout'] if pkg_spec[n]['changed'] is True: combined_changed = True # If combined_error_message contains anything at least some part of the # list of requested package names failed. if combined_failed: module.fail_json(msg=combined_error_message, **result) result['changed'] = combined_changed module.exit_json(**result)
def main(): # The following example playbooks: # # - cronvar: name="SHELL" value="/bin/bash" # # - name: Set the email # cronvar: name="EMAILTO" value="*****@*****.**" # # - name: Get rid of the old new host variable # cronvar: name="NEW_HOST" state=absent # # Would produce: # SHELL = /bin/bash # EMAILTO = [email protected] module = AnsibleModule( argument_spec=dict( name=dict(type='str', required=True), value=dict(type='str'), user=dict(type='str'), cron_file=dict(type='str'), insertafter=dict(type='str'), insertbefore=dict(type='str'), state=dict(type='str', default='present', choices=['absent', 'present']), backup=dict(type='bool', default=False), ), mutually_exclusive=[['insertbefore', 'insertafter']], supports_check_mode=False, ) name = module.params['name'] value = module.params['value'] user = module.params['user'] cron_file = module.params['cron_file'] insertafter = module.params['insertafter'] insertbefore = module.params['insertbefore'] state = module.params['state'] backup = module.params['backup'] ensure_present = state == 'present' changed = False res_args = dict() # Ensure all files generated are only writable by the owning user. Primarily relevant for the cron_file option. os.umask(int('022', 8)) cronvar = CronVar(module, user, cron_file) module.debug('cronvar instantiated - name: "%s"' % name) # --- user input validation --- if name is None and ensure_present: module.fail_json( msg="You must specify 'name' to insert a new cron variable") if value is None and ensure_present: module.fail_json( msg="You must specify 'value' to insert a new cron variable") if name is None and not ensure_present: module.fail_json( msg="You must specify 'name' to remove a cron variable") # if requested make a backup before making a change if backup: (_, backup_file) = tempfile.mkstemp(prefix='cronvar') cronvar.write(backup_file) if cronvar.cron_file and not name and not ensure_present: changed = cronvar.remove_job_file() module.exit_json(changed=changed, cron_file=cron_file, state=state) old_value = cronvar.find_variable(name) if ensure_present: if old_value is None: cronvar.add_variable(name, value, insertbefore, insertafter) changed = True elif old_value != value: cronvar.update_variable(name, value) changed = True else: if old_value is not None: cronvar.remove_variable(name) changed = True res_args = {"vars": cronvar.get_var_names(), "changed": changed} if changed: cronvar.write() # retain the backup only if crontab or cron file have changed if backup: if changed: res_args['backup_file'] = backup_file else: os.unlink(backup_file) if cron_file: res_args['cron_file'] = cron_file module.exit_json(**res_args)
def main(): # The following example playbooks: # # - cron: name="check dirs" hour="5,2" job="ls -alh > /dev/null" # # - name: do the job # cron: name="do the job" hour="5,2" job="/some/dir/job.sh" # # - name: no job # cron: name="an old job" state=absent # # - name: sets env # cron: name="PATH" env=yes value="/bin:/usr/bin" # # Would produce: # PATH=/bin:/usr/bin # # Ansible: check dirs # * * 5,2 * * ls -alh > /dev/null # # Ansible: do the job # * * 5,2 * * /some/dir/job.sh module = AnsibleModule( argument_spec=dict( name=dict(type='str'), user=dict(type='str'), job=dict(type='str', aliases=['value']), cron_file=dict(type='str'), state=dict(type='str', default='present', choices=['present', 'absent']), backup=dict(type='bool', default=False), minute=dict(type='str', default='*'), hour=dict(type='str', default='*'), day=dict(type='str', default='*', aliases=['dom']), month=dict(type='str', default='*'), weekday=dict(type='str', default='*', aliases=['dow']), reboot=dict(type='bool', default=False), special_time=dict(type='str', choices=[ "reboot", "yearly", "annually", "monthly", "weekly", "daily", "hourly" ]), disabled=dict(type='bool', default=False), env=dict(type='bool'), insertafter=dict(type='str'), insertbefore=dict(type='str'), ), supports_check_mode=True, mutually_exclusive=[ ['reboot', 'special_time'], ['insertafter', 'insertbefore'], ], ) name = module.params['name'] user = module.params['user'] job = module.params['job'] cron_file = module.params['cron_file'] state = module.params['state'] backup = module.params['backup'] minute = module.params['minute'] hour = module.params['hour'] day = module.params['day'] month = module.params['month'] weekday = module.params['weekday'] reboot = module.params['reboot'] special_time = module.params['special_time'] disabled = module.params['disabled'] env = module.params['env'] insertafter = module.params['insertafter'] insertbefore = module.params['insertbefore'] do_install = state == 'present' changed = False res_args = dict() warnings = list() if cron_file: cron_file_basename = os.path.basename(cron_file) if not re.search(r'^[A-Z0-9_-]+$', cron_file_basename, re.I): warnings.append( 'Filename portion of cron_file ("%s") should consist' % cron_file_basename + ' solely of upper- and lower-case letters, digits, underscores, and hyphens' ) # Ensure all files generated are only writable by the owning user. Primarily relevant for the cron_file option. os.umask(int('022', 8)) crontab = CronTab(module, user, cron_file) module.debug('cron instantiated - name: "%s"' % name) if not name: module.deprecate( msg="The 'name' parameter will be required in future releases.", version='2.12') if reboot: module.deprecate( msg= "The 'reboot' parameter will be removed in future releases. Use 'special_time' option instead.", version='2.12') if module._diff: diff = dict() diff['before'] = crontab.existing if crontab.cron_file: diff['before_header'] = crontab.cron_file else: if crontab.user: diff['before_header'] = 'crontab for user "%s"' % crontab.user else: diff['before_header'] = 'crontab' # --- user input validation --- if (special_time or reboot) and \ (True in [(x != '*') for x in [minute, hour, day, month, weekday]]): module.fail_json( msg="You must specify time and date fields or special time.") # cannot support special_time on solaris if (special_time or reboot) and platform.system() == 'SunOS': module.fail_json( msg="Solaris does not support special_time=... or @reboot") if cron_file and do_install: if not user: module.fail_json( msg= "To use cron_file=... parameter you must specify user=... as well" ) if job is None and do_install: module.fail_json( msg="You must specify 'job' to install a new cron job or variable") if (insertafter or insertbefore) and not env and do_install: module.fail_json( msg= "Insertafter and insertbefore parameters are valid only with env=yes" ) if reboot: special_time = "reboot" # if requested make a backup before making a change if backup and not module.check_mode: (backuph, backup_file) = tempfile.mkstemp(prefix='crontab') crontab.write(backup_file) if crontab.cron_file and not name and not do_install: if module._diff: diff['after'] = '' diff['after_header'] = '/dev/null' else: diff = dict() if module.check_mode: changed = os.path.isfile(crontab.cron_file) else: changed = crontab.remove_job_file() module.exit_json(changed=changed, cron_file=cron_file, state=state, diff=diff) if env: if ' ' in name: module.fail_json(msg="Invalid name for environment variable") decl = '%s="%s"' % (name, job) old_decl = crontab.find_env(name) if do_install: if len(old_decl) == 0: crontab.add_env(decl, insertafter, insertbefore) changed = True if len(old_decl) > 0 and old_decl[1] != decl: crontab.update_env(name, decl) changed = True else: if len(old_decl) > 0: crontab.remove_env(name) changed = True else: if do_install: for char in ['\r', '\n']: if char in job.strip('\r\n'): warnings.append('Job should not contain line breaks') break job = crontab.get_cron_job(minute, hour, day, month, weekday, job, special_time, disabled) old_job = crontab.find_job(name, job) if len(old_job) == 0: crontab.add_job(name, job) changed = True if len(old_job) > 0 and old_job[1] != job: crontab.update_job(name, job) changed = True if len(old_job) > 2: crontab.update_job(name, job) changed = True else: old_job = crontab.find_job(name) if len(old_job) > 0: crontab.remove_job(name) changed = True # no changes to env/job, but existing crontab needs a terminating newline if not changed and crontab.existing != '': if not (crontab.existing.endswith('\r') or crontab.existing.endswith('\n')): changed = True res_args = dict(jobs=crontab.get_jobnames(), envs=crontab.get_envnames(), warnings=warnings, changed=changed) if changed: if not module.check_mode: crontab.write() if module._diff: diff['after'] = crontab.render() if crontab.cron_file: diff['after_header'] = crontab.cron_file else: if crontab.user: diff[ 'after_header'] = 'crontab for user "%s"' % crontab.user else: diff['after_header'] = 'crontab' res_args['diff'] = diff # retain the backup only if crontab or cron file have changed if backup and not module.check_mode: if changed: res_args['backup_file'] = backup_file else: os.unlink(backup_file) if cron_file: res_args['cron_file'] = cron_file module.exit_json(**res_args) # --- should never get here module.exit_json(msg="Unable to execute cron task.")
def main(): module = AnsibleModule( argument_spec=dict( state=dict(type='str', default='present', choices=['absent', 'present']), name=dict(type='str', required=True), gid=dict(type='int'), system=dict(type='bool', default=False), local=dict(type='bool', default=False), non_unique=dict(type='bool', default=False), ), supports_check_mode=True, required_if=[ ['non_unique', True, ['gid']], ], ) group = Group(module) module.debug('Group instantiated - platform %s' % group.platform) if group.distribution: module.debug('Group instantiated - distribution %s' % group.distribution) rc = None out = '' err = '' result = {} result['name'] = group.name result['state'] = group.state if group.state == 'absent': if group.group_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = group.group_del() if rc != 0: module.fail_json(name=group.name, msg=err) elif group.state == 'present': if not group.group_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = group.group_add(gid=group.gid, system=group.system) else: (rc, out, err) = group.group_mod(gid=group.gid) if rc is not None and rc != 0: module.fail_json(name=group.name, msg=err) if rc is None: result['changed'] = False else: result['changed'] = True if out: result['stdout'] = out if err: result['stderr'] = err if group.group_exists(): info = group.group_info() result['system'] = group.system result['gid'] = info[2] module.exit_json(**result)