Beispiel #1
0
def log_before_repo_roles(input_dict):
    LOGGER.debug("Calling DURING_REPOABLE_CALCULATION hooks")
    if not all(required in input_dict
               for required in ['account_number', 'roles']):
        raise hooks.MissingHookParamaeter(
            "Did not get all required parameters for BEFORE_REPO_ROLES hook")
    return input_dict
Beispiel #2
0
def log_during_repoable_calculation_hooks(input_dict):
    LOGGER.debug("Calling DURING_REPOABLE_CALCULATION hooks")
    if not all(required in input_dict for required in [
            'account_number', 'role_name', 'potentially_repoable_permissions',
            'minimum_age'
    ]):
        raise hooks.MissingHookParamaeter(
            "Did not get all required parameters for DURING_REPOABLE_CALCULATION hook"
        )
    return input_dict
Beispiel #3
0
def log_during_repoable_calculation_batch_hooks(input_dict):
    LOGGER.debug("Calling DURING_REPOABLE_CALCULATION_BATCH hooks")

    if not all(required in input_dict for required in [
            "role_batch",
            "potentially_repoable_permissions",
            "minimum_age",
    ]):
        raise hooks.MissingHookParamaeter(
            "Did not get all required parameters for DURING_REPOABLE_CALCULATION_BATCH hook"
        )
    for role in input_dict["role_batch"]:
        if not isinstance(role, Role):
            raise hooks.MissingHookParamaeter(
                "Role_batch needs to be a series of Role objects in DURING_REPOABLE_CALCULATION_BATCH hook"
            )
    return input_dict
Beispiel #4
0
def update_role_cache(account_number, dynamo_table, config, hooks):
    """
    Update data about all roles in a given account:
      1) list all the roles and initiate a role object with basic data including name and roleID
      2) get inline policies for each of the roles
      3) build a list of active roles - we'll want to keep data about roles that may have been deleted in case we
         need to restore them, so if we used to have a role and now we don't see it we'll mark it inactive
      4) update data about the roles in Dynamo
      5) mark inactive roles in Dynamo
      6) load and instantiate filter plugins
      7) for each filter determine the list of roles that it filters
      8) update data in Dynamo about filters
      9) get Aardvark data for each role
      10) update Dynamo with Aardvark data
      11) calculate repoable permissions/policies for all the roles
      12) update Dynamo with information about how many total and repoable permissions and which services are repoable
      13) update stats in Dynamo with basic information like total permissions and which filters are applicable

    Args:
        account_number (string): The current account number Repokid is being run against

    Returns:
        None
    """
    conn = config["connection_iam"]
    conn["account_number"] = account_number

    LOGGER.info(
        "Getting current role data for account {} (this may take a while for large accounts)"
        .format(account_number))

    role_data = get_account_authorization_details(filter="Role", **conn)
    role_data_by_id = {item["RoleId"]: item for item in role_data}

    # convert policies list to dictionary to maintain consistency with old call which returned a dict
    for _, data in role_data_by_id.items():
        data["RolePolicyList"] = {
            item["PolicyName"]: item["PolicyDocument"]
            for item in data["RolePolicyList"]
        }

    roles = Roles([Role(rd) for rd in role_data])

    active_roles = []
    LOGGER.info("Updating role data for account {}".format(account_number))
    for role in tqdm(roles):
        role.account = account_number
        current_policies = role_data_by_id[role.role_id]["RolePolicyList"]
        active_roles.append(role.role_id)
        roledata.update_role_data(dynamo_table, account_number, role,
                                  current_policies)

    LOGGER.info("Finding inactive roles in account {}".format(account_number))
    roledata.find_and_mark_inactive(dynamo_table, account_number, active_roles)

    LOGGER.info("Filtering roles")
    plugins = FilterPlugins()

    # Blocklist needs to know the current account
    filter_config = config["filter_config"]
    blocklist_filter_config = filter_config.get(
        "BlocklistFilter", filter_config.get("BlacklistFilter"))
    blocklist_filter_config["current_account"] = account_number

    for plugin_path in config.get("active_filters"):
        plugin_name = plugin_path.split(":")[1]
        if plugin_name == "ExclusiveFilter":
            # ExclusiveFilter plugin active; try loading its config. Also, it requires the current account, so add it.
            exclusive_filter_config = filter_config.get("ExclusiveFilter", {})
            exclusive_filter_config["current_account"] = account_number
        plugins.load_plugin(plugin_path,
                            config=config["filter_config"].get(
                                plugin_name, None))

    for plugin in plugins.filter_plugins:
        filtered_list = plugin.apply(roles)
        class_name = plugin.__class__.__name__
        for filtered_role in filtered_list:
            LOGGER.info("Role {} filtered by {}".format(
                filtered_role.role_name, class_name))
            filtered_role.disqualified_by.append(class_name)

    for role in roles:
        set_role_data(dynamo_table, role.role_id,
                      {"DisqualifiedBy": role.disqualified_by})

    LOGGER.info(
        "Getting data from Aardvark for account {}".format(account_number))
    aardvark_data = get_aardvark_data(config["aardvark_api_location"],
                                      account_number=account_number)

    LOGGER.info("Updating roles with Aardvark data in account {}".format(
        account_number))
    for role in roles:
        try:
            role.aa_data = aardvark_data[role.arn]
        except KeyError:
            LOGGER.warning("Aardvark data not found for role: {} ({})".format(
                role.role_id, role.role_name))
        else:
            set_role_data(dynamo_table, role.role_id, {"AAData": role.aa_data})

    LOGGER.info(
        "Calculating repoable permissions and services for account {}".format(
            account_number))

    batch_processing = config.get("query_role_data_in_batch", False)
    batch_size = config.get("batch_processing_size", 100)
    roledata._calculate_repo_scores(
        roles,
        config["filter_config"]["AgeFilter"]["minimum_age"],
        hooks,
        batch_processing,
        batch_size,
    )
    for role in roles:
        LOGGER.debug(
            "Role {} in account {} has\nrepoable permissions: {}\nrepoable services: {}"
            .format(
                role.role_name,
                account_number,
                role.repoable_permissions,
                role.repoable_services,
            ))
        set_role_data(
            dynamo_table,
            role.role_id,
            {
                "TotalPermissions": role.total_permissions,
                "RepoablePermissions": role.repoable_permissions,
                "RepoableServices": role.repoable_services,
            },
        )

    LOGGER.info("Updating stats in account {}".format(account_number))
    roledata.update_stats(dynamo_table, roles, source="Scan")
