Пример #1
0
def handler_init():
    global HANDLER_INITIALIZED, \
        SESSION, \
        IDS, \
        LOOKUP_NAMES, \
        CHILD_TEMPLATES_IN_YAML, \
        MAX_RESOURCES_PER_TEMPLATE, \
        MAX_CONCURRENT_ASSIGNMENTS, \
        MAX_ASSIGNMENTS_ALLOCATION, \
        NUM_CHILD_STACKS, \
        DEFAULT_SESSION_DURATION, \
        BUCKET_NAME, \
        KEY_PREFIX, \
        S3_PUT_OBJECT_ARGS
    if HANDLER_INITIALIZED:
        return

    logging.getLogger("aws_sso_util").setLevel(
        getattr(logging, os.environ.get("LOG_LEVEL", "INFO")))
    logging.basicConfig()

    LOGGER.info("Initializing handler")

    SESSION = boto3.Session()
    IDS = lookup.Ids(lambda: SESSION)

    LOOKUP_NAMES = os.environ.get("LOOKUP_NAMES",
                                  "false").lower() in ["true", "1"]
    CHILD_TEMPLATES_IN_YAML = os.environ.get("CHILD_TEMPLATES_IN_YAML",
                                             "false").lower() in ["true", "1"]

    MAX_RESOURCES_PER_TEMPLATE = int(
        os.environ["MAX_RESOURCES_PER_TEMPLATE"]) if os.environ.get(
            "MAX_RESOURCES_PER_TEMPLATE") else None
    MAX_CONCURRENT_ASSIGNMENTS = int(
        os.environ["MAX_CONCURRENT_ASSIGNMENTS"]) if os.environ.get(
            "MAX_CONCURRENT_ASSIGNMENTS") else None
    MAX_ASSIGNMENTS_ALLOCATION = int(
        os.environ["MAX_ASSIGNMENTS_ALLOCATION"]) if os.environ.get(
            "MAX_ASSIGNMENTS_ALLOCATION") else None
    NUM_CHILD_STACKS = int(os.environ["NUM_CHILD_STACKS"]) if os.environ.get(
        "NUM_CHILD_STACKS") else None
    DEFAULT_SESSION_DURATION = os.environ[
        "DEFAULT_SESSION_DURATION"] if os.environ.get(
            "DEFAULT_SESSION_DURATION") else None

    BUCKET_NAME = os.environ["BUCKET_NAME"]
    KEY_PREFIX = os.environ.get("KEY_PREFIX", "")

    try:
        S3_PUT_OBJECT_ARGS = json.loads(
            os.environ["S3_PUT_OBJECT_ARGS"]) if os.environ.get(
                "S3_PUT_OBJECT_ARGS") else {}
    except:
        LOGGER.exception("Error parsing S3_PUT_OBJECT_ARGS")

    HANDLER_INITIALIZED = True
