Example #1
0
def create_module():
    """Create module description."""
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # generalgroups
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            # present
            description=dict(required=False, type="str", default=None),
            rename=dict(required=False,
                        type="str",
                        default=None,
                        aliases=["new_name"]),
            # members
            privilege=dict(required=False, type='list', default=None),
            user=dict(required=False, type='list', default=None),
            group=dict(required=False, type='list', default=None),
            host=dict(required=False, type='list', default=None),
            hostgroup=dict(required=False, type='list', default=None),
            service=dict(required=False, type='list', default=None),

            # state
            action=dict(type="str", default="role", choices=["role",
                                                             "member"]),
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent", "renamed"]),
        ),
        supports_check_mode=True,
        mutually_exclusive=[],
        required_one_of=[])

    ansible_module._ansible_debug = True  # pylint: disable=protected-access

    return ansible_module
Example #2
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            suffix=dict(choices=["domain", "ca"], required=True),
            state=dict(type="str", default="verified", choices=["verified"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    suffix = ansible_module.params_get("suffix")
    state = ansible_module.params_get("state")

    # Check parameters

    # Init

    # Create command

    if state not in ["verified"]:
        ansible_module.fail_json(msg="Unkown state '%s'" % state)

    # Execute command

    with ansible_module.ipa_connect():
        # Execute command
        ansible_module.ipa_command("topologysuffix_verify", suffix, {})

    # Done

    ansible_module.exit_json(changed=True)
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            # present
            description=dict(required=False, type='str', default=None),
            rename=dict(
                required=False,
                type='str',
                default=None,
                aliases=["new_name"],
            ),
            permission=dict(required=False, type='list', default=None),
            action=dict(type="str",
                        default="privilege",
                        choices=["member", "privilege"]),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent", "renamed"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    description = ansible_module.params_get("description")
    permission = ansible_module.params_get("permission")
    rename = ansible_module.params_get("rename")
    action = ansible_module.params_get("action")

    # state
    state = ansible_module.params_get("state")

    # Check parameters
    invalid = []

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one privilege be added at a time.")
        if action == "member":
            invalid = ["description"]

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        invalid = ["description", "rename"]
        if action == "privilege":
            invalid.append("permission")

    if state == "renamed":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one privilege be added at a time.")
        invalid = ["description", "permission"]
        if action != "privilege":
            ansible_module.fail_json(
                msg="Action '%s' can not be used with state '%s'" %
                (action, state))

    for x in invalid:
        if vars()[x] is not None:
            ansible_module.fail_json(
                msg="Argument '%s' can not be used with action "
                "'%s' and state '%s'" % (x, action, state))

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        commands = []
        for name in names:
            # Make sure privilege exists
            res_find = find_privilege(ansible_module, name)

            # Create command
            if state == "present":

                args = {}
                if description:
                    args['description'] = description

                if action == "privilege":
                    # Found the privilege
                    if res_find is not None:
                        res_cmp = {
                            k: v
                            for k, v in res_find.items() if k not in [
                                "objectclass", "cn", "dn",
                                "memberof_permisssion"
                            ]
                        }
                        # For all settings is args, check if there are
                        # different settings in the find result.
                        # If yes: modify
                        if args and not compare_args_ipa(
                                ansible_module, args, res_cmp):
                            commands.append([name, "privilege_mod", args])
                    else:
                        commands.append([name, "privilege_add", args])
                        res_find = {}

                    member_args = {}
                    if permission:
                        member_args['permission'] = permission

                    if not compare_args_ipa(ansible_module, member_args,
                                            res_find):

                        # Generate addition and removal lists
                        permission_add, permission_del = gen_add_del_lists(
                            permission, res_find.get("member_permission"))

                        # Add members
                        if len(permission_add) > 0:
                            commands.append([
                                name, "privilege_add_permission", {
                                    "permission": permission_add,
                                }
                            ])
                        # Remove members
                        if len(permission_del) > 0:
                            commands.append([
                                name, "privilege_remove_permission", {
                                    "permission": permission_del
                                }
                            ])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No privilege '%s'" %
                                                 name)

                    if permission is None:
                        ansible_module.fail_json(msg="No permission given")

                    commands.append([
                        name, "privilege_add_permission", {
                            "permission": permission
                        }
                    ])

            elif state == "absent":
                if action == "privilege":
                    if res_find is not None:
                        commands.append([name, "privilege_del", {}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No privilege '%s'" %
                                                 name)

                    if permission is None:
                        ansible_module.fail_json(msg="No permission given")

                    commands.append([
                        name, "privilege_remove_permission", {
                            "permission": permission,
                        }
                    ])

            elif state == "renamed":
                if not rename:
                    ansible_module.fail_json(msg="No rename value given.")

                if res_find is None:
                    ansible_module.fail_json(
                        msg="No privilege found to be renamed: '%s'" % (name))

                if name != rename:
                    commands.append(
                        [name, "privilege_mod", {
                            "rename": rename
                        }])

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

        # Execute commands

        changed = ansible_module.execute_ipa_commands(commands, result_handler)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #4
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            # present
            location=dict(required=False,
                          type='str',
                          aliases=["ipalocation_location"],
                          default=None),
            service_weight=dict(required=False,
                                type='int',
                                aliases=["ipaserviceweight"],
                                default=None),
            hidden=dict(required=False, type='bool', default=None),
            no_members=dict(required=False, type='bool', default=None),
            # absent
            delete_continue=dict(required=False,
                                 type='bool',
                                 aliases=["continue"],
                                 default=None),
            ignore_topology_disconnect=dict(required=False,
                                            type='bool',
                                            default=None),
            ignore_last_of_role=dict(required=False, type='bool',
                                     default=None),
            force=dict(required=False, type='bool', default=None),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    location = ansible_module.params_get("location")
    service_weight = ansible_module.params_get("service_weight")
    # Service weight smaller than 0 leads to resetting service weight
    if service_weight is not None and \
       (service_weight < -1 or service_weight > 65535):
        ansible_module.fail_json(
            msg="service_weight %d is out of range [-1 .. 65535]" %
            service_weight)
    if service_weight == -1:
        service_weight = ""
    hidden = ansible_module.params_get("hidden")
    no_members = ansible_module.params_get("no_members")

    # absent
    delete_continue = ansible_module.params_get("delete_continue")
    ignore_topology_disconnect = ansible_module.params_get(
        "ignore_topology_disconnect")
    ignore_last_of_role = ansible_module.params_get("ignore_last_of_role")
    force = ansible_module.params_get("force")

    # state
    state = ansible_module.params_get("state")

    # Check parameters

    invalid = []

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one server can be ensured at a time.")
        invalid = [
            "delete_continue", "ignore_topology_disconnect",
            "ignore_last_of_role", "force"
        ]

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        invalid = ["location", "service_weight", "hidden", "no_members"]

    ansible_module.params_fail_used_invalid(invalid, state)

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        commands = []
        for name in names:
            # Make sure server exists
            res_find = find_server(ansible_module, name)

            # Generate args
            args = gen_args(location, service_weight, no_members,
                            delete_continue, ignore_topology_disconnect,
                            ignore_last_of_role, force)

            # Create command
            if state == "present":
                # Server not found
                if res_find is None:
                    ansible_module.fail_json(msg="Server '%s' not found" %
                                             name)

                # Remove location from args if "" (transformed to None)
                # and "ipalocation_location" not in res_find for idempotency
                if "ipalocation_location" in args and \
                   args["ipalocation_location"] is None and \
                   "ipalocation_location" not in res_find:
                    del args["ipalocation_location"]

                # Remove service weight from args if ""
                # and "ipaserviceweight" not in res_find for idempotency
                if "ipaserviceweight" in args and \
                   args["ipaserviceweight"] == "" and \
                   "ipaserviceweight" not in res_find:
                    del args["ipaserviceweight"]

                # For all settings is args, check if there are
                # different settings in the find result.
                # If yes: modify
                if not compare_args_ipa(ansible_module, args, res_find):
                    commands.append([name, "server_mod", args])

                # hidden handling
                if hidden is not None:
                    res_role_status = server_role_status(ansible_module, name)

                    if "status" in res_role_status:
                        # Fail if status is configured, it should be done
                        # only in the installer
                        if res_role_status["status"] == "configured":
                            ansible_module.fail_json(
                                msg="'%s' in configured state, "
                                "unable to change state" % state)

                        if hidden and res_role_status["status"] == "enabled":
                            commands.append(
                                [name, "server_state", {
                                    "state": "hidden"
                                }])
                        if not hidden and \
                           res_role_status["status"] == "hidden":
                            commands.append(
                                [name, "server_state", {
                                    "state": "enabled"
                                }])

            elif state == "absent":
                if res_find is not None or force:
                    commands.append([name, "server_del", args])
            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

        # Execute commands

        changed = ansible_module.execute_ipa_commands(commands)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #5
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            # present
            description=dict(type="str", default=None),
            gid=dict(type="int", aliases=["gidnumber"], default=None),
            nonposix=dict(required=False, type='bool', default=None),
            external=dict(required=False, type='bool', default=None),
            posix=dict(required=False, type='bool', default=None),
            nomembers=dict(required=False, type='bool', default=None),
            user=dict(required=False, type='list', default=None),
            group=dict(required=False, type='list', default=None),
            service=dict(required=False, type='list', default=None),
            membermanager_user=dict(required=False, type='list', default=None),
            membermanager_group=dict(required=False, type='list',
                                     default=None),
            externalmember=dict(
                required=False,
                type='list',
                default=None,
                aliases=["ipaexternalmember", "external_member"]),
            action=dict(type="str",
                        default="group",
                        choices=["member", "group"]),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent"]),
        ),
        # It does not make sense to set posix, nonposix or external at the
        # same time
        mutually_exclusive=[['posix', 'nonposix', 'external']],
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    description = ansible_module.params_get("description")
    gid = ansible_module.params_get("gid")
    nonposix = ansible_module.params_get("nonposix")
    external = ansible_module.params_get("external")
    posix = ansible_module.params_get("posix")
    nomembers = ansible_module.params_get("nomembers")
    user = ansible_module.params_get("user")
    group = ansible_module.params_get("group")
    # Services are not case sensitive
    service = ansible_module.params_get_lowercase("service")
    membermanager_user = ansible_module.params_get("membermanager_user")
    membermanager_group = ansible_module.params_get("membermanager_group")
    externalmember = ansible_module.params_get("externalmember")
    action = ansible_module.params_get("action")
    # state
    state = ansible_module.params_get("state")

    # Check parameters
    invalid = []

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one group can be added at a time.")
        if action == "member":
            invalid = [
                "description", "gid", "posix", "nonposix", "external",
                "nomembers"
            ]

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        invalid = [
            "description", "gid", "posix", "nonposix", "external", "nomembers"
        ]
        if action == "group":
            invalid.extend(["user", "group", "service", "externalmember"])

    ansible_module.params_fail_used_invalid(invalid, state, action)

    if external is False:
        ansible_module.fail_json(msg="group can not be non-external")

    # Init

    changed = False
    exit_args = {}

    # If nonposix is used, set posix as not nonposix
    if nonposix is not None:
        posix = not nonposix

    # Connect to IPA API
    with ansible_module.ipa_connect():

        has_add_member_service = ansible_module.ipa_command_param_exists(
            "group_add_member", "service")
        if service is not None and not has_add_member_service:
            ansible_module.fail_json(
                msg="Managing a service as part of a group is not supported "
                "by your IPA version")

        has_add_membermanager = ansible_module.ipa_command_exists(
            "group_add_member_manager")
        if ((membermanager_user is not None or membermanager_group is not None)
                and not has_add_membermanager):
            ansible_module.fail_json(
                msg="Managing a membermanager user or group is not supported "
                "by your IPA version")

        commands = []

        for name in names:
            # Make sure group exists
            res_find = find_group(ansible_module, name)

            user_add, user_del = [], []
            group_add, group_del = [], []
            service_add, service_del = [], []
            externalmember_add, externalmember_del = [], []
            membermanager_user_add, membermanager_user_del = [], []
            membermanager_group_add, membermanager_group_del = [], []

            # Create command
            if state == "present":
                # Can't change an existing posix group
                check_objectclass_args(ansible_module, res_find, posix,
                                       external)

                # Generate args
                args = gen_args(description, gid, nomembers)

                if action == "group":
                    # Found the group
                    if res_find is not None:
                        # For all settings in args, check if there are
                        # different settings in the find result.
                        # If yes: modify
                        # Also if it is a modification from nonposix to posix
                        # or nonposix to external.
                        if not compare_args_ipa(
                                ansible_module, args, res_find) or (
                                    not is_posix_group(res_find)
                                    and not is_external_group(res_find) and
                                    (posix or external)):
                            if posix:
                                args['posix'] = True
                            if external:
                                args['external'] = True
                            commands.append([name, "group_mod", args])
                    else:
                        if posix is not None and not posix:
                            args['nonposix'] = True
                        if external:
                            args['external'] = True
                        commands.append([name, "group_add", args])
                        # Set res_find dict for next step
                        res_find = {}

                    # if we just created/modified the group, update res_find
                    res_find.setdefault("objectclass", [])
                    if external and not is_external_group(res_find):
                        res_find["objectclass"].append("ipaexternalgroup")
                    if posix and not is_posix_group(res_find):
                        res_find["objectclass"].append("posixgroup")

                    member_args = gen_member_args(user, group, service,
                                                  externalmember)
                    if not compare_args_ipa(ansible_module, member_args,
                                            res_find):
                        # Generate addition and removal lists
                        user_add, user_del = gen_add_del_lists(
                            user, res_find.get("member_user"))

                        group_add, group_del = gen_add_del_lists(
                            group, res_find.get("member_group"))

                        service_add, service_del = gen_add_del_lists(
                            service, res_find.get("member_service"))

                        (externalmember_add,
                         externalmember_del) = gen_add_del_lists(
                             externalmember, res_find.get("member_external"))

                    membermanager_user_add, membermanager_user_del = \
                        gen_add_del_lists(
                            membermanager_user,
                            res_find.get("membermanager_user")
                        )

                    membermanager_group_add, membermanager_group_del = \
                        gen_add_del_lists(
                            membermanager_group,
                            res_find.get("membermanager_group")
                        )

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No group '%s'" % name)

                    # Reduce add lists for member_user, member_group,
                    # member_service and member_external to new entries
                    # only that are not in res_find.
                    user_add = gen_add_list(user, res_find.get("member_user"))
                    group_add = gen_add_list(group,
                                             res_find.get("member_group"))
                    service_add = gen_add_list(service,
                                               res_find.get("member_service"))
                    externalmember_add = gen_add_list(
                        externalmember, res_find.get("member_external"))

                    membermanager_user_add = gen_add_list(
                        membermanager_user, res_find.get("membermanager_user"))
                    membermanager_group_add = gen_add_list(
                        membermanager_group,
                        res_find.get("membermanager_group"))

            elif state == "absent":
                if action == "group":
                    if res_find is not None:
                        commands.append([name, "group_del", {}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No group '%s'" % name)

                    if not is_external_group(res_find) and externalmember:
                        ansible_module.fail_json(
                            msg="Cannot add external members to a "
                            "non-external group.")

                    user_del = gen_intersection_list(
                        user, res_find.get("member_user"))
                    group_del = gen_intersection_list(
                        group, res_find.get("member_group"))
                    service_del = gen_intersection_list(
                        service, res_find.get("member_service"))
                    externalmember_del = gen_intersection_list(
                        externalmember, res_find.get("member_external"))

                    membermanager_user_del = gen_intersection_list(
                        membermanager_user, res_find.get("membermanager_user"))
                    membermanager_group_del = gen_intersection_list(
                        membermanager_group,
                        res_find.get("membermanager_group"))
            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

            # manage members
            # setup member args for add/remove members.
            add_member_args = {
                "user": user_add,
                "group": group_add,
            }
            del_member_args = {
                "user": user_del,
                "group": group_del,
            }
            if has_add_member_service:
                add_member_args["service"] = service_add
                del_member_args["service"] = service_del

            if is_external_group(res_find):
                add_member_args["ipaexternalmember"] = \
                    externalmember_add
                del_member_args["ipaexternalmember"] = \
                    externalmember_del
            elif externalmember or external:
                ansible_module.fail_json(
                    msg="Cannot add external members to a "
                    "non-external group.")
            # Add members
            add_members = any(
                [user_add, group_add, service_add, externalmember_add])
            if add_members:
                commands.append([name, "group_add_member", add_member_args])
            # Remove members
            remove_members = any(
                [user_del, group_del, service_del, externalmember_del])
            if remove_members:
                commands.append([name, "group_remove_member", del_member_args])

            # manage membermanager members
            if has_add_membermanager:
                # Add membermanager users and groups
                if any([membermanager_user_add, membermanager_group_add]):
                    commands.append([
                        name, "group_add_member_manager", {
                            "user": membermanager_user_add,
                            "group": membermanager_group_add,
                        }
                    ])
                # Remove member manager
                if any([membermanager_user_del, membermanager_group_del]):
                    commands.append([
                        name, "group_remove_member_manager", {
                            "user": membermanager_user_del,
                            "group": membermanager_group_del,
                        }
                    ])

        # Execute commands
        changed = ansible_module.execute_ipa_commands(
            commands, fail_on_member_errors=True)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #6
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list",
                      aliases=["sudocmd"],
                      default=None,
                      required=True),
            # present
            description=dict(type="str", default=None),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    description = ansible_module.params_get("description")
    # state
    state = ansible_module.params_get("state")

    # Check parameters
    if state == "absent":
        invalid = ["description"]
        for x in invalid:
            if vars()[x] is not None:
                ansible_module.fail_json(
                    msg="Argument '%s' can not be used with state '%s'" %
                    (x, state))

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        commands = []

        for name in names:
            # Make sure hostgroup exists
            res_find = find_sudocmd(ansible_module, name)

            # Create command
            if state == "present":
                # Generate args
                args = gen_args(description)
                if res_find is not None:
                    # For all settings in args, check if there are
                    # different settings in the find result.
                    # If yes: modify
                    if not compare_args_ipa(ansible_module, args, res_find):
                        commands.append([name, "sudocmd_mod", args])
                else:
                    commands.append([name, "sudocmd_add", args])
                    # Set res_find to empty dict for next step
                    res_find = {}
            elif state == "absent":
                if res_find is not None:
                    commands.append([name, "sudocmd_del", {}])
            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

        changed = ansible_module.execute_ipa_commands(commands)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #7
0
def init_ansible_module():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list",
                      aliases=["service"],
                      default=None,
                      required=True),
            # service attributesstr
            certificate=dict(type="list",
                             aliases=['usercertificate'],
                             default=None,
                             required=False),
            principal=dict(type="list",
                           aliases=["krbprincipalname"],
                           default=None),
            smb=dict(type="bool", required=False),
            netbiosname=dict(type="str", required=False),
            pac_type=dict(type="list",
                          aliases=["ipakrbauthzdata"],
                          choices=["MS-PAC", "PAD", "NONE"]),
            auth_ind=dict(type="list",
                          aliases=["krbprincipalauthind"],
                          choices=["otp", "radius", "pkinit", "hardened", ""]),
            skip_host_check=dict(type="bool"),
            force=dict(type="bool"),
            requires_pre_auth=dict(type="bool",
                                   aliases=["ipakrbrequirespreauth"]),
            ok_as_delegate=dict(type="bool", aliases=["ipakrbokasdelegate"]),
            ok_to_auth_as_delegate=dict(type="bool",
                                        aliases=["ipakrboktoauthasdelegate"]),
            host=dict(type="list", aliases=["managedby_host"], required=False),
            allow_create_keytab_user=dict(
                type="list",
                required=False,
                aliases=['ipaallowedtoperform_write_keys_user']),
            allow_retrieve_keytab_user=dict(
                type="list",
                required=False,
                aliases=['ipaallowedtoperform_read_keys_user']),
            allow_create_keytab_group=dict(
                type="list",
                required=False,
                aliases=['ipaallowedtoperform_write_keys_group']),
            allow_retrieve_keytab_group=dict(
                type="list",
                required=False,
                aliases=['ipaallowedtoperform_read_keys_group']),
            allow_create_keytab_host=dict(
                type="list",
                required=False,
                aliases=['ipaallowedtoperform_write_keys_host']),
            allow_retrieve_keytab_host=dict(
                type="list",
                required=False,
                aliases=['ipaallowedtoperform_read_keys_host']),
            allow_create_keytab_hostgroup=dict(
                type="list",
                required=False,
                aliases=['ipaallowedtoperform_write_keys_hostgroup']),
            allow_retrieve_keytab_hostgroup=dict(
                type="list",
                required=False,
                aliases=['ipaallowedtoperform_read_keys_hostgroup']),
            delete_continue=dict(type="bool",
                                 required=False,
                                 aliases=['continue']),
            # action
            action=dict(type="str",
                        default="service",
                        choices=["member", "service"]),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent", "disabled"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    return ansible_module
Example #8
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            name=dict(type="list",
                      aliases=["idnsname"],
                      default=None,
                      required=True),
            # present
            description=dict(required=False, type='str', default=None),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    description = ansible_module.params_get("description")

    # state
    state = ansible_module.params_get("state")

    # Check parameters

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one location be added at a time.")

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        invalid = ["description"]
        for x in invalid:
            if vars()[x] is not None:
                ansible_module.fail_json(
                    msg="Argument '%s' can not be used with state '%s'" %
                    (x, state))

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():
        commands = []
        for name in names:
            # Make sure location exists
            res_find = find_location(ansible_module, name)

            # Create command
            if state == "present":

                # Generate args
                args = gen_args(description)

                # Found the location
                if res_find is not None:
                    # For all settings is args, check if there are
                    # different settings in the find result.
                    # If yes: modify
                    if not compare_args_ipa(ansible_module, args, res_find):
                        commands.append([name, "location_mod", args])
                else:
                    commands.append([name, "location_add", args])

            elif state == "absent":
                if res_find is not None:
                    commands.append([name, "location_del", {}])

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

        # Execute commands
        changed = ansible_module.execute_ipa_commands(commands)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #9
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            maxusername=dict(type="int",
                             required=False,
                             aliases=['ipamaxusernamelength']),
            maxhostname=dict(type="int",
                             required=False,
                             aliases=['ipamaxhostnamelength']),
            homedirectory=dict(type="str",
                               required=False,
                               aliases=['ipahomesrootdir']),
            defaultshell=dict(type="str",
                              required=False,
                              aliases=['ipadefaultloginshell', 'loginshell']),
            defaultgroup=dict(type="str",
                              required=False,
                              aliases=['ipadefaultprimarygroup']),
            emaildomain=dict(type="str",
                             required=False,
                             aliases=['ipadefaultemaildomain']),
            searchtimelimit=dict(type="int",
                                 required=False,
                                 aliases=['ipasearchtimelimit']),
            searchrecordslimit=dict(type="int",
                                    required=False,
                                    aliases=['ipasearchrecordslimit']),
            usersearch=dict(type="list",
                            required=False,
                            aliases=['ipausersearchfields']),
            groupsearch=dict(type="list",
                             required=False,
                             aliases=['ipagroupsearchfields']),
            enable_migration=dict(type="bool",
                                  required=False,
                                  aliases=['ipamigrationenabled']),
            groupobjectclasses=dict(type="list",
                                    required=False,
                                    aliases=['ipagroupobjectclasses']),
            userobjectclasses=dict(type="list",
                                   required=False,
                                   aliases=['ipauserobjectclasses']),
            pwdexpnotify=dict(type="int",
                              required=False,
                              aliases=['ipapwdexpadvnotify']),
            configstring=dict(type="list",
                              required=False,
                              aliases=['ipaconfigstring'],
                              choices=[
                                  "AllowNThash", "KDC:Disable Last Success",
                                  "KDC:Disable Lockout",
                                  "KDC:Disable Default Preauth for SPNs", ""
                              ]),  # noqa E128
            selinuxusermaporder=dict(type="list",
                                     required=False,
                                     aliases=['ipaselinuxusermaporder']),
            selinuxusermapdefault=dict(type="str",
                                       required=False,
                                       aliases=['ipaselinuxusermapdefault']),
            pac_type=dict(type="list",
                          required=False,
                          aliases=["ipakrbauthzdata"],
                          choices=["MS-PAC", "PAD", "nfs:NONE", ""]),
            user_auth_type=dict(
                type="list",
                required=False,
                choices=["password", "radius", "otp", "disabled", ""],
                aliases=["ipauserauthtype"]),
            ca_renewal_master_server=dict(type="str", required=False),
            domain_resolution_order=dict(type="list",
                                         required=False,
                                         aliases=["ipadomainresolutionorder"
                                                  ])),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    field_map = {
        "maxusername": "******",
        "maxhostname": "ipamaxhostnamelength",
        "homedirectory": "ipahomesrootdir",
        "defaultshell": "ipadefaultloginshell",
        "defaultgroup": "ipadefaultprimarygroup",
        "emaildomain": "ipadefaultemaildomain",
        "searchtimelimit": "ipasearchtimelimit",
        "searchrecordslimit": "ipasearchrecordslimit",
        "usersearch": "ipausersearchfields",
        "groupsearch": "ipagroupsearchfields",
        "enable_migration": "ipamigrationenabled",
        "groupobjectclasses": "ipagroupobjectclasses",
        "userobjectclasses": "ipauserobjectclasses",
        "pwdexpnotify": "ipapwdexpadvnotify",
        "configstring": "ipaconfigstring",
        "selinuxusermaporder": "ipaselinuxusermaporder",
        "selinuxusermapdefault": "ipaselinuxusermapdefault",
        "pac_type": "ipakrbauthzdata",
        "user_auth_type": "ipauserauthtype",
        "ca_renewal_master_server": "ca_renewal_master_server",
        "domain_resolution_order": "ipadomainresolutionorder"
    }
    reverse_field_map = {v: k for k, v in field_map.items()}

    params = {}
    for x in field_map:
        val = ansible_module.params_get(x)

        if val is not None:
            params[field_map.get(x, x)] = val

    if params.get("ipamigrationenabled") is not None:
        params["ipamigrationenabled"] = \
            str(params["ipamigrationenabled"]).upper()

    if params.get("ipaselinuxusermaporder", None):
        params["ipaselinuxusermaporder"] = \
            "$".join(params["ipaselinuxusermaporder"])

    if params.get("ipadomainresolutionorder", None):
        params["ipadomainresolutionorder"] = \
             ":".join(params["ipadomainresolutionorder"])

    if params.get("ipausersearchfields", None):
        params["ipausersearchfields"] = \
             ",".join(params["ipausersearchfields"])

    if params.get("ipagroupsearchfields", None):
        params["ipagroupsearchfields"] = \
             ",".join(params["ipagroupsearchfields"])

    # verify limits on INT values.
    args_with_limits = [
        ("ipamaxusernamelength", 1, 255),
        ("ipamaxhostnamelength", 64, 255),
        ("ipasearchtimelimit", -1, 2147483647),
        ("ipasearchrecordslimit", -1, 2147483647),
        ("ipapwdexpadvnotify", 0, 2147483647),
    ]
    for arg, minimum, maximum in args_with_limits:
        if arg in params and (params[arg] > maximum or params[arg] < minimum):
            ansible_module.fail_json(
                msg="Argument '%s' must be between %d and %d." %
                (arg, minimum, maximum))

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        result = config_show(ansible_module)
        if params:
            params = {
                k: v
                for k, v in params.items() if k not in result or result[k] != v
            }
            if params \
               and not compare_args_ipa(ansible_module, params, result):
                changed = True
                if not ansible_module.check_mode:
                    try:
                        ansible_module.ipa_command_no_name(
                            "config_mod", params)
                    except ipalib_errors.EmptyModlist:
                        changed = False
        else:
            del result['dn']
            type_map = {"str": str, "int": int, "list": list, "bool": bool}
            for key, value in result.items():
                k = reverse_field_map.get(key, key)
                if ansible_module.argument_spec.get(k):
                    arg_type = ansible_module.argument_spec[k]['type']
                    if k in ('ipaselinuxusermaporder',
                             'domain_resolution_order'):
                        exit_args[k] = result.get(key)[0].split('$')
                    elif k in ('usersearch', 'groupsearch'):
                        exit_args[k] = result.get(key)[0].split(',')
                    elif isinstance(value, str) and arg_type == "list":
                        exit_args[k] = [value]
                    elif (isinstance(value, (tuple, list))
                          and arg_type in ("str", "int")):
                        exit_args[k] = type_map[arg_type](value[0])
                    elif (isinstance(value, (tuple, list))
                          and arg_type == "bool"):
                        exit_args[k] = (value[0] == "TRUE")
                    else:
                        if arg_type not in type_map:
                            raise ValueError("Unexpected attribute type: %s" %
                                             arg_type)
                        exit_args[k] = type_map[arg_type](value)

    # Done
    ansible_module.exit_json(changed=changed, config=exit_args)