Beispiel #5
0
def log_after_repo_hooks(input_dict):
    LOGGER.debug("Calling AFTER_REPO hooks")
    if 'role' not in input_dict:
        raise hooks.MissingHookParamaeter(
            "Required key 'role' not passed to AFTER_REPO")
    return input_dict
Beispiel #6
0
def _get_repoable_permissions(account_number, role_name, permissions, aa_data,
                              no_repo_permissions, minimum_age, hooks):
    """
    Generate a list of repoable permissions for a role based on the list of all permissions the role's policies
    currently allow and Access Advisor data for the services included in the role's policies.

    The first step is to come up with a list of services that were used within the time threshold (the same defined)
    in the age filter config. Permissions are repoable if they aren't in the used list, aren't in the constant list
    of unsupported services/actions (IAM_ACCESS_ADVISOR_UNSUPPORTED_SERVICES, IAM_ACCESS_ADVISOR_UNSUPPORTED_ACTIONS),
    and aren't being temporarily ignored because they're on the no_repo_permissions list (newly added).

    Args:
        account_number
        role_name
        permissions (list): The full list of permissions that the role's permissions allow
        aa_data (list): A list of Access Advisor data for a role. Each element is a dictionary with a couple required
                        attributes: lastAuthenticated (epoch time in milliseconds when the service was last used and
                        serviceNamespace (the service used)
        no_repo_permissions (dict): Keys are the name of permissions and values are the time the entry expires
        minimum_age: Minimum age of a role (in days) for it to be repoable
        hooks: Dict containing hook names and functions to run

    Returns:
        set: Permissions that are 'repoable' (not used within the time threshold)
    """
    ago = datetime.timedelta(minimum_age)
    now = datetime.datetime.now(tzlocal())

    current_time = time.time()
    no_repo_list = [
        perm.lower() for perm in no_repo_permissions
        if no_repo_permissions[perm] > current_time
    ]

    # cast all permissions to lowercase
    permissions = [permission.lower() for permission in permissions]
    potentially_repoable_permissions = {
        permission: RepoablePermissionDecision()
        for permission in permissions if permission not in no_repo_list
    }

    used_services = set()
    for service in aa_data:
        (accessed, valid_authenticated) = _get_epoch_authenticated(
            service['lastAuthenticated'])

        if not accessed:
            continue

        if not valid_authenticated:
            LOGGER.error(
                "Got malformed Access Advisor data for {role_name} in {account_number} for service {service}"
                ": {last_authenticated}".format(
                    role_name=role_name,
                    account_number=account_number,
                    service=service.get('serviceNamespace'),
                    last_authenticated=service['lastAuthenticated']))
            used_services.add(service['serviceNamespace'])

        accessed = datetime.datetime.fromtimestamp(accessed, tzlocal())
        if accessed > now - ago:
            used_services.add(service['serviceNamespace'])

    for permission_name, permission_decision in potentially_repoable_permissions.items(
    ):
        if permission_name.split(
                ':')[0] in IAM_ACCESS_ADVISOR_UNSUPPORTED_SERVICES:
            LOGGER.warn('skipping {}'.format(permission_name))
            continue

        # we have an unused service but need to make sure it's repoable
        if permission_name.split(':')[0] not in used_services:
            if permission_name in IAM_ACCESS_ADVISOR_UNSUPPORTED_ACTIONS:
                LOGGER.warn('skipping {}'.format(permission_name))
                continue

            permission_decision.repoable = True
            permission_decision.decider = 'Access Advisor'

    hooks_output = repokid.hooks.call_hooks(
        hooks, 'DURING_REPOABLE_CALCULATION', {
            'account_number': account_number,
            'role_name': role_name,
            'potentially_repoable_permissions':
            potentially_repoable_permissions,
            'minimum_age': minimum_age
        })

    LOGGER.debug(
        'Repoable permissions for role {role_name} in {account_number}:\n{repoable}'
        .format(role_name=role_name,
                account_number=account_number,
                repoable=''.join(
                    '{}: {}\n'.format(perm, decision.decider)
                    for perm, decision in
                    hooks_output['potentially_repoable_permissions'].items())))

    return set([
        permission_name for permission_name, permission_value in
        hooks_output['potentially_repoable_permissions'].items()
        if permission_value.repoable
    ])
