コード例 #1
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)
コード例 #2
0
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)
コード例 #3
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)
コード例 #4
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),
            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)
コード例 #5
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)
コード例 #6
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)
コード例 #7
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)
コード例 #8
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=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)
コード例 #9
0
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)
コード例 #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)
コード例 #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),
            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)
コード例 #12
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)
コード例 #13
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)
コード例 #14
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)
コード例 #15
0
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)
コード例 #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),
            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)