Python Script to Delete Inactive Greengrass V2 Component Deployments

Python Script to Delete Inactive Greengrass V2 Component Deployments

Takahiro Iwasa
Takahiro Iwasa
2 min read
Greengrass

Deployments of AWS IoT Greengrass V2 components are saved as revisions so that users can quickly roll back to a previous version. However, you may have too many revisions to delete them manually, so I wrote a Python script to clear all the inactive deployments.

Create inactive_deployments_deleter.py with the following code.

import argparse
from time import sleep

import boto3

client = boto3.client('greengrassv2')


def list_inactive_deployments(arn: str, next_token: str = '') -> list:
    """ List inactive deployments.

    Args:
        arn (str): ARN of an AWS IoT Thing/Thing Group
        next_token (str): Next token returned by `list_deployments` API

    Returns:
        list: All INACTIVE deployments
    """

    result = client.list_deployments(
        targetArn=arn,
        historyFilter='ALL',
        nextToken=next_token,
        maxResults=100,
    )
    deployments = result.get('deployments', [])
    deployments = [deployment for deployment in deployments if deployment.get('deploymentStatus') == 'INACTIVE']

    if result.get('nextToken'):
        sleep(0.5)
        deployments.extend(list_inactive_deployments(arn, result.get('nextToken')))

    return deployments


def delete_deployments(deployments: list) -> None:
    """ Delete deployments.

    Args:
        deployments (list): Deployments returned by `list_deployments` API
    """

    for deployment in deployments:
        client.delete_deployment(deploymentId=deployment.get('deploymentId'))
        sleep(0.5)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument('--target-arn', required=True)
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    deployments = list_inactive_deployments(args.target_arn)
    delete_deployments(deployments)


if __name__ == '__main__':
    main()

Run the script with the --target-arn argument like the following.

python inactive_deployments_deleter.py --target-arn "arn:aws:iot:ap-northeast-1:<AWS_ACCOUNT_ID>:thing/<YOUR_THING_NAME>"
Takahiro Iwasa

Takahiro Iwasa

Software Developer at KAKEHASHI Inc.
Involved in the requirements definition, design, and development of cloud-native applications using AWS. Now, building a new prescription data collection platform at KAKEHASHI Inc. Japan AWS Top Engineers 2020-2023.