Beispiel #7
0
def _get_repoable_permissions_batch(repo_able_roles, permissions_dict,
                                    minimum_age, hooks, batch_size):
    """
    Generate a dictionary mapping of role arns to their repoable permissions based on the list of all permissions the
    role's policies currently allow and Access Advisor data for the services included in the role's policies.

    The first step is to come up with a list of services that were used within the time threshold (the same defined)
    in the age filter config. Permissions are repoable if they aren't in the used list, aren't in the constant list
    of unsupported services/actions (IAM_ACCESS_ADVISOR_UNSUPPORTED_SERVICES, IAM_ACCESS_ADVISOR_UNSUPPORTED_ACTIONS),
    and aren't being temporarily ignored because they're on the no_repo_permissions list (newly added).

    Args:
    repo_able_roles: (list): List of the roles that can be checked for repoing
    permissions_dict (dict): Mapping role arns to their full list of permissions that the role's permissions allow
    minimum_age: Minimum age of a role (in days) for it to be repoable
    hooks: Dict containing hook names and functions to run

    Returns:
        dict: Mapping role arns to set of permissions that are 'repoable' (not used within the time threshold)
    """

    if len(repo_able_roles) == 0:
        return {}

    repo_able_roles_batches = copy.deepcopy(repo_able_roles)
    potentially_repoable_permissions_dict = {}
    repoable_set_dict = {}
    repoable_log_dict = {}

    for role in repo_able_roles:
        potentially_repoable_permissions_dict[
            role.arn] = _get_potentially_repoable_permissions(
                role.role_name,
                role.account,
                role.aa_data,
                permissions_dict[role.arn],
                role.no_repo_permissions,
                minimum_age,
            )

    while len(repo_able_roles_batches) > 0:
        role_batch = repo_able_roles_batches[:batch_size]
        repo_able_roles_batches = repo_able_roles_batches[batch_size:]

        hooks_output = repokid.hooks.call_hooks(
            hooks,
            "DURING_REPOABLE_CALCULATION_BATCH",
            {
                "role_batch": role_batch,
                "potentially_repoable_permissions":
                potentially_repoable_permissions_dict,
                "minimum_age": minimum_age,
            },
        )
        for role_arn, output in list(hooks_output.items()):
            repoable_set = set([
                permission_name for permission_name, permission_value in list(
                    output["potentially_repoable_permissions"].items())
                if permission_value.repoable
            ])
            repoable_set_dict[role_arn] = repoable_set
            repoable_log_dict[role_arn] = "".join(
                "{}: {}\n".format(perm, decision.decider)
                for perm, decision in list(
                    output["potentially_repoable_permissions"].items()))

    for role in repo_able_roles:
        LOGGER.debug(
            "Repoable permissions for role {role_name} in {account_number}:\n{repoable}"
            .format(
                role_name=role.role_name,
                account_number=role.account,
                repoable=repoable_log_dict[role.arn],
            ))
    return repoable_set_dict