Пример #2
0
def generate_template(config_file, macro, profile, sso_instance,
                      template_file_suffix, output_dir, base_template_file,
                      template_parameters, lookup_names, num_child_stacks,
                      max_assignments_allocation, default_session_duration,
                      max_resources_per_template, max_concurrent_assignments,
                      assignments_csv, assignments_csv_only, verbose):
    configure_logging(LOGGER, verbose)

    if macro and base_template_file:
        raise click.UsageError("--base-template-file not allowed with --macro")
    if macro and template_parameters:
        raise click.UsageError(
            "--template-parameters not allowed with --macro")

    if assignments_csv_only and not assignments_csv:
        raise click.UsageError("Missing --assignments-csv")

    session = boto3.Session(profile_name=profile)

    ids = lookup.Ids(session, sso_instance, identity_store_id=None)

    cache = {}

    if lookup_names:
        principal_name_fetcher = cfn_utils.get_principal_name_fetcher(
            session, ids, cache)
        permission_set_name_fetcher = cfn_utils.get_permission_set_name_fetcher(
            session, ids, cache)
        target_name_fetcher = cfn_utils.get_target_name_fetcher(
            session, ids, cache)
    else:
        principal_name_fetcher = None
        permission_set_name_fetcher = None
        target_name_fetcher = None

    generation_config = GenerationConfig(
        ids,
        principal_name_fetcher=principal_name_fetcher,
        permission_set_name_fetcher=permission_set_name_fetcher,
        target_name_fetcher=target_name_fetcher)

    generation_config.set(
        max_resources_per_template=max_resources_per_template,
        max_concurrent_assignments=max_concurrent_assignments,
        max_assignments_allocation=max_assignments_allocation,
        num_child_stacks=num_child_stacks,
        default_session_duration=default_session_duration,
    )

    ou_fetcher = lambda ou, recursive: [
        a["Id"] for a in lookup.lookup_accounts_for_ou(
            session, ou, recursive=recursive, cache=cache)
    ]

    if not template_file_suffix:
        template_file_suffix = ".yaml"
    elif not template_file_suffix.endswith(".yaml"):
        template_file_suffix = template_file_suffix + ".yaml"

    if base_template_file:
        base_template = cfn_utils.load_yaml(base_template_file)
        base_template_path = Path(base_template_file.name).resolve()
        prev_len = len(config_file)
        config_file = [
            c for c in config_file
            if Path(c.name).resolve() != base_template_path
        ]
        if len(config_file) != prev_len:
            LOGGER.debug(
                "Removed base template file from list of config files")
    else:
        base_template = None

    if macro:
        template_process_inputs = process_macro(
            config_file=config_file,
            session=session,
            ids=ids,
            ou_fetcher=ou_fetcher,
            template_file_suffix=template_file_suffix,
            output_dir=output_dir,
            base_generation_config=generation_config,
        )
    else:
        template_process_inputs = process_config(
            config_file=config_file,
            session=session,
            ids=ids,
            ou_fetcher=ou_fetcher,
            template_file_suffix=template_file_suffix,
            output_dir=output_dir,
            base_template=base_template,
            base_generation_config=generation_config,
        )

    templates_to_write = process_templates(
        template_process_inputs=template_process_inputs,
        template_file_suffix=template_file_suffix,
    )

    if not assignments_csv_only:
        write_templates(templates_to_write)

    if assignments_csv:
        write_csv(template_process_inputs, assignments_csv, generation_config)
Пример #3
0
def lookup(type, value, instance_arn, identity_store_id, profile,
           error_if_not_found, show_id, separator, header,
           permission_set_style, verbose):
    """Look up names and ids in AWS SSO"""
    configure_logging(LOGGER, verbose)

    session = boto3.Session(profile_name=profile)

    cache = JSONFileCache(IDS_CACHE_DIR)

    ids = _lookup.Ids(session, instance_arn, identity_store_id, cache=cache)
    ids.print_on_fetch = show_id

    HEADER_FIELDS = {
        "group": ["Name", "Id"],
        "user": ["Name", "Id"],
        "permission-set": ["Name", permission_set_style.upper()],
    }

    printer = Printer(
        separator=separator,
        default_separator=" ",
        header_fields=HEADER_FIELDS.get(type),
        disable_header=header,
    )

    try:
        if type == "instance":
            ids.print_on_fetch = False
            print(ids.instance_arn)
        elif type == "identity-store":
            ids.print_on_fetch = False
            print(ids.identity_store_id)
        elif type in "group":
            if not value:
                raise click.UsageError("Group name is required")
            lookup_groups(session,
                          ids,
                          value,
                          printer,
                          error_if_not_found=error_if_not_found)
        elif type == "user":
            if not value:
                raise click.UsageError("User name is required")
            lookup_users(session,
                         ids,
                         value,
                         printer,
                         error_if_not_found=error_if_not_found)
        elif type == "permission-set":
            if not value:
                raise click.UsageError("Permission set name is required")
            if len(value) == 1 and value[0] == ":all":
                lookup_all_permission_sets(
                    session,
                    ids,
                    printer,
                    permission_set_style=permission_set_style)
            else:
                lookup_permission_sets(
                    session,
                    ids,
                    value,
                    printer,
                    permission_set_style=permission_set_style,
                    error_if_not_found=error_if_not_found)

    except _lookup.LookupError as e:
        print(e, file=sys.stderr)
        sys.exit(1)