Example #1
0
def discover_scaling_groups(
    client: boto3.client, asgs: List[str] = None, tags: List[Dict[str, Any]] = None
) -> AWSResponse:
    if not any([asgs, tags]):
        raise FailedActivity(
            "missing one of the required parameters: asg_names or tags"
        )
    if not asgs:
        asgs = []

    if tags:
        tag_filter = []
        for t in tags:
            tag_filter.append({"Name": t["Key"], "Values": [t["Value"]]})
        paginator = client.get_paginator("describe_tags")
        for p in paginator.paginate(Filters=tag_filter):
            asgs.extend(
                [t["ResourceId"] for t in p["Tags"] if t["ResourceId"] not in asgs]
            )

    results = {"AutoScalingGroups": []}
    for group in breakup_iterable(asgs, 50):
        response = client.describe_auto_scaling_groups(AutoScalingGroupNames=group)
        results["AutoScalingGroups"].extend(response["AutoScalingGroups"])
    return results
Example #2
0
def discover_scaling_groups(client: boto3.client,
                            asgs: List[str] = None,
                            tags: List[Dict[str, Any]] = None) -> AWSResponse:
    if not any([asgs, tags]):
        raise FailedActivity(
            'missing one of the required parameters: asg_names or tags')
    if not asgs:
        asgs = []

    if tags:
        tag_filter = []
        for t in tags:
            tag_filter.append({'Name': t['Key'], 'Values': [t['Value']]})
        paginator = client.get_paginator('describe_tags')
        for p in paginator.paginate(Filters=tag_filter):
            asgs.extend([
                t['ResourceId'] for t in p['Tags']
                if t['ResourceId'] not in asgs
            ])

    results = {'AutoScalingGroups': []}
    for group in breakup_iterable(asgs, 50):
        response = client.describe_auto_scaling_groups(
            AutoScalingGroupNames=group)
        results['AutoScalingGroups'].extend(response['AutoScalingGroups'])
    return results
def get_asg_by_name(asg_names: List[str], client: boto3.client) -> AWSResponse:
    logger.debug(f"Searching for ASG(s): {asg_names}.")

    asgs = client.describe_auto_scaling_groups(AutoScalingGroupNames=asg_names)

    if not asgs.get("AutoScalingGroups", []):
        raise FailedActivity(f"Unable to locate ASG(s): {asg_names}")

    found_asgs = [a["AutoScalingGroupName"] for a in asgs["AutoScalingGroups"]]
    invalid_asgs = [a for a in asg_names if a not in found_asgs]
    if invalid_asgs:
        raise FailedActivity(f"No ASG(s) found with name(s): {invalid_asgs}")
    return asgs
Example #4
0
def get_asg_by_name(asg_names: List[str], client: boto3.client) -> AWSResponse:
    logger.debug('Searching for ASG(s): {}.'.format(asg_names))

    asgs = client.describe_auto_scaling_groups(AutoScalingGroupNames=asg_names)

    if not asgs.get('AutoScalingGroups', []):
        raise FailedActivity('Unable to locate ASG(s): {}'.format(asg_names))

    found_asgs = [a['AutoScalingGroupName'] for a in asgs['AutoScalingGroups']]
    invalid_asgs = [a for a in asg_names if a not in found_asgs]
    if invalid_asgs:
        raise FailedActivity(
            'No ASG(s) found with name(s): {}'.format(invalid_asgs))
    return asgs
Example #5
0
def get_asg_by_tags(
    tags: Union[dict, List[Dict[str, str]]], client: boto3.client
) -> AWSResponse:
    # The following is needed because AWS API does not support filters
    # on auto-scaling groups

    # fetch all ASGs using paginator
    # TODO: simplify this function (similar to actions) & update unit tests
    page_iterator = client.get_paginator("describe_auto_scaling_groups").paginate(
        PaginationConfig={"PageSize": 100}
    )

    asg_descrs = {"AutoScalingGroups": []}

    for page in page_iterator:
        asg_descrs["AutoScalingGroups"].extend(page["AutoScalingGroups"])

    filter_set = set(map(lambda x: "=".join([x["Key"], x["Value"]]), tags))

    group_sets = list(
        map(
            lambda g: {
                "Name": g["AutoScalingGroupName"],
                "Tags": set(map(lambda t: "=".join([t["Key"], t["Value"]]), g["Tags"])),
            },
            asg_descrs["AutoScalingGroups"],
        )
    )

    filtered_groups = [g["Name"] for g in group_sets if filter_set.issubset(g["Tags"])]

    logger.debug(f"filtered groups: {filtered_groups}")

    if filtered_groups:
        groups_descr = client.describe_auto_scaling_groups(
            AutoScalingGroupNames=filtered_groups
        )

        return groups_descr
    else:
        raise FailedActivity("No auto-scaling groups matched the tags provided")
Example #6
0
def get_asg_by_tags(tags: Union[dict, List[Dict[str, str]]],
                    client: boto3.client) -> AWSResponse:

    # The following is needed because AWS API does not support filters
    # on auto-scaling groups

    # fetch all ASGs using paginator
    page_iterator = client.get_paginator(
        'describe_auto_scaling_groups').paginate(
            PaginationConfig={'PageSize': 100})
    asg_descrs = {'AutoScalingGroups': []}

    for page in page_iterator:
        asg_descrs['AutoScalingGroups'].extend(page['AutoScalingGroups'])

    filter_set = set(map(lambda x: "=".join([x['Key'], x['Value']]), tags))

    group_sets = list(
        map(
            lambda g: {
                'Name':
                g['AutoScalingGroupName'],
                'Tags':
                set(map(lambda t: "=".join([t['Key'], t['Value']]), g['Tags']))
            }, asg_descrs['AutoScalingGroups']))

    filtered_groups = [
        g['Name'] for g in group_sets if filter_set.issubset(g['Tags'])
    ]

    logger.debug("filtered groups: {}".format(filtered_groups))

    if filtered_groups:
        groups_descr = client.describe_auto_scaling_groups(
            AutoScalingGroupNames=filtered_groups)

        return groups_descr
    else:
        raise FailedActivity(
            "No auto-scaling groups matched the tags provided")