Beispiel #8
0
def _get_repoable_permissions(
    account_number,
    role_name,
    permissions,
    aa_data,
    no_repo_permissions,
    minimum_age,
    hooks,
):
    """
    Generate a list of repoable permissions for a role based on the list of all permissions the role's policies
    currently allow and Access Advisor data for the services included in the role's policies.

    The first step is to come up with a list of services that were used within the time threshold (the same defined)
    in the age filter config. Permissions are repoable if they aren't in the used list, aren't in the constant list
    of unsupported services/actions (IAM_ACCESS_ADVISOR_UNSUPPORTED_SERVICES, IAM_ACCESS_ADVISOR_UNSUPPORTED_ACTIONS),
    and aren't being temporarily ignored because they're on the no_repo_permissions list (newly added).

    Args:
        account_number
        role_name
        permissions (list): The full list of permissions that the role's permissions allow
        aa_data (list): A list of Access Advisor data for a role. Each element is a dictionary with a couple required
                        attributes: lastAuthenticated (epoch time in milliseconds when the service was last used and
                        serviceNamespace (the service used)
        no_repo_permissions (dict): Keys are the name of permissions and values are the time the entry expires
        minimum_age: Minimum age of a role (in days) for it to be repoable
        hooks: Dict containing hook names and functions to run

    Returns:
        set: Permissions that are 'repoable' (not used within the time threshold)
    """
    potentially_repoable_permissions = _get_potentially_repoable_permissions(
        role_name,
        account_number,
        aa_data,
        permissions,
        no_repo_permissions,
        minimum_age,
    )

    hooks_output = repokid.hooks.call_hooks(
        hooks,
        "DURING_REPOABLE_CALCULATION",
        {
            "account_number": account_number,
            "role_name": role_name,
            "potentially_repoable_permissions":
            potentially_repoable_permissions,
            "minimum_age": minimum_age,
        },
    )

    LOGGER.debug(
        "Repoable permissions for role {role_name} in {account_number}:\n{repoable}"
        .format(
            role_name=role_name,
            account_number=account_number,
            repoable="".join(
                "{}: {}\n".format(perm, decision.decider)
                for perm, decision in list(
                    hooks_output["potentially_repoable_permissions"].items())),
        ))

    return set([
        permission_name for permission_name, permission_value in list(
            hooks_output["potentially_repoable_permissions"].items())
        if permission_value.repoable
    ])
