Пример #1
0
def main():
    from ansible.module_utils.basic import AnsibleModule
    module = AnsibleModule(
        argument_spec={
            'name': {
                'required': True,
            },
            'state': {
                'required': False,
                'default': 'present',
                'choices': ['absent', 'present'],
            },
            'value': {
                'required': False,
                'default': None,
            },
            'edit_only': {
                'type': 'bool',
                'required': False,
                'default': False,
            },
            'path': {
                'required': False,
                'default': '',
            },
            'bootloader': {
                'required': False,
                'choices': list(BOOTLOADERS.keys()),
            },
            'backup': {
                'type': 'bool',
                'required': False,
                'default': False,
            },
        },
        supports_check_mode=True,
    )

    params = module.params

    path = params['path'].strip()
    bootloader = params['bootloader']
    if path and not bootloader:
        try:
            bootloader = PATHS[path]
        except KeyError:
            module.fail_json(
                msg=("If the `path` argument is given,"
                     " then `bootloader` must also be given."),
                changed=False,
            )
    if not path:
        try:
            path, bootloader = find_bootloader_config()
        except LookupError as err:
            module.fail_json(msg=str(err), changed=False)

    # seed the result dict in the object
    result = {
        'changed': False,
        'path': path,
        'bootloader': bootloader,
        'edited': False,
        'installed': False,
    }

    try:
        handler = BOOTLOADERS[bootloader](module)
    except KeyError:
        module.fail_json(msg=(
            "Unknown value for `bootloader` argument: {bootloader}".format(
                bootloader=bootloader)),
                         **result)

    # if the user is working with this module in only check mode we do not
    # want to make any changes to the environment, just return the current
    # state with no modifications
    if module.check_mode:
        return result

    # read in config file contents
    try:
        with open(path, 'r') as input:
            current_config = input.read()
    except (OSError, IOError) as err:
        module.fail_json(msg=("Cannot read file `{path}`: {err}".format(
            path=path, err=err)),
                         **result)

    # apply requested changes
    new_config = handler.edit(current_config, params['state'], params['name'],
                              params['value'])

    # exit early if no changes
    if new_config == current_config:
        module.exit_json(**result)

    # make a backup if requested
    if params['backup']:
        result['backup'] = module.backup_local(path)

    # write out changed config
    try:
        with NamedTemporaryFile(dir=dirname(path),
                                prefix=(basename(path) + '.'),
                                suffix='.tmp',
                                delete=False) as edited:
            edited.write(new_config)
        module.atomic_move(edited.name, path)
        result['changed'] = True
    except (OSError, IOError) as err:
        module.fail_json(msg=("Cannot write back file `{path}`: {err}".format(
            path=path, err=err)),
                         **result)
    finally:
        module.cleanup(edited.name)

    result['edited'] = True

    # ensure new config is used by the bootloader next time
    result['installed'] = False
    if not params['edit_only']:
        try:
            install_result = handler.install(path)
            result.update(install_result)
            result['installed'] = True
            result['changed'] = True
        except Exception as err:
            module.fail_json(
                msg=("Cannot install new config file `{path}`: {err}".format(
                    path=path, err=err)),
                **result)

    # all done
    module.exit_json(**result)
Пример #2
0
def main():
    from ansible.module_utils.basic import AnsibleModule
    module = AnsibleModule(
        argument_spec = {
            'name': {
                'required': True,
            },
            'state': {
                'required': False,
                'default': 'present',
                'choices': ['absent', 'present'],
            },
            'value': {
                'required': False,
                'default': None,
            },
            'edit_only': {
                'type': 'bool',
                'required': False,
                'default': False,
            },
            'path': {
                'required': False,
                'default': '',
            },
            'bootloader': {
                'required': False,
                'choices': list(BOOTLOADERS.keys()),
            },
            'backup': {
                'type': 'bool',
                'required': False,
                'default': False,
            },
        },
        supports_check_mode=True,
    )

    params = module.params

    path = params['path'].strip()
    bootloader = params['bootloader']
    if path and not bootloader:
        try:
            bootloader = PATHS[path]
        except KeyError:
            module.fail_json(
                msg=("If the `path` argument is given,"
                     " then `bootloader` must also be given."),
                changed=False,
            )
    if not path:
        try:
            path, bootloader = find_bootloader_config()
        except LookupError as err:
            module.fail_json(msg=str(err), changed=False)

    # seed the result dict in the object
    result = {
        'changed': False,
        'path': path,
        'bootloader': bootloader,
        'edited': False,
        'installed': False,
    }

    try:
        handler = BOOTLOADERS[bootloader](module)
    except KeyError:
        module.fail_json(
            msg=("Unknown value for `bootloader` argument: {bootloader}"
                 .format(bootloader=bootloader)),
            **result
        )

    # if the user is working with this module in only check mode we do not
    # want to make any changes to the environment, just return the current
    # state with no modifications
    if module.check_mode:
        return result

    # read in config file contents
    try:
        with open(path, 'r') as input:
            current_config = input.read()
    except (OSError, IOError) as err:
        module.fail_json(
            msg=("Cannot read file `{path}`: {err}"
                 .format(path=path, err=err)),
            **result
        )

    # apply requested changes
    new_config = handler.edit(
        current_config, params['state'], params['name'], params['value'])

    # exit early if no changes
    if new_config == current_config:
        module.exit_json(**result)

    # make a backup if requested
    if params['backup']:
        result['backup'] = module.backup_local(path)

    # write out changed config
    try:
        with NamedTemporaryFile(
                dir=dirname(path),
                prefix=(basename(path) + '.'),
                suffix='.tmp',
                delete=False) as edited:
            edited.write(new_config)
        module.atomic_move(edited.name, path)
        result['changed'] = True
    except (OSError, IOError) as err:
        module.fail_json(
            msg=("Cannot write back file `{path}`: {err}"
                 .format(path=path, err=err)),
            **result
        )
    finally:
        module.cleanup(edited.name)

    result['edited'] = True

    # ensure new config is used by the bootloader next time
    result['installed'] = False
    if not params['edit_only']:
        try:
            install_result = handler.install(path)
            result.update(install_result)
            result['installed'] = True
            result['changed'] = True
        except Exception as err:
            module.fail_json(
                msg=("Cannot install new config file `{path}`: {err}"
                     .format(path=path, err=err)),
                **result
            )

    # all done
    module.exit_json(**result)