Example #10
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            # present
            right=dict(type="list",
                       aliases=["ipapermright"],
                       default=None,
                       required=False,
                       choices=[
                           "read", "search", "compare", "write", "add",
                           "delete", "all"
                       ]),
            attrs=dict(type="list", default=None, required=False),
            # Note: bindtype has a default of permission for Adds.
            bindtype=dict(type="str",
                          aliases=["ipapermbindruletype"],
                          default=None,
                          require=False,
                          choices=["permission", "all", "anonymous", "self"]),
            subtree=dict(type="str",
                         aliases=["ipapermlocation"],
                         default=None,
                         required=False),
            extra_target_filter=dict(type="list",
                                     aliases=["filter", "extratargetfilter"],
                                     default=None,
                                     required=False),
            rawfilter=dict(type="list",
                           aliases=["ipapermtargetfilter"],
                           default=None,
                           required=False),
            target=dict(type="str",
                        aliases=["ipapermtarget"],
                        default=None,
                        required=False),
            targetto=dict(type="str",
                          aliases=["ipapermtargetto"],
                          default=None,
                          required=False),
            targetfrom=dict(type="str",
                            aliases=["ipapermtargetfrom"],
                            default=None,
                            required=False),
            memberof=dict(type="list", default=None, required=False),
            targetgroup=dict(type="str", default=None, required=False),
            object_type=dict(type="str",
                             aliases=["type"],
                             default=None,
                             required=False),
            no_members=dict(type=bool, default=None, require=False),
            rename=dict(type="str",
                        default=None,
                        required=False,
                        aliases=["new_name"]),
            action=dict(type="str",
                        default="permission",
                        choices=["member", "permission"]),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent", "renamed"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    right = ansible_module.params_get("right")
    attrs = ansible_module.params_get("attrs")
    bindtype = ansible_module.params_get("bindtype")
    subtree = ansible_module.params_get("subtree")
    extra_target_filter = ansible_module.params_get("extra_target_filter")
    rawfilter = ansible_module.params_get("rawfilter")
    target = ansible_module.params_get("target")
    targetto = ansible_module.params_get("targetto")
    targetfrom = ansible_module.params_get("targetfrom")
    memberof = ansible_module.params_get("memberof")
    targetgroup = ansible_module.params_get("targetgroup")
    object_type = ansible_module.params_get("object_type")
    no_members = ansible_module.params_get("no_members")
    rename = ansible_module.params_get("rename")
    action = ansible_module.params_get("action")

    # state
    state = ansible_module.params_get("state")

    # Check parameters

    invalid = []

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one permission can be added at a time.")
        if action == "member":
            invalid = [
                "bindtype", "target", "targetto", "targetfrom", "subtree",
                "targetgroup", "object_type", "rename"
            ]
        else:
            invalid = ["rename"]

    if state == "renamed":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one permission can be renamed at a time.")
        if action == "member":
            ansible_module.fail_json(
                msg="Member action can not be used with state 'renamed'")
        invalid = [
            "right", "attrs", "bindtype", "subtree", "extra_target_filter",
            "rawfilter", "target", "targetto", "targetfrom", "memberof",
            "targetgroup", "object_type", "no_members"
        ]

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        invalid = [
            "bindtype", "subtree", "target", "targetto", "targetfrom",
            "targetgroup", "object_type", "no_members", "rename"
        ]
        if action != "member":
            invalid += [
                "right", "attrs", "memberof", "extra_target_filter",
                "rawfilter"
            ]

    ansible_module.params_fail_used_invalid(invalid, state, action)

    if bindtype == "self" and ansible_module.ipa_check_version("<", "4.8.7"):
        ansible_module.fail_json(
            msg="Bindtype 'self' is not supported by your IPA version.")

    if all([extra_target_filter, rawfilter]):
        ansible_module.fail_json(
            msg="Cannot specify target filter and extra target filter "
            "simultaneously.")

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        commands = []
        for name in names:
            # Make sure permission exists
            res_find = find_permission(ansible_module, name)

            # Create command
            if state == "present":
                # Generate args
                args = gen_args(right, attrs, bindtype, subtree,
                                extra_target_filter, rawfilter, target,
                                targetto, targetfrom, memberof, targetgroup,
                                object_type, no_members, rename)

                if action == "permission":
                    # Found the permission
                    if res_find is not None:
                        # For all settings is args, check if there are
                        # different settings in the find result.
                        # If yes: modify
                        if not compare_args_ipa(ansible_module, args,
                                                res_find):
                            commands.append([name, "permission_mod", args])
                    else:
                        commands.append([name, "permission_add", args])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No permission '%s'" %
                                                 name)

                    member_attrs = {}
                    check_members = {
                        "attrs": attrs,
                        "memberof": memberof,
                        "ipapermright": right,
                        "ipapermtargetfilter": rawfilter,
                        "extratargetfilter": extra_target_filter,
                        # subtree member management is currently disabled.
                        # "ipapermlocation": subtree,
                    }

                    for _member, _member_change in check_members.items():
                        if _member_change is not None:
                            _res_list = res_find[_member]
                            # if running in a client context, data may be
                            # returned as a tuple instead of a list.
                            if isinstance(_res_list, tuple):
                                _res_list = list(_res_list)
                            _new_set = set(_res_list + _member_change)
                            if _new_set != set(_res_list):
                                member_attrs[_member] = list(_new_set)

                    if member_attrs:
                        commands.append([name, "permission_mod", member_attrs])

                else:
                    ansible_module.fail_json(msg="Unknown action '%s'" %
                                             action)

            elif state == "renamed":
                if action == "permission":
                    # Generate args
                    # Note: Only valid arg for rename is rename.
                    args = gen_args(right, attrs, bindtype, subtree,
                                    extra_target_filter, rawfilter, target,
                                    targetto, targetfrom, memberof,
                                    targetgroup, object_type, no_members,
                                    rename)

                    # Found the permission
                    if res_find is not None:
                        # For all settings is args, check if there are
                        # different settings in the find result.
                        # If yes: modify
                        if not compare_args_ipa(ansible_module, args,
                                                res_find):
                            commands.append([name, "permission_mod", args])
                    else:
                        ansible_module.fail_json(
                            msg="Permission not found, cannot rename")
                else:
                    ansible_module.fail_json(msg="Unknown action '%s'" %
                                             action)

            elif state == "absent":
                if action == "permission":
                    if res_find is not None:
                        commands.append([name, "permission_del", {}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No permission '%s'" %
                                                 name)

                    member_attrs = {}
                    check_members = {
                        "attrs": attrs,
                        "memberof": memberof,
                        "ipapermright": right,
                        "ipapermtargetfilter": rawfilter,
                        "extratargetfilter": extra_target_filter,
                        # subtree member management is currently disabled.
                        # "ipapermlocation": subtree,
                    }

                    for _member, _member_change in check_members.items():
                        if _member_change is not None:
                            _res_set = set(res_find[_member])
                            _new_set = _res_set - set(_member_change)
                            if _new_set != _res_set:
                                member_attrs[_member] = list(_new_set)

                    if member_attrs:
                        commands.append([name, "permission_mod", member_attrs])

            else:
                ansible_module.fail_json(msg="Unknown state '%s'" % state)

        # Execute commands

        changed = ansible_module.execute_ipa_commands(commands, result_handler)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #11
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            # present
            description=dict(type="str", default=None),
            nomembers=dict(required=False, type='bool', default=None),
            hbacsvc=dict(required=False, type='list', default=None),
            action=dict(type="str",
                        default="hbacsvcgroup",
                        choices=["member", "hbacsvcgroup"]),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    description = ansible_module.params_get("description")
    nomembers = ansible_module.params_get("nomembers")
    hbacsvc = ansible_module.params_get_lowercase("hbacsvc")
    action = ansible_module.params_get("action")
    # state
    state = ansible_module.params_get("state")

    # Check parameters

    invalid = []

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one hbacsvcgroup can be added at a time.")
        if action == "member":
            invalid = ["description", "nomembers"]

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        invalid = ["description", "nomembers"]
        if action == "hbacsvcgroup":
            invalid.extend(["hbacsvc"])

    ansible_module.params_fail_used_invalid(invalid, state, action)

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        commands = []

        for name in names:
            # Make sure hbacsvcgroup exists
            res_find = find_hbacsvcgroup(ansible_module, name)

            hbacsvc_add, hbacsvc_del = [], []

            # Create command
            if state == "present":
                # Generate args
                args = gen_args(description, nomembers)

                if action == "hbacsvcgroup":
                    # Found the hbacsvcgroup
                    if res_find is not None:
                        # For all settings is args, check if there are
                        # different settings in the find result.
                        # If yes: modify
                        if not compare_args_ipa(ansible_module, args,
                                                res_find):
                            commands.append([name, "hbacsvcgroup_mod", args])
                    else:
                        commands.append([name, "hbacsvcgroup_add", args])
                        # Set res_find to empty dict for next step
                        res_find = {}

                    member_args = gen_member_args(hbacsvc)
                    if not compare_args_ipa(ansible_module, member_args,
                                            res_find):
                        # Generate addition and removal lists
                        if hbacsvc is not None:
                            hbacsvc_add, hbacsvc_del = gen_add_del_lists(
                                hbacsvc, res_find.get("member_hbacsvc"))

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No hbacsvcgroup '%s'" %
                                                 name)

                    # Ensure members are present
                    if hbacsvc:
                        hbacsvc_add = gen_add_list(
                            hbacsvc, res_find.get("member_hbacsvc"))

            elif state == "absent":
                if action == "hbacsvcgroup":
                    if res_find is not None:
                        commands.append([name, "hbacsvcgroup_del", {}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No hbacsvcgroup '%s'" %
                                                 name)

                    # Ensure members are absent
                    if hbacsvc:
                        hbacsvc_del = gen_intersection_list(
                            hbacsvc, res_find.get("member_hbacsvc"))

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

            # Manage members
            if len(hbacsvc_add) > 0:
                commands.append([
                    name, "hbacsvcgroup_add_member", {
                        "hbacsvc": hbacsvc_add
                    }
                ])
            # Remove members
            if len(hbacsvc_del) > 0:
                commands.append([
                    name, "hbacsvcgroup_remove_member", {
                        "hbacsvc": hbacsvc_del
                    }
                ])

        # Execute commands
        changed = ansible_module.execute_ipa_commands(commands, result_handler)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #12
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list",
                      aliases=["cn", "service"],
                      default=None,
                      required=True),
            # present
            description=dict(type="str", default=None),

            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    description = ansible_module.params_get("description")

    # state
    state = ansible_module.params_get("state")

    # Check parameters

    invalid = []
    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one hbacsvc can be set at a time.")

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        invalid = ["description"]

    ansible_module.params_fail_used_invalid(invalid, state)

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        commands = []

        for name in names:
            # Try to find hbacsvc
            res_find = find_hbacsvc(ansible_module, name)

            # Create command
            if state == "present":
                # Generate args
                args = gen_args(description)

                # Found the hbacsvc
                if res_find is not None:
                    # For all settings is args, check if there are
                    # different settings in the find result.
                    # If yes: modify
                    if not compare_args_ipa(ansible_module, args, res_find):
                        commands.append([name, "hbacsvc_mod", args])
                else:
                    commands.append([name, "hbacsvc_add", args])

            elif state == "absent":
                if res_find is not None:
                    commands.append([name, "hbacsvc_del", {}])

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

        # Execute commands

        changed = ansible_module.execute_ipa_commands(commands)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #13
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            # present
            description=dict(type="str", default=None),
            nomembers=dict(required=False, type='bool', default=None),
            host=dict(required=False, type='list', default=None),
            hostgroup=dict(required=False, type='list', default=None),
            membermanager_user=dict(required=False, type='list', default=None),
            membermanager_group=dict(required=False, type='list',
                                     default=None),
            rename=dict(required=False, type='str', default=None,
                        aliases=["new_name"]),
            action=dict(type="str", default="hostgroup",
                        choices=["member", "hostgroup"]),
            # state
            state=dict(type="str", default="present",
                       choices=["present", "absent", "renamed"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    description = ansible_module.params_get("description")
    nomembers = ansible_module.params_get("nomembers")
    host = ansible_module.params_get("host")
    hostgroup = ansible_module.params_get("hostgroup")
    membermanager_user = ansible_module.params_get("membermanager_user")
    membermanager_group = ansible_module.params_get("membermanager_group")
    rename = ansible_module.params_get("rename")
    action = ansible_module.params_get("action")
    # state
    state = ansible_module.params_get("state")

    # Check parameters

    invalid = []
    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one hostgroup can be added at a time.")
        invalid = ["rename"]
        if action == "member":
            invalid.extend(["description", "nomembers"])

    if state == "renamed":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one hostgroup can be added at a time.")
        if action == "member":
            ansible_module.fail_json(
                msg="Action '%s' can not be used with state '%s'" %
                (action, state))
        invalid = [
            "description", "nomembers", "host", "hostgroup",
            "membermanager_user", "membermanager_group"
        ]

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(
                msg="No name given.")
        invalid = ["description", "nomembers", "rename"]
        if action == "hostgroup":
            invalid.extend(["host", "hostgroup"])

    ansible_module.params_fail_used_invalid(invalid, state, action)

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        has_add_membermanager = ansible_module.ipa_command_exists(
            "hostgroup_add_member_manager")
        if ((membermanager_user is not None or
             membermanager_group is not None) and not has_add_membermanager):
            ansible_module.fail_json(
                msg="Managing a membermanager user or group is not supported "
                "by your IPA version"
            )
        has_mod_rename = ansible_module.ipa_command_param_exists(
            "hostgroup_mod", "rename")
        if not has_mod_rename and rename is not None:
            ansible_module.fail_json(
                msg="Renaming hostgroups is not supported by your IPA version")

        # If hosts are given, ensure that the hosts are FQDN and also
        # lowercase to be able to do a proper comparison to exising hosts
        # in the hostgroup.
        # Fixes #666 (ipahostgroup not idempotent and with error)
        if host is not None:
            default_domain = ansible_module.ipa_get_domain()
            host = [ensure_fqdn(_host, default_domain).lower()
                    for _host in host]

        commands = []

        for name in names:
            # Make sure hostgroup exists
            res_find = find_hostgroup(ansible_module, name)

            # Create command
            if state == "present":
                # Generate args
                args = gen_args(description, nomembers, rename)

                if action == "hostgroup":
                    # Found the hostgroup
                    if res_find is not None:
                        # For all settings is args, check if there are
                        # different settings in the find result.
                        # If yes: modify
                        if not compare_args_ipa(ansible_module, args,
                                                res_find):
                            commands.append([name, "hostgroup_mod", args])
                    else:
                        commands.append([name, "hostgroup_add", args])
                        # Set res_find to empty dict for next step
                        res_find = {}

                    member_args = gen_member_args(host, hostgroup)
                    if not compare_args_ipa(ansible_module, member_args,
                                            res_find):
                        # Generate addition and removal lists
                        host_add, host_del = gen_add_del_lists(
                            host, res_find.get("member_host"))

                        hostgroup_add, hostgroup_del = gen_add_del_lists(
                            hostgroup, res_find.get("member_hostgroup"))

                        # Add members
                        if len(host_add) > 0 or len(hostgroup_add) > 0:
                            commands.append([name, "hostgroup_add_member",
                                             {
                                                 "host": host_add,
                                                 "hostgroup": hostgroup_add,
                                             }])
                        # Remove members
                        if len(host_del) > 0 or len(hostgroup_del) > 0:
                            commands.append([name, "hostgroup_remove_member",
                                             {
                                                 "host": host_del,
                                                 "hostgroup": hostgroup_del,
                                             }])

                    membermanager_user_add, membermanager_user_del = \
                        gen_add_del_lists(
                            membermanager_user,
                            res_find.get("membermanager_user")
                        )

                    membermanager_group_add, membermanager_group_del = \
                        gen_add_del_lists(
                            membermanager_group,
                            res_find.get("membermanager_group")
                        )

                    if has_add_membermanager:
                        # Add membermanager users and groups
                        if len(membermanager_user_add) > 0 or \
                           len(membermanager_group_add) > 0:
                            commands.append(
                                [name, "hostgroup_add_member_manager",
                                 {
                                     "user": membermanager_user_add,
                                     "group": membermanager_group_add,
                                 }]
                            )
                        # Remove member manager
                        if len(membermanager_user_del) > 0 or \
                           len(membermanager_group_del) > 0:
                            commands.append(
                                [name, "hostgroup_remove_member_manager",
                                 {
                                     "user": membermanager_user_del,
                                     "group": membermanager_group_del,
                                 }]
                            )

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(
                            msg="No hostgroup '%s'" % name)

                    # Reduce add lists for member_host and member_hostgroup,
                    # to new entries only that are not in res_find.
                    if host is not None and "member_host" in res_find:
                        host = gen_add_list(host, res_find["member_host"])
                    if hostgroup is not None \
                       and "member_hostgroup" in res_find:
                        hostgroup = gen_add_list(
                            hostgroup, res_find["member_hostgroup"])

                    # Ensure members are present
                    commands.append([name, "hostgroup_add_member",
                                     {
                                         "host": host,
                                         "hostgroup": hostgroup,
                                     }])

                    if has_add_membermanager:
                        # Reduce add list for membermanager_user and
                        # membermanager_group to new entries only that are
                        # not in res_find.
                        if membermanager_user is not None \
                           and "membermanager_user" in res_find:
                            membermanager_user = gen_add_list(
                                membermanager_user,
                                res_find["membermanager_user"])
                        if membermanager_group is not None \
                           and "membermanager_group" in res_find:
                            membermanager_group = gen_add_list(
                                membermanager_group,
                                res_find["membermanager_group"])

                        # Add membermanager users and groups
                        if membermanager_user is not None or \
                           membermanager_group is not None:
                            commands.append(
                                [name, "hostgroup_add_member_manager",
                                 {
                                     "user": membermanager_user,
                                     "group": membermanager_group,
                                 }]
                            )

            elif state == "renamed":
                if res_find is not None:
                    if rename != name:
                        commands.append(
                            [name, "hostgroup_mod", {"rename": rename}]
                        )
                else:
                    # If a hostgroup with the desired name exists, do nothing.
                    new_find = find_hostgroup(ansible_module, rename)
                    if new_find is None:
                        # Fail only if the either hostsgroups do not exist.
                        ansible_module.fail_json(
                            msg="Attribute `rename` can not be used, unless "
                                "hostgroup exists."
                        )

            elif state == "absent":
                if action == "hostgroup":
                    if res_find is not None:
                        commands.append([name, "hostgroup_del", {}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(
                            msg="No hostgroup '%s'" % name)

                    # Reduce del lists of member_host and member_hostgroup,
                    # to the entries only that are in res_find.
                    if host is not None:
                        host = gen_intersection_list(
                            host, res_find.get("member_host"))
                    if hostgroup is not None:
                        hostgroup = gen_intersection_list(
                            hostgroup, res_find.get("member_hostgroup"))

                    # Ensure members are absent
                    commands.append([name, "hostgroup_remove_member",
                                     {
                                         "host": host,
                                         "hostgroup": hostgroup,
                                     }])

                    if has_add_membermanager:
                        # Reduce del lists of membermanager_user and
                        # membermanager_group to the entries only that are
                        # in res_find.
                        if membermanager_user is not None:
                            membermanager_user = gen_intersection_list(
                                membermanager_user,
                                res_find.get("membermanager_user"))
                        if membermanager_group is not None:
                            membermanager_group = gen_intersection_list(
                                membermanager_group,
                                res_find.get("membermanager_group"))

                        # Remove membermanager users and groups
                        if membermanager_user is not None or \
                           membermanager_group is not None:
                            commands.append(
                                [name, "hostgroup_remove_member_manager",
                                 {
                                     "user": membermanager_user,
                                     "group": membermanager_group,
                                 }]
                            )

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

        # Execute commands

        changed = ansible_module.execute_ipa_commands(
            commands, fail_on_member_errors=True)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            # present
            principal=dict(required=False, type='list', default=None),
            target=dict(required=False, type='list',
                        aliases=["servicedelegationtarget"], default=None),

            action=dict(type="str", default="servicedelegationrule",
                        choices=["member", "servicedelegationrule"]),
            # state
            state=dict(type="str", default="present",
                       choices=["present", "absent"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    principal = ansible_module.params_get("principal")
    target = ansible_module.params_get("target")

    action = ansible_module.params_get("action")

    # state
    state = ansible_module.params_get("state")

    # Check parameters

    invalid = []

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one servicedelegationrule can be added at a time.")

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        if action == "servicedelegationrule":
            invalid = ["principal", "target"]

    ansible_module.params_fail_used_invalid(invalid, state, action)

    # Init

    membertarget = "ipaallowedtarget_servicedelegationtarget"
    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        # Normalize principals
        if principal:
            principal = servicedelegation_normalize_principals(
                ansible_module, principal, state == "present")
        if target and state == "present":
            check_targets(ansible_module, target)

        commands = []
        principal_add = principal_del = []
        target_add = target_del = []
        for name in names:
            # Make sure servicedelegationrule exists
            res_find = find_servicedelegationrule(ansible_module, name)

            # Create command
            if state == "present":

                if action == "servicedelegationrule":
                    # A servicedelegationrule does not have normal options.
                    # There is no servicedelegationtarget-mod command.
                    # Principal members are handled with the _add_member and
                    # _remove_member commands further down.
                    if res_find is None:
                        commands.append([name, "servicedelegationrule_add",
                                         {}])
                        res_find = {}

                    # Generate addition and removal lists for principal
                    principal_add, principal_del = gen_add_del_lists(
                        principal, res_find.get("memberprincipal"))

                    # Generate addition and removal lists for target
                    target_add, target_del = gen_add_del_lists(
                        target, res_find.get(membertarget))

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(
                            msg="No servicedelegationrule '%s'" % name)

                    # Reduce add lists for principal
                    # to new entries only that are not in res_find.
                    if principal is not None and \
                       "memberprincipal" in res_find:
                        principal_add = gen_add_list(
                            principal, res_find["memberprincipal"])
                    else:
                        principal_add = principal

                    # Reduce add lists for target
                    # to new entries only that are not in res_find.
                    if target is not None and membertarget in res_find:
                        target_add = gen_add_list(
                            target, res_find[membertarget])
                    else:
                        target_add = target

            elif state == "absent":
                if action == "servicedelegationrule":
                    if res_find is not None:
                        commands.append([name, "servicedelegationrule_del",
                                         {}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(
                            msg="No servicedelegationrule '%s'" % name)

                    # Reduce del lists of principals to the entries only
                    # that are in res_find.
                    if principal is not None:
                        principal_del = gen_intersection_list(
                            principal, res_find.get("memberprincipal"))
                    else:
                        principal_del = principal

                    # Reduce del lists of targets to the entries only
                    # that are in res_find.
                    if target is not None:
                        target_del = gen_intersection_list(
                            target, res_find.get(membertarget))
                    else:
                        target_del = target

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

            # Handle members

            # Add principal members
            if principal_add is not None and len(principal_add) > 0:
                commands.append(
                    [name, "servicedelegationtarget_add_member",
                     {
                         "principal": principal_add,
                     }])
            # Remove principal members
            if principal_del is not None and len(principal_del) > 0:
                commands.append(
                    [name, "servicedelegationtarget_remove_member",
                     {
                         "principal": principal_del,
                     }])

            # Add target members
            if target_add is not None and len(target_add) > 0:
                commands.append(
                    [name, "servicedelegationrule_add_target",
                     {
                         "servicedelegationtarget": target_add,
                     }])
            # Remove target members
            if target_del is not None and len(target_del) > 0:
                commands.append(
                    [name, "servicedelegationrule_remove_target",
                     {
                         "servicedelegationtarget": target_del,
                     }])

        # Execute commands

        changed = ansible_module.execute_ipa_commands(
            commands, fail_on_member_errors=True)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            suffix=dict(choices=["domain", "ca", "domain+ca"], required=True),
            name=dict(type="str", aliases=["cn"], default=None),
            left=dict(type="str", aliases=["leftnode"], default=None),
            right=dict(type="str", aliases=["rightnode"], default=None),
            direction=dict(type="str",
                           default=None,
                           choices=["left-to-right", "right-to-left"]),
            state=dict(type="str",
                       default="present",
                       choices=[
                           "present", "absent", "enabled", "disabled",
                           "reinitialized", "checked"
                       ]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    suffixes = ansible_module.params_get("suffix")
    name = ansible_module.params_get("name")
    left = ansible_module.params_get("left")
    right = ansible_module.params_get("right")
    direction = ansible_module.params_get("direction")
    state = ansible_module.params_get("state")

    # Check parameters

    if state != "reinitialized" and direction is not None:
        ansible_module.fail_json(
            msg="Direction is not supported in this mode.")

    # Init

    changed = False
    exit_args = {}

    with ansible_module.ipa_connect():
        commands = []

        for suffix in suffixes.split("+"):
            # Create command
            if state in ["present", "enabled"]:
                # Make sure topology segment exists

                if left is None or right is None:
                    ansible_module.fail_json(
                        msg="Left and right need to be set.")
                args = {
                    "iparepltoposegmentleftnode": left,
                    "iparepltoposegmentrightnode": right,
                }
                if name is not None:
                    args["cn"] = name

                res_left_right = find_left_right(ansible_module, suffix, left,
                                                 right)
                if res_left_right is not None:
                    if name is not None and \
                       res_left_right["cn"][0] != name:
                        ansible_module.fail_json(
                            msg="Left and right nodes already used with "
                            "different name (cn) '%s'" % res_left_right["cn"])

                    # Left and right nodes and also the name can not be
                    # changed
                    for key in [
                            "iparepltoposegmentleftnode",
                            "iparepltoposegmentrightnode"
                    ]:
                        if key in args:
                            del args[key]
                    if len(args) > 1:
                        # cn needs to be in args always
                        commands.append(["topologysegment_mod", args, suffix])
                    # else: Nothing to change
                else:
                    if name is None:
                        args["cn"] = "%s-to-%s" % (left, right)
                    commands.append(["topologysegment_add", args, suffix])

            elif state in ["absent", "disabled"]:
                # Make sure topology segment does not exist

                res_find = find_left_right_cn(ansible_module, suffix, left,
                                              right, name)
                if res_find is not None:
                    # Found either given name or found name from left and right
                    # node
                    args = {"cn": res_find["cn"][0]}
                    commands.append(["topologysegment_del", args, suffix])

            elif state == "checked":
                # Check if topology segment does exists

                res_find = find_left_right_cn(ansible_module, suffix, left,
                                              right, name)
                if res_find is not None:
                    # Found either given name or found name from left and right
                    # node
                    exit_args.setdefault("found", []).append(suffix)
                else:
                    # Not found
                    exit_args.setdefault("not-found", []).append(suffix)

            elif state == "reinitialized":
                # Reinitialize segment

                if direction not in ["left-to-right", "right-to-left"]:
                    ansible_module.fail_json(msg="Unknown direction '%s'" %
                                             direction)

                res_find = find_left_right_cn(ansible_module, suffix, left,
                                              right, name)
                if res_find is not None:
                    # Found either given name or found name from left and right
                    # node
                    args = {"cn": res_find["cn"][0]}
                    if direction == "left-to-right":
                        args["left"] = True
                    elif direction == "right-to-left":
                        args["right"] = True

                    commands.append(
                        ["topologysegment_reinitialize", args, suffix])
                else:
                    params = []
                    if name is not None:
                        params.append("name=%s" % name)
                    if left is not None:
                        params.append("left=%s" % left)
                    if right is not None:
                        params.append("right=%s" % right)
                    ansible_module.fail_json(
                        msg="No entry '%s' for suffix '%s'" %
                        (",".join(params), suffix))

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

        # Check mode exit
        if ansible_module.check_mode:
            ansible_module.exit_json(changed=len(commands) > 0, **exit_args)

        # Execute command

        for command, args, _suffix in commands:
            ansible_module.ipa_command(command, _suffix, args)
            changed = True

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #16
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            # present
            description=dict(type="str", default=None),
            usercategory=dict(type="str",
                              default=None,
                              aliases=["usercat"],
                              choices=["all", ""]),
            hostcategory=dict(type="str",
                              default=None,
                              aliases=["hostcat"],
                              choices=["all", ""]),
            servicecategory=dict(type="str",
                                 default=None,
                                 aliases=["servicecat"],
                                 choices=["all", ""]),
            nomembers=dict(required=False, type='bool', default=None),
            host=dict(required=False, type='list', default=None),
            hostgroup=dict(required=False, type='list', default=None),
            hbacsvc=dict(required=False, type='list', default=None),
            hbacsvcgroup=dict(required=False, type='list', default=None),
            user=dict(required=False, type='list', default=None),
            group=dict(required=False, type='list', default=None),
            action=dict(type="str",
                        default="hbacrule",
                        choices=["member", "hbacrule"]),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent", "enabled", "disabled"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    description = ansible_module.params_get("description")
    usercategory = ansible_module.params_get("usercategory")
    hostcategory = ansible_module.params_get("hostcategory")
    servicecategory = ansible_module.params_get("servicecategory")
    nomembers = ansible_module.params_get("nomembers")
    host = ansible_module.params_get_lowercase("host")
    hostgroup = ansible_module.params_get_lowercase("hostgroup")
    hbacsvc = ansible_module.params_get_lowercase("hbacsvc")
    hbacsvcgroup = ansible_module.params_get_lowercase("hbacsvcgroup")
    user = ansible_module.params_get_lowercase("user")
    group = ansible_module.params_get_lowercase("group")
    action = ansible_module.params_get("action")
    # state
    state = ansible_module.params_get("state")

    # Check parameters

    invalid = []

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one hbacrule can be added at a time.")
        if action == "member":
            invalid = [
                "description", "usercategory", "hostcategory",
                "servicecategory", "nomembers"
            ]
        else:
            if hostcategory == 'all' and any([host, hostgroup]):
                ansible_module.fail_json(
                    msg="Hosts cannot be added when host category='all'")
            if usercategory == 'all' and any([user, group]):
                ansible_module.fail_json(
                    msg="Users cannot be added when user category='all'")
            if servicecategory == 'all' and any([hbacsvc, hbacsvcgroup]):
                ansible_module.fail_json(
                    msg="Services cannot be added when service category='all'")

    elif state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        invalid = [
            "description", "usercategory", "hostcategory", "servicecategory",
            "nomembers"
        ]
        if action == "hbacrule":
            invalid.extend([
                "host", "hostgroup", "hbacsvc", "hbacsvcgroup", "user", "group"
            ])

    elif state in ["enabled", "disabled"]:
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        if action == "member":
            ansible_module.fail_json(
                msg="Action member can not be used with states enabled and "
                "disabled")
        invalid = [
            "description", "usercategory", "hostcategory", "servicecategory",
            "nomembers", "host", "hostgroup", "hbacsvc", "hbacsvcgroup",
            "user", "group"
        ]
    else:
        ansible_module.fail_json(msg="Invalid state '%s'" % state)

    ansible_module.params_fail_used_invalid(invalid, state, action)

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        # Get default domain
        default_domain = ansible_module.ipa_get_domain()

        # Ensure fqdn host names, use default domain for simple names
        if host is not None:
            _host = [ensure_fqdn(x, default_domain).lower() for x in host]
            host = _host

        commands = []

        for name in names:
            # Make sure hbacrule exists
            res_find = find_hbacrule(ansible_module, name)

            host_add, host_del = [], []
            hostgroup_add, hostgroup_del = [], []
            hbacsvc_add, hbacsvc_del = [], []
            hbacsvcgroup_add, hbacsvcgroup_del = [], []
            user_add, user_del = [], []
            group_add, group_del = [], []

            # Create command
            if state == "present":
                # Generate args
                args = gen_args(description, usercategory, hostcategory,
                                servicecategory, nomembers)

                if action == "hbacrule":
                    # Found the hbacrule
                    if res_find is not None:
                        # Remove usercategory, hostcategory and
                        # servicecategory from args if "" and category
                        # not in res_find (needed for idempotency)
                        if "usercategory" in args and \
                           args["usercategory"] == "" and \
                           "usercategory" not in res_find:
                            del args["usercategory"]
                        if "hostcategory" in args and \
                           args["hostcategory"] == "" and \
                           "hostcategory" not in res_find:
                            del args["hostcategory"]
                        if "servicecategory" in args and \
                           args["servicecategory"] == "" and \
                           "servicecategory" not in res_find:
                            del args["servicecategory"]

                        # For all settings is args, check if there are
                        # different settings in the find result.
                        # If yes: modify
                        if not compare_args_ipa(ansible_module, args,
                                                res_find):
                            commands.append([name, "hbacrule_mod", args])
                    else:
                        commands.append([name, "hbacrule_add", args])
                        # Set res_find to empty dict for next step
                        res_find = {}

                    # Generate addition and removal lists
                    if host is not None:
                        host_add, host_del = gen_add_del_lists(
                            host, res_find.get("memberhost_host"))

                    if hostgroup is not None:
                        hostgroup_add, hostgroup_del = gen_add_del_lists(
                            hostgroup, res_find.get("memberhost_hostgroup"))

                    if hbacsvc is not None:
                        hbacsvc_add, hbacsvc_del = gen_add_del_lists(
                            hbacsvc, res_find.get("memberservice_hbacsvc"))

                    if hbacsvcgroup is not None:
                        hbacsvcgroup_add, hbacsvcgroup_del = gen_add_del_lists(
                            hbacsvcgroup,
                            res_find.get("memberservice_hbacsvcgroup"))

                    if user is not None:
                        user_add, user_del = gen_add_del_lists(
                            user, res_find.get("memberuser_user"))

                    if group is not None:
                        group_add, group_del = gen_add_del_lists(
                            group, res_find.get("memberuser_group"))

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No hbacrule '%s'" % name)

                    # Generate add lists for host, hostgroup and
                    # res_find to only try to add hosts and hostgroups
                    # that not in hbacrule already
                    if host:
                        host_add = gen_add_list(
                            host, res_find.get("memberhost_host"))
                    if hostgroup:
                        hostgroup_add = gen_add_list(
                            hostgroup, res_find.get("memberhost_hostgroup"))

                    # Generate add lists for hbacsvc, hbacsvcgroup and
                    # res_find to only try to add hbacsvcs and hbacsvcgroups
                    # that not in hbacrule already
                    if hbacsvc:
                        hbacsvc_add = gen_add_list(
                            hbacsvc, res_find.get("memberservice_hbacsvc"))
                    if hbacsvcgroup:
                        hbacsvcgroup_add = gen_add_list(
                            hbacsvcgroup,
                            res_find.get("memberservice_hbacsvcgroup"))

                    # Generate add lists for user, group and
                    # res_find to only try to add users and groups
                    # that not in hbacrule already
                    if user:
                        user_add = gen_add_list(
                            user, res_find.get("memberuser_user"))
                    if group:
                        group_add = gen_add_list(
                            group, res_find.get("memberuser_group"))

            elif state == "absent":
                if action == "hbacrule":
                    if res_find is not None:
                        commands.append([name, "hbacrule_del", {}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No hbacrule '%s'" % name)

                    # Generate intersection lists for host, hostgroup and
                    # res_find to only try to remove hosts and hostgroups
                    # that are in hbacrule
                    if host:
                        if "memberhost_host" in res_find:
                            host_del = gen_intersection_list(
                                host, res_find["memberhost_host"])
                    if hostgroup:
                        if "memberhost_hostgroup" in res_find:
                            hostgroup_del = gen_intersection_list(
                                hostgroup, res_find["memberhost_hostgroup"])

                    # Generate intersection lists for hbacsvc, hbacsvcgroup
                    # and res_find to only try to remove hbacsvcs and
                    # hbacsvcgroups that are in hbacrule
                    if hbacsvc:
                        if "memberservice_hbacsvc" in res_find:
                            hbacsvc_del = gen_intersection_list(
                                hbacsvc, res_find["memberservice_hbacsvc"])
                    if hbacsvcgroup:
                        if "memberservice_hbacsvcgroup" in res_find:
                            hbacsvcgroup_del = gen_intersection_list(
                                hbacsvcgroup,
                                res_find["memberservice_hbacsvcgroup"])

                    # Generate intersection lists for user, group and
                    # res_find to only try to remove users and groups
                    # that are in hbacrule
                    if user:
                        if "memberuser_user" in res_find:
                            user_del = gen_intersection_list(
                                user, res_find["memberuser_user"])
                    if group:
                        if "memberuser_group" in res_find:
                            group_del = gen_intersection_list(
                                group, res_find["memberuser_group"])

            elif state == "enabled":
                if res_find is None:
                    ansible_module.fail_json(msg="No hbacrule '%s'" % name)
                # hbacrule_enable is not failing on an enabled hbacrule
                # Therefore it is needed to have a look at the ipaenabledflag
                # in res_find.
                if "ipaenabledflag" not in res_find or \
                   res_find["ipaenabledflag"][0] != "TRUE":
                    commands.append([name, "hbacrule_enable", {}])

            elif state == "disabled":
                if res_find is None:
                    ansible_module.fail_json(msg="No hbacrule '%s'" % name)
                # hbacrule_disable is not failing on an disabled hbacrule
                # Therefore it is needed to have a look at the ipaenabledflag
                # in res_find.
                if "ipaenabledflag" not in res_find or \
                   res_find["ipaenabledflag"][0] != "FALSE":
                    commands.append([name, "hbacrule_disable", {}])

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

            # Manage HBAC rule members.

            # Add hosts and hostgroups
            if len(host_add) > 0 or len(hostgroup_add) > 0:
                commands.append([
                    name, "hbacrule_add_host", {
                        "host": host_add,
                        "hostgroup": hostgroup_add,
                    }
                ])
            # Remove hosts and hostgroups
            if len(host_del) > 0 or len(hostgroup_del) > 0:
                commands.append([
                    name, "hbacrule_remove_host", {
                        "host": host_del,
                        "hostgroup": hostgroup_del,
                    }
                ])

            # Add hbacsvcs and hbacsvcgroups
            if len(hbacsvc_add) > 0 or len(hbacsvcgroup_add) > 0:
                commands.append([
                    name, "hbacrule_add_service", {
                        "hbacsvc": hbacsvc_add,
                        "hbacsvcgroup": hbacsvcgroup_add,
                    }
                ])
            # Remove hbacsvcs and hbacsvcgroups
            if len(hbacsvc_del) > 0 or len(hbacsvcgroup_del) > 0:
                commands.append([
                    name, "hbacrule_remove_service", {
                        "hbacsvc": hbacsvc_del,
                        "hbacsvcgroup": hbacsvcgroup_del,
                    }
                ])

            # Add users and groups
            if len(user_add) > 0 or len(group_add) > 0:
                commands.append([
                    name, "hbacrule_add_user", {
                        "user": user_add,
                        "group": group_add,
                    }
                ])
            # Remove users and groups
            if len(user_del) > 0 or len(group_del) > 0:
                commands.append([
                    name, "hbacrule_remove_user", {
                        "user": user_del,
                        "group": group_del,
                    }
                ])

        # Execute commands

        changed = ansible_module.execute_ipa_commands(
            commands, fail_on_member_errors=True)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #17
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            inclusive=dict(type="list",
                           aliases=["automemberinclusiveregex"],
                           default=None,
                           options=dict(
                               key=dict(type="str", required=True),
                               expression=dict(type="str", required=True)
                           ),
                           elements="dict",
                           required=False),
            exclusive=dict(type="list",
                           aliases=["automemberexclusiveregex"],
                           default=None,
                           options=dict(
                               key=dict(type="str", required=True),
                               expression=dict(type="str", required=True)
                           ),
                           elements="dict",
                           required=False),
            name=dict(type="list", aliases=["cn"],
                      default=None, required=False),
            description=dict(type="str", default=None),
            automember_type=dict(type='str', required=False,
                                 choices=['group', 'hostgroup']),
            no_wait=dict(type="bool", default=None),
            default_group=dict(type="str", default=None),
            action=dict(type="str", default="automember",
                        choices=["member", "automember"]),
            state=dict(type="str", default="present",
                       choices=["present", "absent", "rebuilt",
                                "orphans_removed"]),
            users=dict(type="list", default=None),
            hosts=dict(type="list", default=None),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")
    if names is None:
        names = []

    # present
    description = ansible_module.params_get("description")

    # conditions
    inclusive = ansible_module.params_get("inclusive")
    exclusive = ansible_module.params_get("exclusive")

    # no_wait for rebuilt
    no_wait = ansible_module.params_get("no_wait")

    # default_group
    default_group = ansible_module.params_get("default_group")

    # action
    action = ansible_module.params_get("action")
    # state
    state = ansible_module.params_get("state")

    # grouping/type
    automember_type = ansible_module.params_get("automember_type")

    rebuild_users = ansible_module.params_get("users")
    rebuild_hosts = ansible_module.params_get("hosts")

    # Check parameters
    invalid = []

    if state in ["rebuilt", "orphans_removed"]:
        invalid = ["name", "description", "exclusive", "inclusive",
                   "default_group"]

        if action == "member":
            ansible_module.fail_json(
                msg="'action=member' is not usable with state '%s'" % state)

        if state == "rebuilt":
            if automember_type == "group" and rebuild_hosts is not None:
                ansible_module.fail_json(
                    msg="state %s: hosts can not be set when type is '%s'" %
                    (state, automember_type))
            if automember_type == "hostgroup" and rebuild_users is not None:
                ansible_module.fail_json(
                    msg="state %s: users can not be set when type is '%s'" %
                    (state, automember_type))

        elif state == "orphans_removed":
            invalid.extend(["users", "hosts"])

            if not automember_type:
                ansible_module.fail_json(
                    msg="'automember_type' is required unless state: rebuilt")

    else:
        if default_group is not None:
            for param in ["name", "exclusive", "inclusive", "users", "hosts"
                          "no_wait"]:
                if ansible_module.params.get(param) is not None:
                    msg = "Cannot use {0} together with default_group"
                    ansible_module.fail_json(msg=msg.format(param))
            if action == "member":
                ansible_module.fail_json(
                    msg="Cannot use default_group with action:member")
            if state == "absent":
                ansible_module.fail_json(
                    msg="Cannot use default_group with state:absent")

        else:
            invalid = ["users", "hosts", "no_wait"]

        if not automember_type:
            ansible_module.fail_json(
                msg="'automember_type' is required.")

    ansible_module.params_fail_used_invalid(invalid, state, action)

    # Init
    changed = False
    exit_args = {}
    res_find = None

    with ansible_module.ipa_connect():

        commands = []

        for name in names:
            # Make sure automember rule exists
            res_find = find_automember(ansible_module, name, automember_type)

            # Check inclusive and exclusive conditions
            if inclusive is not None or exclusive is not None:
                # automember_type is either "group" or "hostgorup"
                if automember_type == "group":
                    _type = u"user"
                elif automember_type == "hostgroup":
                    _type = u"host"
                else:
                    ansible_module.fail_json(
                        msg="Bad automember type '%s'" % automember_type)

                try:
                    aciattrs = ansible_module.ipa_command(
                        "json_metadata", _type, {}
                    )['objects'][_type]['aciattrs']
                except Exception as ex:
                    ansible_module.fail_json(
                        msg="%s: %s: %s" % ("json_metadata", _type, str(ex)))

                check_condition_keys(ansible_module, inclusive, aciattrs)
                check_condition_keys(ansible_module, exclusive, aciattrs)

            # Create command
            if state == 'present':
                args = gen_args(description, automember_type)

                if action == "automember":
                    if res_find is not None:
                        if not compare_args_ipa(ansible_module,
                                                args,
                                                res_find,
                                                ignore=['type']):
                            commands.append([name, 'automember_mod', args])
                    else:
                        commands.append([name, 'automember_add', args])
                        res_find = {}

                    if inclusive is not None:
                        inclusive_add, inclusive_del = gen_add_del_lists(
                            transform_conditions(inclusive),
                            res_find.get("automemberinclusiveregex", [])
                        )
                    else:
                        inclusive_add, inclusive_del = [], []

                    if exclusive is not None:
                        exclusive_add, exclusive_del = gen_add_del_lists(
                            transform_conditions(exclusive),
                            res_find.get("automemberexclusiveregex", [])
                        )
                    else:
                        exclusive_add, exclusive_del = [], []

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(
                            msg="No automember '%s'" % name)

                    inclusive_add = transform_conditions(inclusive or [])
                    inclusive_del = []
                    exclusive_add = transform_conditions(exclusive or [])
                    exclusive_del = []

                for _inclusive in inclusive_add:
                    key, regex = _inclusive.split("=", 1)
                    condition_args = gen_condition_args(
                        automember_type, key, inclusiveregex=regex)
                    commands.append([name, 'automember_add_condition',
                                     condition_args])

                for _inclusive in inclusive_del:
                    key, regex = _inclusive.split("=", 1)
                    condition_args = gen_condition_args(
                        automember_type, key, inclusiveregex=regex)
                    commands.append([name, 'automember_remove_condition',
                                     condition_args])

                for _exclusive in exclusive_add:
                    key, regex = _exclusive.split("=", 1)
                    condition_args = gen_condition_args(
                        automember_type, key, exclusiveregex=regex)
                    commands.append([name, 'automember_add_condition',
                                     condition_args])

                for _exclusive in exclusive_del:
                    key, regex = _exclusive.split("=", 1)
                    condition_args = gen_condition_args(
                        automember_type, key, exclusiveregex=regex)
                    commands.append([name, 'automember_remove_condition',
                                     condition_args])

            elif state == 'absent':
                if action == "automember":
                    if res_find is not None:
                        commands.append([name, 'automember_del',
                                         {'type': automember_type}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(
                            msg="No automember '%s'" % name)

                    if inclusive is not None:
                        for _inclusive in transform_conditions(inclusive):
                            key, regex = _inclusive.split("=", 1)
                            condition_args = gen_condition_args(
                                automember_type, key, inclusiveregex=regex)
                            commands.append(
                                [name, 'automember_remove_condition',
                                 condition_args])

                    if exclusive is not None:
                        for _exclusive in transform_conditions(exclusive):
                            key, regex = _exclusive.split("=", 1)
                            condition_args = gen_condition_args(
                                automember_type, key, exclusiveregex=regex)
                            commands.append([name,
                                             'automember_remove_condition',
                                            condition_args])

        if len(names) == 0:
            if state == "rebuilt":
                args = gen_rebuild_args(automember_type, rebuild_users,
                                        rebuild_hosts, no_wait)
                commands.append([None, 'automember_rebuild', args])

            elif state == "orphans_removed":
                res_find = find_automember_orphans(ansible_module,
                                                   automember_type)
                if res_find["count"] > 0:
                    commands.append([None, 'automember_find_orphans',
                                     {'type': automember_type,
                                      'remove': True}])

            elif default_group is not None and state == "present":
                res_find = find_automember_default_group(ansible_module,
                                                         automember_type)

                if default_group == "":
                    if isinstance(res_find["automemberdefaultgroup"], list):
                        commands.append([None,
                                         'automember_default_group_remove',
                                         {'type': automember_type}])

                else:
                    dn_default_group = [DN(('cn', default_group),
                                           ('cn', '%ss' % automember_type),
                                           ('cn', 'accounts'),
                                           ansible_module.ipa_get_basedn())]
                    if repr(res_find["automemberdefaultgroup"]) != \
                       repr(dn_default_group):
                        commands.append(
                            [None, 'automember_default_group_set',
                             {'type': automember_type,
                              'automemberdefaultgroup': default_group}])

            else:
                ansible_module.fail_json(msg="Invalid operation")

        # Execute commands

        changed = ansible_module.execute_ipa_commands(commands)

        # result["failed"] is used only for INCLUDE_RE, EXCLUDE_RE
        # if entries could not be added that are already there and
        # if entries could not be removed that are not there.
        # All other issues like invalid attributes etc. are handled
        # as exceptions. Therefore the error section is not here as
        # in other modules.

    # Done
    ansible_module.exit_json(changed=changed, **exit_args)
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            inclusive=dict(type="list",
                           aliases=["automemberinclusiveregex"], default=None,
                           options=dict(
                               key=dict(type="str", required=True),
                               expression=dict(type="str", required=True)
                           ),
                           elements="dict", required=False),
            exclusive=dict(type="list", aliases=[
                           "automemberexclusiveregex"], default=None,
                           options=dict(
                               key=dict(type="str", required=True),
                               expression=dict(type="str", required=True)
                           ),
                           elements="dict", required=False),
            name=dict(type="list", aliases=["cn"],
                      default=None, required=True),
            description=dict(type="str", default=None),
            automember_type=dict(type='str', required=False,
                                 choices=['group', 'hostgroup']),
            action=dict(type="str", default="automember",
                        choices=["member", "automember"]),
            state=dict(type="str", default="present",
                       choices=["present", "absent", "rebuild"]),
            users=dict(type="list", default=None),
            hosts=dict(type="list", default=None),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    description = ansible_module.params_get("description")

    # conditions
    inclusive = ansible_module.params_get("inclusive")
    exclusive = ansible_module.params_get("exclusive")

    # action
    action = ansible_module.params_get("action")
    # state
    state = ansible_module.params_get("state")

    # grouping/type
    automember_type = ansible_module.params_get("automember_type")

    rebuild_users = ansible_module.params_get("users")
    rebuild_hosts = ansible_module.params_get("hosts")

    if (rebuild_hosts or rebuild_users) and state != "rebuild":
        ansible_module.fail_json(
            msg="'hosts' and 'users' are only valid with state: rebuild")
    if not automember_type and state != "rebuild":
        ansible_module.fail_json(
            msg="'automember_type' is required unless state: rebuild")

    # Init
    changed = False
    exit_args = {}
    res_find = None

    with ansible_module.ipa_connect():

        commands = []

        for name in names:
            # Make sure automember rule exists
            res_find = find_automember(ansible_module, name, automember_type)

            # Check inclusive and exclusive conditions
            if inclusive is not None or exclusive is not None:
                # automember_type is either "group" or "hostgorup"
                if automember_type == "group":
                    _type = u"user"
                elif automember_type == "hostgroup":
                    _type = u"host"
                else:
                    ansible_module.fail_json(
                        msg="Bad automember type '%s'" % automember_type)

                try:
                    aciattrs = ansible_module.ipa_command(
                        "json_metadata", _type, {}
                    )['objects'][_type]['aciattrs']
                except Exception as ex:
                    ansible_module.fail_json(
                        msg="%s: %s: %s" % ("json_metadata", _type, str(ex)))

                check_condition_keys(ansible_module, inclusive, aciattrs)
                check_condition_keys(ansible_module, exclusive, aciattrs)

            # Create command
            if state == 'present':
                args = gen_args(description, automember_type)

                if action == "automember":
                    if res_find is not None:
                        if not compare_args_ipa(ansible_module,
                                                args,
                                                res_find,
                                                ignore=['type']):
                            commands.append([name, 'automember_mod', args])
                    else:
                        commands.append([name, 'automember_add', args])
                        res_find = {}

                    inclusive_add, inclusive_del = gen_add_del_lists(
                        transform_conditions(inclusive or []),
                        res_find.get("automemberinclusiveregex", [])
                    )

                    exclusive_add, exclusive_del = gen_add_del_lists(
                        transform_conditions(exclusive or []),
                        res_find.get("automemberexclusiveregex", [])
                    )

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(
                            msg="No automember '%s'" % name)

                    inclusive_add = transform_conditions(inclusive or [])
                    inclusive_del = []
                    exclusive_add = transform_conditions(exclusive or [])
                    exclusive_del = []

                for _inclusive in inclusive_add:
                    key, regex = _inclusive.split("=", 1)
                    condition_args = gen_condition_args(
                        automember_type, key, inclusiveregex=regex)
                    commands.append([name, 'automember_add_condition',
                                     condition_args])

                for _inclusive in inclusive_del:
                    key, regex = _inclusive.split("=", 1)
                    condition_args = gen_condition_args(
                        automember_type, key, inclusiveregex=regex)
                    commands.append([name, 'automember_remove_condition',
                                     condition_args])

                for _exclusive in exclusive_add:
                    key, regex = _exclusive.split("=", 1)
                    condition_args = gen_condition_args(
                        automember_type, key, exclusiveregex=regex)
                    commands.append([name, 'automember_add_condition',
                                     condition_args])

                for _exclusive in exclusive_del:
                    key, regex = _exclusive.split("=", 1)
                    condition_args = gen_condition_args(
                        automember_type, key, exclusiveregex=regex)
                    commands.append([name, 'automember_remove_condition',
                                     condition_args])

            elif state == 'absent':
                if action == "automember":
                    if res_find is not None:
                        commands.append([name, 'automember_del',
                                         {'type': automember_type}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(
                            msg="No automember '%s'" % name)

                    if inclusive is not None:
                        for _inclusive in transform_conditions(inclusive):
                            key, regex = _inclusive.split("=", 1)
                            condition_args = gen_condition_args(
                                automember_type, key, inclusiveregex=regex)
                            commands.append(
                                [name, 'automember_remove_condition',
                                 condition_args])

                    if exclusive is not None:
                        for _exclusive in transform_conditions(exclusive):
                            key, regex = _exclusive.split("=", 1)
                            condition_args = gen_condition_args(
                                automember_type, key, exclusiveregex=regex)
                            commands.append([name,
                                             'automember_remove_condition',
                                            condition_args])

            elif state == "rebuild":
                if automember_type:
                    commands.append([None, 'automember_rebuild',
                                     {"type": automember_type}])
                if rebuild_users:
                    commands.append([None, 'automember_rebuild',
                                    {"users": rebuild_users}])
                if rebuild_hosts:
                    commands.append([None, 'automember_rebuild',
                                    {"hosts": rebuild_hosts}])

        # Execute commands

        changed = ansible_module.execute_ipa_commands(commands)

        # result["failed"] is used only for INCLUDE_RE, EXCLUDE_RE
        # if entries could not be added that are already there and
        # if entries could not be removed that are not there.
        # All other issues like invalid attributes etc. are handled
        # as exceptions. Therefore the error section is not here as
        # in other modules.

    # Done
    ansible_module.exit_json(changed=changed, **exit_args)
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list",
                      aliases=["cn"],
                      default=None,
                      required=False),
            # present
            maxlife=dict(type="int", aliases=["krbmaxpwdlife"], default=None),
            minlife=dict(type="int", aliases=["krbminpwdlife"], default=None),
            history=dict(type="int",
                         aliases=["krbpwdhistorylength"],
                         default=None),
            minclasses=dict(type="int",
                            aliases=["krbpwdmindiffchars"],
                            default=None),
            minlength=dict(type="int",
                           aliases=["krbpwdminlength"],
                           default=None),
            priority=dict(type="int", aliases=["cospriority"], default=None),
            maxfail=dict(type="int",
                         aliases=["krbpwdmaxfailure"],
                         default=None),
            failinterval=dict(type="int",
                              aliases=["krbpwdfailurecountinterval"],
                              default=None),
            lockouttime=dict(type="int",
                             aliases=["krbpwdlockoutduration"],
                             default=None),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    maxlife = ansible_module.params_get("maxlife")
    minlife = ansible_module.params_get("minlife")
    history = ansible_module.params_get("history")
    minclasses = ansible_module.params_get("minclasses")
    minlength = ansible_module.params_get("minlength")
    priority = ansible_module.params_get("priority")
    maxfail = ansible_module.params_get("maxfail")
    failinterval = ansible_module.params_get("failinterval")
    lockouttime = ansible_module.params_get("lockouttime")

    # state
    state = ansible_module.params_get("state")

    # Check parameters

    if names is None:
        names = [u"global_policy"]

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one pwpolicy can be set at a time.")

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        if "global_policy" in names:
            ansible_module.fail_json(
                msg="'global_policy' can not be made absent.")
        invalid = [
            "maxlife", "minlife", "history", "minclasses", "minlength",
            "priority", "maxfail", "failinterval", "lockouttime"
        ]
        for x in invalid:
            if vars()[x] is not None:
                ansible_module.fail_json(
                    msg="Argument '%s' can not be used with state '%s'" %
                    (x, state))

    # Init

    changed = False
    exit_args = {}

    with ansible_module.ipa_connect():

        commands = []

        for name in names:
            # Try to find pwpolicy
            res_find = find_pwpolicy(ansible_module, name)

            # Create command
            if state == "present":
                # Generate args
                args = gen_args(maxlife, minlife, history, minclasses,
                                minlength, priority, maxfail, failinterval,
                                lockouttime)

                # Found the pwpolicy
                if res_find is not None:
                    # For all settings is args, check if there are
                    # different settings in the find result.
                    # If yes: modify
                    if not compare_args_ipa(ansible_module, args, res_find):
                        commands.append([name, "pwpolicy_mod", args])
                else:
                    commands.append([name, "pwpolicy_add", args])

            elif state == "absent":
                if res_find is not None:
                    commands.append([name, "pwpolicy_del", {}])

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

        # Execute commands

        changed = ansible_module.execute_ipa_commands(commands)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list",
                      aliases=["aciname"],
                      default=None,
                      required=True),
            # present
            permission=dict(required=False,
                            type='list',
                            aliases=["permissions"],
                            default=None),
            attribute=dict(required=False,
                           type='list',
                           aliases=["attrs"],
                           default=None),
            action=dict(type="str",
                        default="selfservice",
                        choices=["member", "selfservice"]),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    permission = ansible_module.params_get("permission")
    attribute = ansible_module.params_get("attribute")
    action = ansible_module.params_get("action")
    # state
    state = ansible_module.params_get("state")

    # Check parameters
    invalid = []

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one selfservice be added at a time.")
        if action == "member":
            invalid = ["permission"]

    if state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        invalid = ["permission"]
        if action == "selfservice":
            invalid.append("attribute")

    ansible_module.params_fail_used_invalid(invalid, state, action)

    if permission is not None:
        perm = [p for p in permission if p not in ("read", "write")]
        if perm:
            ansible_module.fail_json(msg="Invalid permission '%s'" % perm)
        if len(set(permission)) != len(permission):
            ansible_module.fail_json(
                msg="Invalid permission '%s', items are not unique" %
                repr(permission))

    if attribute is not None:
        if len(set(attribute)) != len(attribute):
            ansible_module.fail_json(
                msg="Invalid attribute '%s', items are not unique" %
                repr(attribute))

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        commands = []
        for name in names:
            # Make sure selfservice exists
            res_find = find_selfservice(ansible_module, name)

            # Create command
            if state == "present":

                # Generate args
                args = gen_args(permission, attribute)

                if action == "selfservice":
                    # Found the selfservice
                    if res_find is not None:
                        # For all settings is args, check if there are
                        # different settings in the find result.
                        # If yes: modify
                        if not compare_args_ipa(ansible_module, args,
                                                res_find):
                            commands.append([name, "selfservice_mod", args])
                    else:
                        commands.append([name, "selfservice_add", args])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No selfservice '%s'" %
                                                 name)

                    if attribute is None:
                        ansible_module.fail_json(msg="No attributes given")

                    # New attribute list (add given ones to find result)
                    # Make list with unique entries
                    attrs = list(set(list(res_find["attrs"]) + attribute))
                    if len(attrs) > len(res_find["attrs"]):
                        commands.append(
                            [name, "selfservice_mod", {
                                "attrs": attrs
                            }])

            elif state == "absent":
                if action == "selfservice":
                    if res_find is not None:
                        commands.append([name, "selfservice_del", {}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No selfservice '%s'" %
                                                 name)

                    if attribute is None:
                        ansible_module.fail_json(msg="No attributes given")

                    # New attribute list (remove given ones from find result)
                    # Make list with unique entries
                    attrs = list(set(res_find["attrs"]) - set(attribute))
                    if len(attrs) < 1:
                        ansible_module.fail_json(
                            msg="At minimum one attribute is needed.")

                    # Entries New number of attributes is smaller
                    if len(attrs) < len(res_find["attrs"]):
                        commands.append(
                            [name, "selfservice_mod", {
                                "attrs": attrs
                            }])

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

        # Check mode exit
        if ansible_module.check_mode:
            ansible_module.exit_json(changed=len(commands) > 0, **exit_args)

        # Execute commands

        changed = ansible_module.execute_ipa_commands(commands)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            forwarders=dict(type="list", default=None, required=False,
                            aliases=["idnsforwarders"], elements='dict',
                            options=dict(
                                 ip_address=dict(type='str', required=True),
                                 port=dict(type='int', required=False,
                                           default=None),
                            )),
            forwardpolicy=dict(type='str',
                               aliases=["idnsforwardpolicy", "forward_policy"],
                               required=False,
                               choices=['only', 'first', 'none']),
            skip_overlap_check=dict(type='bool', required=False),
            permission=dict(type='bool', required=False,
                            aliases=['managedby']),
            action=dict(type="str", default="dnsforwardzone",
                        choices=["member", "dnsforwardzone"]),
            # state
            state=dict(type='str', default='present',
                       choices=['present', 'absent', 'enabled', 'disabled']),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters
    names = ansible_module.params_get("name")
    action = ansible_module.params_get("action")
    forwarders = forwarder_list(
        ansible_module.params_get("forwarders"))
    forwardpolicy = ansible_module.params_get("forwardpolicy")
    skip_overlap_check = ansible_module.params_get("skip_overlap_check")
    permission = ansible_module.params_get("permission")
    state = ansible_module.params_get("state")

    if state == 'present' and len(names) != 1:
        ansible_module.fail_json(
            msg="Only one dnsforwardzone can be added at a time.")
    if state == 'absent' and len(names) < 1:
        ansible_module.fail_json(msg="No name given.")

    # absent stae means delete if the action is NOT member but update if it is
    # if action is member then update an exisiting resource
    # and if action is not member then create a resource
    if state == "absent" and action == "dnsforwardzone":
        operation = "del"
    elif action == "member":
        operation = "update"
    else:
        operation = "add"

    invalid = []
    if state in ["enabled", "disabled"]:
        if action == "member":
            ansible_module.fail_json(
                msg="Action `member` cannot be used with state `%s`"
                    % (state))
        invalid = [
            "forwarders", "forwardpolicy", "skip_overlap_check", "permission"
        ]
        wants_enable = (state == "enabled")

    if operation == "del":
        invalid = [
            "forwarders", "forwardpolicy", "skip_overlap_check", "permission"
        ]

    ansible_module.params_fail_used_invalid(invalid, state, action)

    changed = False
    exit_args = {}
    args = {}
    is_enabled = "IGNORE"

    # Connect to IPA API
    with ansible_module.ipa_connect():

        # we need to determine 3 variables
        # args = the values we want to change/set
        # command = the ipa api command to call del, add, or mod
        # is_enabled = is the current resource enabled (True)
        #             disabled (False) and do we care (IGNORE)

        for name in names:
            commands = []
            command = None

            # Make sure forwardzone exists
            existing_resource = find_dnsforwardzone(ansible_module, name)

            # validate parameters
            if state == 'present':
                if existing_resource is None and not forwarders:
                    ansible_module.fail_json(msg='No forwarders specified.')

            if existing_resource is None:
                if operation == "add":
                    # does not exist but should be present
                    # determine args
                    args = gen_args(forwarders, forwardpolicy,
                                    skip_overlap_check)
                    # set command
                    command = "dnsforwardzone_add"
                    # enabled or disabled?

                elif operation == "update":
                    # does not exist and is updating
                    # trying to update something that doesn't exist, so error
                    ansible_module.fail_json(
                        msg="dnsforwardzone '%s' not found." % (name))

                elif operation == "del":
                    # there's nothnig to do.
                    continue

            else:   # existing_resource is not None
                fix_resource_data_types(existing_resource)
                if state != "absent":
                    if forwarders:
                        forwarders = list(
                            set(existing_resource["idnsforwarders"]
                                + forwarders))
                else:
                    if forwarders:
                        forwarders = list(
                            set(existing_resource["idnsforwarders"])
                            - set(forwarders))

                if operation == "add":
                    # exists and should be present, has it changed?
                    # determine args
                    args = gen_args(
                        forwarders, forwardpolicy, skip_overlap_check)
                    if 'skip_overlap_check' in args:
                        del args['skip_overlap_check']

                    # set command
                    if not compare_args_ipa(
                            ansible_module, args, existing_resource):
                        command = "dnsforwardzone_mod"

                elif operation == "del":
                    # exists but should be absent
                    # set command
                    command = "dnsforwardzone_del"
                    args = {}

                elif operation == "update":
                    # exists and is updating
                    # calculate the new forwarders and mod
                    args = gen_args(
                        forwarders, forwardpolicy, skip_overlap_check)
                    if "skip_overlap_check" in args:
                        del args['skip_overlap_check']

                    # command
                    if not compare_args_ipa(
                            ansible_module, args, existing_resource):
                        command = "dnsforwardzone_mod"

            if state in ['enabled', 'disabled']:
                if existing_resource is not None:
                    is_enabled = existing_resource["idnszoneactive"][0]
                else:
                    ansible_module.fail_json(
                        msg="dnsforwardzone '%s' not found." % (name))

            # does the enabled state match what we want (if we care)
            if is_enabled != "IGNORE":
                if wants_enable and is_enabled != "TRUE":
                    commands.append([name, "dnsforwardzone_enable", {}])
                elif not wants_enable and is_enabled != "FALSE":
                    commands.append([name, "dnsforwardzone_disable", {}])

            # if command is set...
            if command is not None:
                commands.append([name, command, args])

            if permission is not None:
                if existing_resource is None:
                    managedby = None
                else:
                    managedby = existing_resource.get('managedby', None)
                if permission and managedby is None:
                    commands.append(
                        [name, 'dnsforwardzone_add_permission', {}]
                    )
                elif not permission and managedby is not None:
                    commands.append(
                        [name, 'dnsforwardzone_remove_permission', {}]
                    )

            # Check mode exit
            if ansible_module.check_mode:
                ansible_module.exit_json(changed=len(commands) > 0,
                                         **exit_args)

            # Execute commands
            for _name, command, args in commands:
                ansible_module.ipa_command(command, _name, args)
                changed = True

    # Done
    ansible_module.exit_json(changed=changed, dnsforwardzone=exit_args)
Example #22
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            realm=dict(type="str", default=None, required=True),
            # state
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent"]),
            # present
            trust_type=dict(type="str", default="ad", required=False),
            admin=dict(type="str", default=None, required=False),
            password=dict(type="str",
                          default=None,
                          required=False,
                          no_log=True),
            server=dict(type="str", default=None, required=False),
            trust_secret=dict(type="str",
                              default=None,
                              required=False,
                              no_log=True),
            base_id=dict(type="int", default=None, required=False),
            range_size=dict(type="int", default=200000, required=False),
            range_type=dict(type="str",
                            default="ipa-ad-trust",
                            required=False,
                            choices=["ipa-ad-trust-posix", "ipa-ad-trust"]),
            two_way=dict(type="bool", default=False, required=False),
            external=dict(type="bool", default=False, required=False),
        ),
        mutually_exclusive=[["trust_secret", "admin"]],
        required_together=[["admin", "password"]],
        supports_check_mode=True)

    ansible_module._ansible_debug = True

    # general
    realm = ansible_module.params_get("realm")

    # state
    state = ansible_module.params_get("state")

    # trust
    trust_type = ansible_module.params_get("trust_type")
    admin = ansible_module.params_get("admin")
    password = ansible_module.params_get("password")
    server = ansible_module.params_get("server")
    trust_secret = ansible_module.params_get("trust_secret")
    base_id = ansible_module.params_get("base_id")
    range_size = ansible_module.params_get("range_size")
    range_type = ansible_module.params_get("range_type")
    two_way = ansible_module.params_get("two_way")
    external = ansible_module.params_get("external")

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        res_find = find_trust(ansible_module, realm)

        if state == "absent":
            if res_find is not None:
                if not ansible_module.check_mode:
                    del_trust(ansible_module, realm)
                changed = True
        elif res_find is None:
            if admin is None and trust_secret is None:
                ansible_module.fail_json(
                    msg="one of admin or trust_secret is required when state "
                    "is present")
            else:
                args = gen_args(trust_type, admin, password, server,
                                trust_secret, base_id, range_size, range_type,
                                two_way, external)

                if not ansible_module.check_mode:
                    add_trust(ansible_module, realm, args)
                changed = True

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #23
0
def main():
    forwarder_spec = dict(ip_address=dict(type=str, required=True),
                          port=dict(type=int, required=False, default=None))

    ansible_module = IPAAnsibleModule(argument_spec=dict(
        # dnsconfig
        forwarders=dict(type='list',
                        default=None,
                        required=False,
                        options=dict(**forwarder_spec)),
        forward_policy=dict(type='str',
                            required=False,
                            default=None,
                            choices=['only', 'first', 'none'],
                            aliases=["forwardpolicy"]),
        allow_sync_ptr=dict(type='bool', required=False, default=None),

        # general
        action=dict(
            type="str", default="dnsconfig", choices=["member", "dnsconfig"]),
        state=dict(
            type="str", default="present", choices=["present", "absent"]),
    ))

    ansible_module._ansible_debug = True

    # dnsconfig
    forwarders = ansible_module.params_get('forwarders') or []
    forward_policy = ansible_module.params_get('forward_policy')
    allow_sync_ptr = ansible_module.params_get('allow_sync_ptr')

    action = ansible_module.params_get('action')
    state = ansible_module.params_get('state')

    # Check parameters.
    invalid = []
    if state == "present" and action == "member":
        invalid = ['forward_policy', 'allow_sync_ptr']
    if state == 'absent':
        if action != "member":
            ansible_module.fail_json(
                msg="State 'absent' is only valid with action 'member'.")
        invalid = ['forward_policy', 'allow_sync_ptr']

    ansible_module.params_fail_used_invalid(invalid, state)

    # Init

    changed = False

    # Connect to IPA API
    with ansible_module.ipa_connect():

        res_find = find_dnsconfig(ansible_module)
        args = gen_args(ansible_module, state, action, res_find, forwarders,
                        forward_policy, allow_sync_ptr)

        # Execute command only if configuration changes.
        if not compare_args_ipa(ansible_module, args, res_find):
            try:
                if not ansible_module.check_mode:
                    ansible_module.ipa_command_no_name('dnsconfig_mod', args)
                # If command did not fail, something changed.
                changed = True

            except Exception as e:
                msg = str(e)
                ansible_module.fail_json(msg="dnsconfig_mod: %s" % msg)

    # Done

    ansible_module.exit_json(changed=changed)
Example #24
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            # present
            description=dict(required=False, type="str", default=None),
            usercategory=dict(required=False, type="str", default=None,
                              choices=["all", ""], aliases=['usercat']),
            hostcategory=dict(required=False, type="str", default=None,
                              choices=["all", ""], aliases=['hostcat']),
            nomembers=dict(required=False, type='bool', default=None),
            host=dict(required=False, type='list', default=None),
            hostgroup=dict(required=False, type='list', default=None),
            user=dict(required=False, type='list', default=None),
            group=dict(required=False, type='list', default=None),
            allow_sudocmd=dict(required=False, type="list", default=None),
            deny_sudocmd=dict(required=False, type="list", default=None),
            allow_sudocmdgroup=dict(required=False, type="list", default=None),
            deny_sudocmdgroup=dict(required=False, type="list", default=None),
            cmdcategory=dict(required=False, type="str", default=None,
                             choices=["all", ""], aliases=['cmdcat']),
            runasusercategory=dict(required=False, type="str", default=None,
                                   choices=["all", ""],
                                   aliases=['runasusercat']),
            runasgroupcategory=dict(required=False, type="str", default=None,
                                    choices=["all", ""],
                                    aliases=['runasgroupcat']),
            runasuser=dict(required=False, type="list", default=None),
            runasgroup=dict(required=False, type="list", default=None),
            order=dict(type="int", required=False, aliases=['sudoorder']),
            sudooption=dict(required=False, type='list', default=None,
                            aliases=["options"]),
            action=dict(type="str", default="sudorule",
                        choices=["member", "sudorule"]),
            # state
            state=dict(type="str", default="present",
                       choices=["present", "absent",
                                "enabled", "disabled"]),
        ),
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    # Get parameters

    # general
    names = ansible_module.params_get("name")

    # present
    # The 'noqa' variables are not used here, but required for vars().
    # The use of 'noqa' ensures flake8 does not complain about them.
    description = ansible_module.params_get("description")  # noqa
    cmdcategory = ansible_module.params_get('cmdcategory')  # noqa
    usercategory = ansible_module.params_get("usercategory")  # noqa
    hostcategory = ansible_module.params_get("hostcategory")  # noqa
    runasusercategory = ansible_module.params_get(          # noqa
                                          "runasusercategory")
    runasgroupcategory = ansible_module.params_get(         # noqa
                                           "runasgroupcategory")
    hostcategory = ansible_module.params_get("hostcategory")  # noqa
    nomembers = ansible_module.params_get("nomembers")  # noqa
    host = ansible_module.params_get("host")
    hostgroup = ansible_module.params_get("hostgroup")
    user = ansible_module.params_get("user")
    group = ansible_module.params_get("group")
    allow_sudocmd = ansible_module.params_get('allow_sudocmd')
    allow_sudocmdgroup = ansible_module.params_get('allow_sudocmdgroup')
    deny_sudocmd = ansible_module.params_get('deny_sudocmd')
    deny_sudocmdgroup = ansible_module.params_get('deny_sudocmdgroup')
    sudooption = ansible_module.params_get("sudooption")
    order = ansible_module.params_get("order")
    runasuser = ansible_module.params_get("runasuser")
    runasgroup = ansible_module.params_get("runasgroup")
    action = ansible_module.params_get("action")

    # state
    state = ansible_module.params_get("state")

    # Check parameters

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one sudorule can be added at a time.")
        if action == "member":
            invalid = ["description", "usercategory", "hostcategory",
                       "cmdcategory", "runasusercategory",
                       "runasgroupcategory", "order", "nomembers"]

            for arg in invalid:
                if arg in vars() and vars()[arg] is not None:
                    ansible_module.fail_json(
                        msg="Argument '%s' can not be used with action "
                        "'%s'" % (arg, action))
        else:
            if hostcategory == 'all' and any([host, hostgroup]):
                ansible_module.fail_json(
                    msg="Hosts cannot be added when host category='all'")
            if usercategory == 'all' and any([user, group]):
                ansible_module.fail_json(
                    msg="Users cannot be added when user category='all'")
            if cmdcategory == 'all' \
               and any([allow_sudocmd, allow_sudocmdgroup]):
                ansible_module.fail_json(
                    msg="Commands cannot be added when command category='all'")

    elif state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        invalid = ["description", "usercategory", "hostcategory",
                   "cmdcategory", "runasusercategory",
                   "runasgroupcategory", "nomembers", "order"]
        if action == "sudorule":
            invalid.extend(["host", "hostgroup", "user", "group",
                            "runasuser", "runasgroup", "allow_sudocmd",
                            "allow_sudocmdgroup", "deny_sudocmd",
                            "deny_sudocmdgroup", "sudooption"])
        for arg in invalid:
            if vars()[arg] is not None:
                ansible_module.fail_json(
                    msg="Argument '%s' can not be used with state '%s'" %
                    (arg, state))

    elif state in ["enabled", "disabled"]:
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")
        if action == "member":
            ansible_module.fail_json(
                msg="Action member can not be used with states enabled and "
                "disabled")
        invalid = ["description", "usercategory", "hostcategory",
                   "cmdcategory", "runasusercategory", "runasgroupcategory",
                   "nomembers", "nomembers", "host", "hostgroup",
                   "user", "group", "allow_sudocmd", "allow_sudocmdgroup",
                   "deny_sudocmd", "deny_sudocmdgroup", "runasuser",
                   "runasgroup", "order", "sudooption"]
        for arg in invalid:
            if vars()[arg] is not None:
                ansible_module.fail_json(
                    msg="Argument '%s' can not be used with state '%s'" %
                    (arg, state))
    else:
        ansible_module.fail_json(msg="Invalid state '%s'" % state)

    # Init

    changed = False
    exit_args = {}

    # Connect to IPA API
    with ansible_module.ipa_connect():

        commands = []

        for name in names:
            # Make sure sudorule exists
            res_find = find_sudorule(ansible_module, name)

            # Create command
            if state == "present":
                # Generate args
                args = gen_args(description, usercategory, hostcategory,
                                cmdcategory, runasusercategory,
                                runasgroupcategory, order, nomembers)
                if action == "sudorule":
                    # Found the sudorule
                    if res_find is not None:
                        # Remove empty usercategory, hostcategory,
                        # cmdcaterory, runasusercategory and hostcategory
                        # from args if "" and if the category is not in the
                        # sudorule. The empty string is used to reset the
                        # category.
                        if "usercategory" in args \
                           and args["usercategory"] == "" \
                           and "usercategory" not in res_find:
                            del args["usercategory"]
                        if "hostcategory" in args \
                           and args["hostcategory"] == "" \
                           and "hostcategory" not in res_find:
                            del args["hostcategory"]
                        if "cmdcategory" in args \
                           and args["cmdcategory"] == "" \
                           and "cmdcategory" not in res_find:
                            del args["cmdcategory"]
                        if "ipasudorunasusercategory" in args \
                           and args["ipasudorunasusercategory"] == "" \
                           and "ipasudorunasusercategory" not in res_find:
                            del args["ipasudorunasusercategory"]
                        if "ipasudorunasgroupcategory" in args \
                           and args["ipasudorunasgroupcategory"] == "" \
                           and "ipasudorunasgroupcategory" not in res_find:
                            del args["ipasudorunasgroupcategory"]

                        # For all settings is args, check if there are
                        # different settings in the find result.
                        # If yes: modify
                        if not compare_args_ipa(ansible_module, args,
                                                res_find):
                            commands.append([name, "sudorule_mod", args])
                    else:
                        commands.append([name, "sudorule_add", args])
                        # Set res_find to empty dict for next step
                        res_find = {}

                    # Generate addition and removal lists
                    host_add, host_del = gen_add_del_lists(
                        host, res_find.get('memberhost_host', []))

                    hostgroup_add, hostgroup_del = gen_add_del_lists(
                        hostgroup, res_find.get('memberhost_hostgroup', []))

                    user_add, user_del = gen_add_del_lists(
                        user, res_find.get('memberuser_user', []))

                    group_add, group_del = gen_add_del_lists(
                        group, res_find.get('memberuser_group', []))

                    allow_cmd_add, allow_cmd_del = gen_add_del_lists(
                        allow_sudocmd,
                        res_find.get('memberallowcmd_sudocmd', []))

                    allow_cmdgroup_add, allow_cmdgroup_del = gen_add_del_lists(
                        allow_sudocmdgroup,
                        res_find.get('memberallowcmd_sudocmdgroup', []))

                    deny_cmd_add, deny_cmd_del = gen_add_del_lists(
                        deny_sudocmd,
                        res_find.get('memberdenycmd_sudocmd', []))

                    deny_cmdgroup_add, deny_cmdgroup_del = gen_add_del_lists(
                        deny_sudocmdgroup,
                        res_find.get('memberdenycmd_sudocmdgroup', []))

                    sudooption_add, sudooption_del = gen_add_del_lists(
                        sudooption, res_find.get('ipasudoopt', []))

                    runasuser_add, runasuser_del = gen_add_del_lists(
                        runasuser, res_find.get('ipasudorunas_user', []))

                    runasgroup_add, runasgroup_del = gen_add_del_lists(
                        runasgroup, res_find.get('ipasudorunas_group', []))

                    # Add hosts and hostgroups
                    if len(host_add) > 0 or len(hostgroup_add) > 0:
                        commands.append([name, "sudorule_add_host",
                                         {
                                             "host": host_add,
                                             "hostgroup": hostgroup_add,
                                         }])
                    # Remove hosts and hostgroups
                    if len(host_del) > 0 or len(hostgroup_del) > 0:
                        commands.append([name, "sudorule_remove_host",
                                         {
                                             "host": host_del,
                                             "hostgroup": hostgroup_del,
                                         }])

                    # Add users and groups
                    if len(user_add) > 0 or len(group_add) > 0:
                        commands.append([name, "sudorule_add_user",
                                         {
                                             "user": user_add,
                                             "group": group_add,
                                         }])
                    # Remove users and groups
                    if len(user_del) > 0 or len(group_del) > 0:
                        commands.append([name, "sudorule_remove_user",
                                         {
                                             "user": user_del,
                                             "group": group_del,
                                         }])

                    # Add commands allowed
                    if len(allow_cmd_add) > 0 or len(allow_cmdgroup_add) > 0:
                        commands.append([name, "sudorule_add_allow_command",
                                         {"sudocmd": allow_cmd_add,
                                          "sudocmdgroup": allow_cmdgroup_add,
                                          }])

                    if len(allow_cmd_del) > 0 or len(allow_cmdgroup_del) > 0:
                        commands.append([name, "sudorule_remove_allow_command",
                                         {"sudocmd": allow_cmd_del,
                                          "sudocmdgroup": allow_cmdgroup_del
                                          }])

                    # Add commands denied
                    if len(deny_cmd_add) > 0 or len(deny_cmdgroup_add) > 0:
                        commands.append([name, "sudorule_add_deny_command",
                                         {"sudocmd": deny_cmd_add,
                                          "sudocmdgroup": deny_cmdgroup_add,
                                          }])

                    if len(deny_cmd_del) > 0 or len(deny_cmdgroup_del) > 0:
                        commands.append([name, "sudorule_remove_deny_command",
                                         {"sudocmd": deny_cmd_del,
                                          "sudocmdgroup": deny_cmdgroup_del
                                          }])

                    # Add RunAS Users
                    if len(runasuser_add) > 0:
                        commands.append([name, "sudorule_add_runasuser",
                                         {"user": runasuser_add}])
                    # Remove RunAS Users
                    if len(runasuser_del) > 0:
                        commands.append([name, "sudorule_remove_runasuser",
                                         {"user": runasuser_del}])

                    # Add RunAS Groups
                    if len(runasgroup_add) > 0:
                        commands.append([name, "sudorule_add_runasgroup",
                                         {"group": runasgroup_add}])
                    # Remove RunAS Groups
                    if len(runasgroup_del) > 0:
                        commands.append([name, "sudorule_remove_runasgroup",
                                         {"group": runasgroup_del}])

                    # Add sudo options
                    for sudoopt in sudooption_add:
                        commands.append([name, "sudorule_add_option",
                                         {"ipasudoopt": sudoopt}])

                    # Remove sudo options
                    for sudoopt in sudooption_del:
                        commands.append([name, "sudorule_remove_option",
                                         {"ipasudoopt": sudoopt}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No sudorule '%s'" % name)

                    # Generate add lists for host, hostgroup, user, group,
                    # allow_sudocmd, allow_sudocmdgroup, deny_sudocmd,
                    # deny_sudocmdgroup, sudooption, runasuser, runasgroup
                    # and res_find to only try to add the items that not in
                    # the sudorule already
                    if host is not None and \
                       "memberhost_host" in res_find:
                        host = gen_add_list(
                            host, res_find["memberhost_host"])
                    if hostgroup is not None and \
                       "memberhost_hostgroup" in res_find:
                        hostgroup = gen_add_list(
                            hostgroup, res_find["memberhost_hostgroup"])
                    if user is not None and \
                       "memberuser_user" in res_find:
                        user = gen_add_list(
                            user, res_find["memberuser_user"])
                    if group is not None and \
                       "memberuser_group" in res_find:
                        group = gen_add_list(
                            group, res_find["memberuser_group"])
                    if allow_sudocmd is not None and \
                       "memberallowcmd_sudocmd" in res_find:
                        allow_sudocmd = gen_add_list(
                            allow_sudocmd, res_find["memberallowcmd_sudocmd"])
                    if allow_sudocmdgroup is not None and \
                       "memberallowcmd_sudocmdgroup" in res_find:
                        allow_sudocmdgroup = gen_add_list(
                            allow_sudocmdgroup,
                            res_find["memberallowcmd_sudocmdgroup"])
                    if deny_sudocmd is not None and \
                       "memberdenycmd_sudocmd" in res_find:
                        deny_sudocmd = gen_add_list(
                            deny_sudocmd, res_find["memberdenycmd_sudocmd"])
                    if deny_sudocmdgroup is not None and \
                       "memberdenycmd_sudocmdgroup" in res_find:
                        deny_sudocmdgroup = gen_add_list(
                            deny_sudocmdgroup,
                            res_find["memberdenycmd_sudocmdgroup"])
                    if sudooption is not None and \
                       "ipasudoopt" in res_find:
                        sudooption = gen_add_list(
                            sudooption, res_find["ipasudoopt"])
                    if runasuser is not None and \
                       "ipasudorunas_user" in res_find:
                        runasuser = gen_add_list(
                            runasuser, res_find["ipasudorunas_user"])
                    if runasgroup is not None and \
                       "ipasudorunasgroup_group" in res_find:
                        runasgroup = gen_add_list(
                            runasgroup, res_find["ipasudorunasgroup_group"])

                    # Add hosts and hostgroups
                    if host is not None or hostgroup is not None:
                        commands.append([name, "sudorule_add_host",
                                         {
                                             "host": host,
                                             "hostgroup": hostgroup,
                                         }])

                    # Add users and groups
                    if user is not None or group is not None:
                        commands.append([name, "sudorule_add_user",
                                         {
                                             "user": user,
                                             "group": group,
                                         }])

                    # Add commands
                    if allow_sudocmd is not None \
                       or allow_sudocmdgroup is not None:
                        commands.append([name, "sudorule_add_allow_command",
                                         {"sudocmd": allow_sudocmd,
                                          "sudocmdgroup": allow_sudocmdgroup,
                                          }])

                    # Add commands
                    if deny_sudocmd is not None \
                       or deny_sudocmdgroup is not None:
                        commands.append([name, "sudorule_add_deny_command",
                                         {"sudocmd": deny_sudocmd,
                                          "sudocmdgroup": deny_sudocmdgroup,
                                          }])

                    # Add RunAS Users
                    if runasuser is not None and len(runasuser) > 0:
                        commands.append([name, "sudorule_add_runasuser",
                                         {"user": runasuser}])

                    # Add RunAS Groups
                    if runasgroup is not None and len(runasgroup) > 0:
                        commands.append([name, "sudorule_add_runasgroup",
                                         {"group": runasgroup}])

                    # Add options
                    if sudooption is not None:
                        existing_opts = res_find.get('ipasudoopt', [])
                        for sudoopt in sudooption:
                            if sudoopt not in existing_opts:
                                commands.append([name, "sudorule_add_option",
                                                 {"ipasudoopt": sudoopt}])

            elif state == "absent":
                if action == "sudorule":
                    if res_find is not None:
                        commands.append([name, "sudorule_del", {}])

                elif action == "member":
                    if res_find is None:
                        ansible_module.fail_json(msg="No sudorule '%s'" % name)

                    # Generate intersection lists for host, hostgroup, user,
                    # group, allow_sudocmd, allow_sudocmdgroup, deny_sudocmd
                    # deny_sudocmdgroup, sudooption, runasuser, runasgroup
                    # and res_find to only try to remove the items that are
                    # in sudorule
                    if host is not None:
                        if "memberhost_host" in res_find:
                            host = gen_intersection_list(
                                host, res_find["memberhost_host"])
                        else:
                            host = None
                    if hostgroup is not None:
                        if "memberhost_hostgroup" in res_find:
                            hostgroup = gen_intersection_list(
                                hostgroup, res_find["memberhost_hostgroup"])
                        else:
                            hostgroup = None
                    if user is not None:
                        if "memberuser_user" in res_find:
                            user = gen_intersection_list(
                                user, res_find["memberuser_user"])
                        else:
                            user = None
                    if group is not None:
                        if "memberuser_group" in res_find:
                            group = gen_intersection_list(
                                group, res_find["memberuser_group"])
                        else:
                            group = None
                    if allow_sudocmd is not None:
                        if "memberallowcmd_sudocmd" in res_find:
                            allow_sudocmd = gen_intersection_list(
                                allow_sudocmd,
                                res_find["memberallowcmd_sudocmd"])
                        else:
                            allow_sudocmd = None
                    if allow_sudocmdgroup is not None:
                        if "memberallowcmd_sudocmdgroup" in res_find:
                            allow_sudocmdgroup = gen_intersection_list(
                                allow_sudocmdgroup,
                                res_find["memberallowcmd_sudocmdgroup"])
                        else:
                            allow_sudocmdgroup = None
                    if deny_sudocmd is not None:
                        if "memberdenycmd_sudocmd" in res_find:
                            deny_sudocmd = gen_intersection_list(
                                deny_sudocmd,
                                res_find["memberdenycmd_sudocmd"])
                        else:
                            deny_sudocmd = None
                    if deny_sudocmdgroup is not None:
                        if "memberdenycmd_sudocmdgroup" in res_find:
                            deny_sudocmdgroup = gen_intersection_list(
                                deny_sudocmdgroup,
                                res_find["memberdenycmd_sudocmdgroup"])
                        else:
                            deny_sudocmdgroup = None
                    if sudooption is not None:
                        if "ipasudoopt" in res_find:
                            sudooption = gen_intersection_list(
                                sudooption, res_find["ipasudoopt"])
                        else:
                            sudooption = None
                    if runasuser is not None:
                        if "ipasudorunas_user" in res_find:
                            runasuser = gen_intersection_list(
                                runasuser, res_find["ipasudorunas_user"])
                        else:
                            runasuser = None
                    if runasgroup is not None:
                        if "ipasudorunasgroup_group" in res_find:
                            runasgroup = gen_intersection_list(
                                runasgroup,
                                res_find["ipasudorunasgroup_group"])
                        else:
                            runasgroup = None

                    # Remove hosts and hostgroups
                    if host is not None or hostgroup is not None:
                        commands.append([name, "sudorule_remove_host",
                                         {
                                             "host": host,
                                             "hostgroup": hostgroup,
                                         }])

                    # Remove users and groups
                    if user is not None or group is not None:
                        commands.append([name, "sudorule_remove_user",
                                         {
                                             "user": user,
                                             "group": group,
                                         }])

                    # Remove allow commands
                    if allow_sudocmd is not None \
                       or allow_sudocmdgroup is not None:
                        commands.append([name, "sudorule_remove_allow_command",
                                         {"sudocmd": allow_sudocmd,
                                          "sudocmdgroup": allow_sudocmdgroup
                                          }])

                    # Remove deny commands
                    if deny_sudocmd is not None \
                       or deny_sudocmdgroup is not None:
                        commands.append([name, "sudorule_remove_deny_command",
                                         {"sudocmd": deny_sudocmd,
                                          "sudocmdgroup": deny_sudocmdgroup
                                          }])

                    # Remove RunAS Users
                    if runasuser is not None:
                        commands.append([name, "sudorule_remove_runasuser",
                                         {"user": runasuser}])

                    # Remove RunAS Groups
                    if runasgroup is not None:
                        commands.append([name, "sudorule_remove_runasgroup",
                                         {"group": runasgroup}])

                    # Remove options
                    if sudooption is not None:
                        existing_opts = res_find.get('ipasudoopt', [])
                        for sudoopt in sudooption:
                            if sudoopt in existing_opts:
                                commands.append([name,
                                                 "sudorule_remove_option",
                                                 {"ipasudoopt": sudoopt}])

            elif state == "enabled":
                if res_find is None:
                    ansible_module.fail_json(msg="No sudorule '%s'" % name)
                # sudorule_enable is not failing on an enabled sudorule
                # Therefore it is needed to have a look at the ipaenabledflag
                # in res_find.
                if "ipaenabledflag" not in res_find or \
                   res_find["ipaenabledflag"][0] != "TRUE":
                    commands.append([name, "sudorule_enable", {}])

            elif state == "disabled":
                if res_find is None:
                    ansible_module.fail_json(msg="No sudorule '%s'" % name)
                # sudorule_disable is not failing on an disabled sudorule
                # Therefore it is needed to have a look at the ipaenabledflag
                # in res_find.
                if "ipaenabledflag" not in res_find or \
                   res_find["ipaenabledflag"][0] != "FALSE":
                    commands.append([name, "sudorule_disable", {}])

            else:
                ansible_module.fail_json(msg="Unkown state '%s'" % state)

        # Execute commands

        changed = ansible_module.execute_ipa_commands(
            commands, fail_on_member_errors=True)

    # Done

    ansible_module.exit_json(changed=changed, **exit_args)
Example #25
0
def main():
    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # generalgroups
            name=dict(type="list", aliases=["cn"], default=None,
                      required=True),
            description=dict(required=False, type="str", default=None),
            vault_type=dict(type="str",
                            aliases=["ipavaulttype"],
                            default=None,
                            required=False,
                            choices=["standard", "symmetric", "asymmetric"]),
            vault_public_key=dict(
                type="str",
                required=False,
                default=None,
                aliases=['ipavaultpublickey', 'public_key', 'new_public_key']),
            vault_public_key_file=dict(
                type="str",
                required=False,
                default=None,
                aliases=['public_key_file', 'new_public_key_file']),
            vault_private_key=dict(
                type="str",
                required=False,
                default=None,
                no_log=True,
                aliases=['ipavaultprivatekey', 'private_key']),
            vault_private_key_file=dict(type="str",
                                        required=False,
                                        default=None,
                                        aliases=['private_key_file']),
            vault_salt=dict(type="str",
                            required=False,
                            default=None,
                            aliases=['ipavaultsalt', 'salt']),
            username=dict(type="str",
                          required=False,
                          default=None,
                          aliases=['user']),
            service=dict(type="str", required=False, default=None),
            shared=dict(type="bool", required=False, default=None),
            users=dict(required=False, type='list', default=None),
            groups=dict(required=False, type='list', default=None),
            services=dict(required=False, type='list', default=None),
            owners=dict(required=False,
                        type='list',
                        default=None,
                        aliases=['ownerusers']),
            ownergroups=dict(required=False, type='list', default=None),
            ownerservices=dict(required=False, type='list', default=None),
            vault_data=dict(type="str",
                            required=False,
                            default=None,
                            no_log=True,
                            aliases=['ipavaultdata', 'data']),
            datafile_in=dict(type="str",
                             required=False,
                             default=None,
                             aliases=['in']),
            datafile_out=dict(type="str",
                              required=False,
                              default=None,
                              aliases=['out']),
            vault_password=dict(
                type="str",
                required=False,
                default=None,
                no_log=True,
                aliases=['ipavaultpassword', 'password', "old_password"]),
            vault_password_file=dict(
                type="str",
                required=False,
                default=None,
                no_log=False,
                aliases=['password_file', "old_password_file"]),
            new_password=dict(type="str",
                              required=False,
                              default=None,
                              no_log=True),
            new_password_file=dict(type="str",
                                   required=False,
                                   default=None,
                                   no_log=False),
            # state
            action=dict(type="str",
                        default="vault",
                        choices=["vault", "data", "member"]),
            state=dict(type="str",
                       default="present",
                       choices=["present", "absent", "retrieved"]),
        ),
        supports_check_mode=True,
        mutually_exclusive=[['username', 'service', 'shared'],
                            ['datafile_in', 'vault_data'],
                            ['new_password', 'new_password_file'],
                            ['vault_password', 'vault_password_file'],
                            ['vault_public_key', 'vault_public_key_file']],
    )

    ansible_module._ansible_debug = True

    # general
    names = ansible_module.params_get("name")

    # present
    description = ansible_module.params_get("description")

    username = ansible_module.params_get("username")
    service = ansible_module.params_get("service")
    shared = ansible_module.params_get("shared")

    users = ansible_module.params_get("users")
    groups = ansible_module.params_get("groups")
    services = ansible_module.params_get("services")
    owners = ansible_module.params_get("owners")
    ownergroups = ansible_module.params_get("ownergroups")
    ownerservices = ansible_module.params_get("ownerservices")

    vault_type = ansible_module.params_get("vault_type")
    salt = ansible_module.params_get("vault_salt")
    password = ansible_module.params_get("vault_password")
    password_file = ansible_module.params_get("vault_password_file")
    new_password = ansible_module.params_get("new_password")
    new_password_file = ansible_module.params_get("new_password_file")
    public_key = ansible_module.params_get("vault_public_key")
    public_key_file = ansible_module.params_get("vault_public_key_file")
    private_key = ansible_module.params_get("vault_private_key")
    private_key_file = ansible_module.params_get("vault_private_key_file")

    vault_data = ansible_module.params_get("vault_data")

    datafile_in = ansible_module.params_get("datafile_in")
    datafile_out = ansible_module.params_get("datafile_out")

    action = ansible_module.params_get("action")
    state = ansible_module.params_get("state")

    # Check parameters

    if state == "present":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one vault can be added at a time.")

    elif state == "absent":
        if len(names) < 1:
            ansible_module.fail_json(msg="No name given.")

    elif state == "retrieved":
        if len(names) != 1:
            ansible_module.fail_json(
                msg="Only one vault can be retrieved at a time.")

    else:
        ansible_module.fail_json(msg="Invalid state '%s'" % state)

    check_parameters(ansible_module, state, action, description, username,
                     service, shared, users, groups, services, owners,
                     ownergroups, ownerservices, vault_type, salt, password,
                     password_file, public_key, public_key_file, private_key,
                     private_key_file, vault_data, datafile_in, datafile_out,
                     new_password, new_password_file)
    # Init

    changed = False
    exit_args = {}

    with ansible_module.ipa_connect(context='ansible-freeipa') as ccache_name:
        if ccache_name is not None:
            os.environ["KRB5CCNAME"] = ccache_name

        commands = []

        for name in names:
            # Make sure vault exists
            res_find = find_vault(ansible_module, name, username, service,
                                  shared)

            # Set default vault_type if needed.
            res_type = res_find.get('ipavaulttype')[0] if res_find else None
            if vault_type is None:
                vault_type = res_type if res_find is not None else u"symmetric"

            # Generate args
            args = gen_args(description, username, service, shared, vault_type,
                            salt, public_key, public_key_file)
            pwdargs = None

            # Create command
            if state == "present":
                # verify data encription args
                check_encryption_params(
                    ansible_module, state, action, vault_type, salt, password,
                    password_file, public_key, public_key_file, private_key,
                    private_key_file, vault_data, datafile_in, datafile_out,
                    new_password, new_password_file, res_find)

                change_passwd = any([
                    new_password, new_password_file,
                    (private_key or private_key_file)
                    and (public_key or public_key_file)
                ])
                if action == "vault":
                    # Found the vault
                    if res_find is not None:
                        arg_type = args.get("ipavaulttype")

                        modified = not compare_args_ipa(
                            ansible_module, args, res_find)

                        if arg_type != res_type or change_passwd:
                            stargs = data_storage_args(
                                res_type, args, vault_data, password,
                                password_file, private_key, private_key_file,
                                datafile_in, datafile_out)
                            stored = get_stored_data(ansible_module, res_find,
                                                     stargs)
                            if stored:
                                vault_data = \
                                    (stored or b"").decode("utf-8")

                            remove_attrs = {
                                "symmetric": ["private_key", "public_key"],
                                "asymmetric": ["password", "ipavaultsalt"],
                                "standard": [
                                    "private_key", "public_key", "password",
                                    "ipavaultsalt"
                                ],
                            }
                            for attr in remove_attrs.get(arg_type, []):
                                if attr in args:
                                    del args[attr]

                            if vault_type == 'symmetric':
                                if 'ipavaultsalt' not in args:
                                    args['ipavaultsalt'] = os.urandom(32)
                            else:
                                args['ipavaultsalt'] = b''

                        if modified:
                            commands.append([name, "vault_mod_internal", args])
                    else:
                        if vault_type == 'symmetric' \
                           and 'ipavaultsalt' not in args:
                            args['ipavaultsalt'] = os.urandom(32)

                        commands.append([name, "vault_add_internal", args])

                        if vault_type != 'standard' and vault_data is None:
                            vault_data = ''

                        # Set res_find to empty dict for next steps
                        res_find = {}

                    # Generate adittion and removal lists
                    user_add, user_del = \
                        gen_add_del_lists(users,
                                          res_find.get('member_user', []))
                    group_add, group_del = \
                        gen_add_del_lists(groups,
                                          res_find.get('member_group', []))
                    service_add, service_del = \
                        gen_add_del_lists(services,
                                          res_find.get('member_service', []))

                    owner_add, owner_del = \
                        gen_add_del_lists(owners,
                                          res_find.get('owner_user', []))

                    ownergroups_add, ownergroups_del = \
                        gen_add_del_lists(ownergroups,
                                          res_find.get('owner_group', []))

                    ownerservice_add, ownerservice_del = \
                        gen_add_del_lists(ownerservices,
                                          res_find.get('owner_service', []))

                    # Add users and groups
                    user_add_args = gen_member_args(args, user_add, group_add,
                                                    service_add)
                    if user_add_args is not None:
                        commands.append(
                            [name, 'vault_add_member', user_add_args])

                    # Remove users and groups
                    user_del_args = gen_member_args(args, user_del, group_del,
                                                    service_del)
                    if user_del_args is not None:
                        commands.append(
                            [name, 'vault_remove_member', user_del_args])

                    # Add owner users and groups
                    owner_add_args = gen_member_args(args, owner_add,
                                                     ownergroups_add,
                                                     ownerservice_add)
                    if owner_add_args is not None:
                        commands.append(
                            [name, 'vault_add_owner', owner_add_args])

                    # Remove owner users and groups
                    owner_del_args = gen_member_args(args, owner_del,
                                                     ownergroups_del,
                                                     ownerservice_del)
                    if owner_del_args is not None:
                        commands.append(
                            [name, 'vault_remove_owner', owner_del_args])

                elif action in "member":
                    # Add users and groups
                    if any([users, groups, services]):
                        user_args = gen_member_args(args, users, groups,
                                                    services)
                        commands.append([name, 'vault_add_member', user_args])
                    if any([owners, ownergroups, ownerservices]):
                        owner_args = gen_member_args(args, owners, ownergroups,
                                                     ownerservices)
                        commands.append([name, 'vault_add_owner', owner_args])

                if any([vault_data, datafile_in]):
                    if change_passwd:
                        pwdargs = data_storage_args(vault_type, args,
                                                    vault_data, new_password,
                                                    new_password_file,
                                                    private_key,
                                                    private_key_file,
                                                    datafile_in, datafile_out)
                    else:
                        pwdargs = data_storage_args(vault_type, args,
                                                    vault_data, password,
                                                    password_file, private_key,
                                                    private_key_file,
                                                    datafile_in, datafile_out)

                    pwdargs['override_password'] = True
                    pwdargs.pop("private_key", None)
                    pwdargs.pop("private_key_file", None)
                    commands.append([name, "vault_archive", pwdargs])

            elif state == "retrieved":
                if res_find is None:
                    ansible_module.fail_json(
                        msg="Vault `%s` not found to retrieve data." % name)

                # verify data encription args
                check_encryption_params(
                    ansible_module, state, action, vault_type, salt, password,
                    password_file, public_key, public_key_file, private_key,
                    private_key_file, vault_data, datafile_in, datafile_out,
                    new_password, new_password_file, res_find)

                pwdargs = data_storage_args(res_find["ipavaulttype"][0], args,
                                            vault_data, password,
                                            password_file, private_key,
                                            private_key_file, datafile_in,
                                            datafile_out)
                if 'data' in pwdargs:
                    del pwdargs['data']

                commands.append([name, "vault_retrieve", pwdargs])

            elif state == "absent":
                if 'ipavaulttype' in args:
                    del args['ipavaulttype']

                if action == "vault":
                    if res_find is not None:
                        remove = ['ipavaultsalt', 'ipavaultpublickey']
                        args = {
                            k: v
                            for k, v in args.items() if k not in remove
                        }
                        commands.append([name, "vault_del", args])

                elif action == "member":
                    # remove users and groups
                    if any([users, groups, services]):
                        user_args = gen_member_args(args, users, groups,
                                                    services)
                        commands.append(
                            [name, 'vault_remove_member', user_args])

                    if any([owners, ownergroups, ownerservices]):
                        owner_args = gen_member_args(args, owners, ownergroups,
                                                     ownerservices)
                        commands.append(
                            [name, 'vault_remove_owner', owner_args])
                else:
                    ansible_module.fail_json(
                        msg="Invalid action '%s' for state '%s'" %
                        (action, state))
            else:
                ansible_module.fail_json(msg="Unknown state '%s'" % state)

        # Check mode exit
        if ansible_module.check_mode:
            ansible_module.exit_json(changed=len(commands) > 0, **exit_args)

        # Execute commands

        errors = []
        for name, command, args in commands:
            try:
                result = ansible_module.ipa_command(command, name, args)

                if command == 'vault_archive':
                    changed = 'Archived data into' in result['summary']
                elif command == 'vault_retrieve':
                    if 'result' not in result:
                        raise Exception("No result obtained.")
                    if "data" in result["result"]:
                        data_return = exit_args.setdefault("vault", {})
                        data_return["data"] = result["result"]["data"]
                    else:
                        if not datafile_out:
                            raise Exception("No data retrieved.")
                    changed = False
                else:
                    if "completed" in result:
                        if result["completed"] > 0:
                            changed = True
                    else:
                        changed = True
            except ipalib_errors.EmptyModlist:
                result = {}
            except Exception as exception:
                ansible_module.fail_json(msg="%s: %s: %s" %
                                         (command, name, str(exception)))

            # Get all errors
            # All "already a member" and "not a member" failures in the
            # result are ignored. All others are reported.
            if "failed" in result and len(result["failed"]) > 0:
                for item in result["failed"]:
                    failed_item = result["failed"][item]
                    for member_type in failed_item:
                        for member, failure in failed_item[member_type]:
                            if "already a member" in failure \
                               or "not a member" in failure:
                                continue
                            errors.append(
                                "%s: %s %s: %s" %
                                (command, member_type, member, failure))
        if len(errors) > 0:
            ansible_module.fail_json(msg=", ".join(errors))

    # Done

    # exit_raw_json is a replacement for ansible_module.exit_json that
    # does not mask the output.
    exit_raw_json(ansible_module, changed=changed, **exit_args)
def configure_module():
    """Configure ipadnsrecord ansible module variables."""
    record_spec = dict(
        zone_name=dict(type='str', required=False, aliases=['dnszone']),
        record_type=dict(type='str', default="A",
                         choices=["A", "AAAA", "A6", "AFSDB", "CERT", "CNAME",
                                  "DLV", "DNAME", "DS", "KX", "LOC", "MX",
                                  "NAPTR", "NS", "PTR", "SRV", "SSHFP", "TLSA",
                                  "TXT", "URI"]),
        record_value=dict(type='list', required=False),
        record_ttl=dict(type='int', required=False),
        del_all=dict(type='bool', required=False),
        a_rec=dict(type='list', required=False, aliases=['a_record']),
        aaaa_rec=dict(type='list', required=False, aliases=['aaaa_record']),
        a6_rec=dict(type='list', required=False, aliases=['a6_record']),
        afsdb_rec=dict(type='list', required=False, aliases=['afsdb_record']),
        cert_rec=dict(type='list', required=False, aliases=['cert_record']),
        cname_rec=dict(type='list', required=False, aliases=['cname_record']),
        dlv_rec=dict(type='list', required=False, aliases=['dlv_record']),
        dname_rec=dict(type='list', required=False, aliases=['dname_record']),
        ds_rec=dict(type='list', required=False, aliases=['ds_record']),
        kx_rec=dict(type='list', required=False, aliases=['kx_record']),
        loc_rec=dict(type='list', required=False, aliases=['loc_record']),
        mx_rec=dict(type='list', required=False, aliases=['mx_record']),
        naptr_rec=dict(type='list', required=False, aliases=['naptr_record']),
        ns_rec=dict(type='list', required=False, aliases=['ns_record']),
        ptr_rec=dict(type='list', required=False, aliases=['ptr_record']),
        srv_rec=dict(type='list', required=False, aliases=['srv_record']),
        sshfp_rec=dict(type='list', required=False, aliases=['sshfp_record']),
        tlsa_rec=dict(type='list', required=False, aliases=['tlsa_record']),
        txt_rec=dict(type='list', required=False, aliases=['txt_record']),
        uri_rec=dict(type='list', required=False, aliases=['uri_record']),
        ip_address=dict(type='str', required=False),
        create_reverse=dict(type='bool', required=False, aliases=['reverse']),
        a_ip_address=dict(type='str', required=False),
        a_create_reverse=dict(type='bool', required=False),
        aaaa_ip_address=dict(type='str', required=False),
        aaaa_create_reverse=dict(type='bool', required=False),
        a6_data=dict(type='str', required=False),
        afsdb_subtype=dict(type='int', required=False),
        afsdb_hostname=dict(type='str', required=False),
        cert_type=dict(type='int', required=False),
        cert_key_tag=dict(type='int', required=False),
        cert_algorithm=dict(type='int', required=False),
        cert_certificate_or_crl=dict(type='str', required=False),
        cname_hostname=dict(type='str', required=False),
        dlv_key_tag=dict(type='int', required=False),
        dlv_algorithm=dict(type='int', required=False),
        dlv_digest_type=dict(type='int', required=False),
        dlv_digest=dict(type='str', required=False),
        dname_target=dict(type='str', required=False),
        ds_key_tag=dict(type='int', required=False),
        ds_algorithm=dict(type='int', required=False),
        ds_digest_type=dict(type='int', required=False),
        ds_digest=dict(type='str', required=False),
        kx_preference=dict(type='int', required=False),
        kx_exchanger=dict(type='str', required=False),
        loc_lat_deg=dict(type='int', required=False),
        loc_lat_min=dict(type='int', required=False),
        loc_lat_sec=dict(type='float', required=False),
        loc_lat_dir=dict(type='str', required=False),
        loc_lon_deg=dict(type='int', required=False),
        loc_lon_min=dict(type='int', required=False),
        loc_lon_sec=dict(type='float', required=False),
        loc_lon_dir=dict(type='str', required=False),
        loc_altitude=dict(type='float', required=False),
        loc_size=dict(type='float', required=False),
        loc_h_precision=dict(type='float', required=False),
        loc_v_precision=dict(type='float', required=False),
        mx_preference=dict(type='int', required=False),
        mx_exchanger=dict(type='str', required=False),
        naptr_order=dict(type='int', required=False),
        naptr_preference=dict(type='int', required=False),
        naptr_flags=dict(type='str', required=False),
        naptr_service=dict(type='str', required=False),
        naptr_regexp=dict(type='str', required=False),
        naptr_replacement=dict(type='str', required=False),
        ns_hostname=dict(type='str', required=False),
        ptr_hostname=dict(type='str', required=False),
        srv_priority=dict(type='int', required=False),
        srv_weight=dict(type='int', required=False),
        srv_port=dict(type='int', required=False),
        srv_target=dict(type='str', required=False),
        sshfp_algorithm=dict(type='int', required=False),
        sshfp_fingerprint=dict(type='str', required=False),
        sshfp_fp_type=dict(type='int', required=False),
        tlsa_cert_usage=dict(type='int', required=False),
        tlsa_cert_association_data=dict(type='str', required=False),
        tlsa_matching_type=dict(type='int', required=False),
        tlsa_selector=dict(type='int', required=False),
        txt_data=dict(type='str', required=False),
        uri_priority=dict(type='int', required=False),
        uri_target=dict(type='str', required=False),
        uri_weight=dict(type='int', required=False),
    )

    ansible_module = IPAAnsibleModule(
        argument_spec=dict(
            # general
            name=dict(type="list", aliases=["record_name"], default=None,
                      required=False),

            records=dict(type="list", default=None,
                         options=dict(
                            # Here name is a simple string
                            name=dict(type='str', required=True,
                                      aliases=['record_name']),
                            **record_spec),
                         ),

            # general
            state=dict(type="str", default="present",
                       choices=["present", "absent", "disabled"]),

            # Add record specific parameters for simple use case
            **record_spec
        ),
        mutually_exclusive=[["name", "records"], ['record_value', 'del_all']],
        required_one_of=[["name", "records"]],
        supports_check_mode=True,
    )

    ansible_module._ansible_debug = True

    return ansible_module