Beispiel #9
0
def check_and_log_during_repoable_calculation_hooks(input_dict):
    LOGGER.debug("Calling DURING_REPOABLE_CALCULATION hooks")
    if not all(
        ['role_name', 'potentially_repoable_permissions', 'minimum_age'
         ] in input_dict):
        raise hooks.MissingHookParamaeter
Beispiel #10
0
def check_and_log_after_repo_hooks():
    LOGGER.debug("Calling AFTER_REPO hooks")
    pass
Beispiel #11
0
def check_and_log_after_schedule_repo_hooks(input_dict):
    LOGGER.debug("Calling AFTER_SCHEDULE_REPO hooks")
    if 'roles' not in input_dict:
        raise hooks.MissingHookParamaeter
Beispiel #12
0
def update_role_cache(account_number, dynamo_table, config, hooks):
    """
    Update data about all roles in a given account:
      1) list all the roles and initiate a role object with basic data including name and roleID
      2) get inline policies for each of the roles
      3) build a list of active roles - we'll want to keep data about roles that may have been deleted in case we
         need to restore them, so if we used to have a role and now we don't see it we'll mark it inactive
      4) update data about the roles in Dynamo
      5) mark inactive roles in Dynamo
      6) load and instantiate filter plugins
      7) for each filter determine the list of roles that it filters
      8) update data in Dynamo about filters
      9) get Aardvark data for each role
      10) update Dynamo with Aardvark data
      11) calculate repoable permissions/policies for all the roles
      12) update Dynamo with information about how many total and repoable permissions and which services are repoable
      13) update stats in Dynamo with basic information like total permissions and which filters are applicable

    Args:
        account_number (string): The current account number Repokid is being run against

    Returns:
        None
    """
    conn = config['connection_iam']
    conn['account_number'] = account_number

    LOGGER.info('Getting current role data for account {} (this may take a while for large accounts)'.format(
        account_number))
    role_data = get_account_authorization_details(filter='Role', **conn)
    role_data_by_id = {item['RoleId']: item for item in role_data}

    # convert policies list to dictionary to maintain consistency with old call which returned a dict
    for _, data in role_data_by_id.items():
        data['RolePolicyList'] = {item['PolicyName']: item['PolicyDocument'] for item in data['RolePolicyList']}

    roles = Roles([Role(rd) for rd in role_data])

    active_roles = []
    LOGGER.info('Updating role data for account {}'.format(account_number))
    for role in tqdm(roles):
        role.account = account_number
        current_policies = role_data_by_id[role.role_id]['RolePolicyList']
        active_roles.append(role.role_id)
        roledata.update_role_data(dynamo_table, account_number, role, current_policies)

    LOGGER.info('Finding inactive roles in account {}'.format(account_number))
    roledata.find_and_mark_inactive(dynamo_table, account_number, active_roles)

    LOGGER.info('Filtering roles')
    plugins = FilterPlugins()

    # Blacklist needs to know the current account
    config['filter_config']['BlacklistFilter']['current_account'] = account_number

    for plugin_path in config.get('active_filters'):
        plugin_name = plugin_path.split(':')[1]
        plugins.load_plugin(plugin_path, config=config['filter_config'].get(plugin_name, None))

    for plugin in plugins.filter_plugins:
        filtered_list = plugin.apply(roles)
        class_name = plugin.__class__.__name__
        for filtered_role in filtered_list:
            LOGGER.info('Role {} filtered by {}'.format(filtered_role.role_name, class_name))
            filtered_role.disqualified_by.append(class_name)

    for role in roles:
        set_role_data(dynamo_table, role.role_id, {'DisqualifiedBy': role.disqualified_by})

    LOGGER.info('Getting data from Aardvark for account {}'.format(account_number))
    aardvark_data = _get_aardvark_data(config['aardvark_api_location'], account_number=account_number)

    LOGGER.info('Updating roles with Aardvark data in account {}'.format(account_number))
    for role in roles:
        try:
            role.aa_data = aardvark_data[role.arn]
        except KeyError:
            LOGGER.warning('Aardvark data not found for role: {} ({})'.format(role.role_id, role.role_name))
        else:
            set_role_data(dynamo_table, role.role_id, {'AAData': role.aa_data})

    LOGGER.info('Calculating repoable permissions and services for account {}'.format(account_number))
    roledata._calculate_repo_scores(roles, config['filter_config']['AgeFilter']['minimum_age'], hooks)
    for role in roles:
        LOGGER.debug('Role {} in account {} has\nrepoable permissions: {}\nrepoable services:'.format(
            role.role_name, account_number, role.repoable_permissions, role.repoable_services
        ))
        set_role_data(dynamo_table, role.role_id, {'TotalPermissions': role.total_permissions,
                                                   'RepoablePermissions': role.repoable_permissions,
                                                   'RepoableServices': role.repoable_services})

    LOGGER.info('Updating stats in account {}'.format(account_number))
    roledata.update_stats(dynamo_table, roles, source='Scan')
Beispiel #13
0
def main():
    args = docopt(__doc__, version='Repokid {version}'.format(version=__version__))

    if args.get('config'):
        config_filename = args.get('<config_filename>')
        _generate_default_config(filename=config_filename)
        sys.exit(0)

    account_number = args.get('<account_number>')

    if not CONFIG:
        config = _generate_default_config()
    else:
        config = CONFIG

    LOGGER.debug('Repokid cli called with args {}'.format(args))

    hooks = _get_hooks(config.get('hooks', ['repokid.hooks.loggers']))
    dynamo_table = dynamo_get_or_create_table(**config['dynamo_db'])

    if args.get('update_role_cache'):
        return update_role_cache(account_number, dynamo_table, config, hooks)

    if args.get('display_role_cache'):
        inactive = args.get('--inactive')
        return display_roles(account_number, dynamo_table, inactive=inactive)

    if args.get('find_roles_with_permission'):
        return find_roles_with_permission(args.get('<permission>'), dynamo_table)

    if args.get('display_role'):
        role_name = args.get('<role_name>')
        return display_role(account_number, role_name, dynamo_table, config, hooks)

    if args.get('repo_role'):
        role_name = args.get('<role_name>')
        commit = args.get('--commit')
        return repo_role(account_number, role_name, dynamo_table, config, hooks, commit=commit)

    if args.get('rollback_role'):
        role_name = args.get('<role_name>')
        commit = args.get('--commit')
        selection = args.get('--selection')
        return rollback_role(account_number, role_name, dynamo_table, config, hooks, selection=selection, commit=commit)

    if args.get('repo_all_roles'):
        LOGGER.info('Updating role data')
        update_role_cache(account_number, dynamo_table, config, hooks)
        LOGGER.info('Repoing all roles')
        commit = args.get('--commit')
        return repo_all_roles(account_number, dynamo_table, config, hooks, commit=commit, scheduled=False)

    if args.get('schedule_repo'):
        LOGGER.info('Updating role data')
        update_role_cache(account_number, dynamo_table, config, hooks)
        return schedule_repo(account_number, dynamo_table, config, hooks)

    if args.get('show_scheduled_roles'):
        LOGGER.info('Showing scheduled roles')
        return show_scheduled_roles(account_number, dynamo_table)

    if args.get('cancel_scheduled_repo'):
        role_name = args.get('--role')
        is_all = args.get('--all')
        if not is_all:
            LOGGER.info('Cancelling scheduled repo for role: {} in account {}'.format(role_name, account_number))
        else:
            LOGGER.info('Cancelling scheduled repo for all roles in account {}'.format(account_number))
        return cancel_scheduled_repo(account_number, dynamo_table, role_name=role_name, is_all=is_all)

    if args.get('repo_scheduled_roles'):
        update_role_cache(account_number, dynamo_table, config, hooks)
        LOGGER.info('Repoing scheduled roles')
        commit = args.get('--commit')
        return repo_all_roles(account_number, dynamo_table, config, hooks, commit=commit, scheduled=True)

    if args.get('repo_stats'):
        output_file = args.get('<output_filename>')
        account_number = args.get('--account')
        return repo_stats(output_file, dynamo_table, account_number=account_number)
Beispiel #14
0
def main():
    args = docopt(__doc__,
                  version="Repokid {version}".format(version=__version__))

    if args.get("config"):
        config_filename = args.get("<config_filename>")
        _generate_default_config(filename=config_filename)
        sys.exit(0)

    account_number = args.get("<account_number>")

    if not CONFIG:
        config = _generate_default_config()
    else:
        config = CONFIG

    LOGGER.debug("Repokid cli called with args {}".format(args))

    hooks = get_hooks(config.get("hooks", ["repokid.hooks.loggers"]))
    dynamo_table = dynamo_get_or_create_table(**config["dynamo_db"])

    if args.get("update_role_cache"):
        return update_role_cache(account_number, dynamo_table, config, hooks)

    if args.get("display_role_cache"):
        inactive = args.get("--inactive")
        return display_roles(account_number, dynamo_table, inactive=inactive)

    if args.get("find_roles_with_permissions"):
        permissions = args.get("<permission>")
        output_file = args.get("--output")
        return find_roles_with_permissions(permissions, dynamo_table,
                                           output_file)

    if args.get("remove_permissions_from_roles"):
        permissions = args.get("<permission>")
        role_filename = args.get("--role-file")
        commit = args.get("--commit")
        return remove_permissions_from_roles(permissions,
                                             role_filename,
                                             dynamo_table,
                                             config,
                                             hooks,
                                             commit=commit)

    if args.get("display_role"):
        role_name = args.get("<role_name>")
        return display_role(account_number, role_name, dynamo_table, config,
                            hooks)

    if args.get("repo_role"):
        role_name = args.get("<role_name>")
        commit = args.get("--commit")
        return repo_role(account_number,
                         role_name,
                         dynamo_table,
                         config,
                         hooks,
                         commit=commit)

    if args.get("rollback_role"):
        role_name = args.get("<role_name>")
        commit = args.get("--commit")
        selection = args.get("--selection")
        return rollback_role(
            account_number,
            role_name,
            dynamo_table,
            config,
            hooks,
            selection=selection,
            commit=commit,
        )

    if args.get("repo_all_roles"):
        LOGGER.info("Updating role data")
        update_role_cache(account_number, dynamo_table, config, hooks)
        LOGGER.info("Repoing all roles")
        commit = args.get("--commit")
        return repo_all_roles(account_number,
                              dynamo_table,
                              config,
                              hooks,
                              commit=commit,
                              scheduled=False)

    if args.get("schedule_repo"):
        LOGGER.info("Updating role data")
        update_role_cache(account_number, dynamo_table, config, hooks)
        return schedule_repo(account_number, dynamo_table, config, hooks)

    if args.get("show_scheduled_roles"):
        LOGGER.info("Showing scheduled roles")
        return show_scheduled_roles(account_number, dynamo_table)

    if args.get("cancel_scheduled_repo"):
        role_name = args.get("--role")
        is_all = args.get("--all")
        if not is_all:
            LOGGER.info(
                "Cancelling scheduled repo for role: {} in account {}".format(
                    role_name, account_number))
        else:
            LOGGER.info(
                "Cancelling scheduled repo for all roles in account {}".format(
                    account_number))
        return cancel_scheduled_repo(account_number,
                                     dynamo_table,
                                     role_name=role_name,
                                     is_all=is_all)

    if args.get("repo_scheduled_roles"):
        update_role_cache(account_number, dynamo_table, config, hooks)
        LOGGER.info("Repoing scheduled roles")
        commit = args.get("--commit")
        return repo_all_roles(account_number,
                              dynamo_table,
                              config,
                              hooks,
                              commit=commit,
                              scheduled=True)

    if args.get("repo_stats"):
        output_file = args.get("<output_filename>")
        account_number = args.get("--account")
        return repo_stats(output_file,
                          dynamo_table,
                          account_number=account_number)
Beispiel #15
0
def log_after_schedule_repo_hooks(input_dict):
    LOGGER.debug("Calling AFTER_SCHEDULE_REPO hooks")
    if "roles" not in input_dict:
        raise hooks.MissingHookParamaeter(
            "Required key 'roles' not passed to AFTER_SCHEDULE_REPO")
    return input_dict