|
| 1 | +""" |
| 2 | +Script to force unlock locks in terraform with a given prefix and of a certain age. |
| 3 | +
|
| 4 | +Warning this script should be used with care. |
| 5 | +
|
| 6 | +This script has to be used because sometimes the ecs pr pipeline cleanup won't always properly release the lock when |
| 7 | +it fails. |
| 8 | +
|
| 9 | +CLI arguments: |
| 10 | + --min-age-hr |
| 11 | + --key-prefix |
| 12 | + --table-name |
| 13 | + --profile |
| 14 | +
|
| 15 | +Example usage: |
| 16 | +
|
| 17 | +python ./terraform_force_unlock.py --min-age-hr=8 --key-prefix=nhsd-apm-management-ptl-terraform/env:/api-deployment:ptl: --table-name=terraform-state-lock --profile=apm_ptl |
| 18 | +
|
| 19 | +""" |
| 20 | + |
| 21 | +import json |
| 22 | +import boto3 |
| 23 | +import dateutil |
| 24 | +import datetime |
| 25 | +import click |
| 26 | + |
| 27 | + |
| 28 | +@click.command() |
| 29 | +@click.option("--min-age-hr", type=int, default=8) |
| 30 | +@click.option("--key-prefix", type=str, default="nhsd-apm-management-ptl-terraform/env:/api-deployment:ptl:") |
| 31 | +@click.option("--table-name", type=str, default="terraform-state-lock") |
| 32 | +@click.option("--profile", type=str, default="apm_ptl") |
| 33 | +def main(min_age_hr, key_prefix, table_name, profile): |
| 34 | + |
| 35 | + accepted_envs = ["apm_ptl", "apm_prod"] |
| 36 | + |
| 37 | + if profile not in accepted_envs: |
| 38 | + raise ValueError("Profile must be apm_ptl or apm_prod") |
| 39 | + |
| 40 | + terraform_lock_table = boto3.Session(profile_name=profile).resource("dynamodb").Table(table_name) |
| 41 | + |
| 42 | + filter_expr = "begins_with(#n0, :v0) AND attribute_exists(#n1)" |
| 43 | + |
| 44 | + ExpressionAttributeNames = {"#n0": "LockID", "#n1": "Info"} |
| 45 | + ExpressionAttributeValues = { |
| 46 | + ":v0": key_prefix, |
| 47 | + } |
| 48 | + items = terraform_lock_table.scan(FilterExpression=filter_expr, ExpressionAttributeNames=ExpressionAttributeNames, ExpressionAttributeValues=ExpressionAttributeValues) |
| 49 | + print(f"Found {len(items['Items'])} locks which start with key prefix '{key_prefix}'") |
| 50 | + |
| 51 | + removed_count = 0 |
| 52 | + for lock_item in items["Items"]: |
| 53 | + lock_item_info = json.loads(lock_item["Info"]) |
| 54 | + lock_id = lock_item["LockID"] |
| 55 | + created_at = dateutil.parser.parse(lock_item_info["Created"]) |
| 56 | + |
| 57 | + if datetime.datetime.now(datetime.timezone.utc) - created_at > datetime.timedelta(hours=min_age_hr): |
| 58 | + print(f"{lock_id} {created_at=} is more than {min_age_hr} hours old, deleting lock...") |
| 59 | + terraform_lock_table.delete_item(Key={"LockID": lock_id}) |
| 60 | + removed_count += 1 |
| 61 | + |
| 62 | + else: |
| 63 | + print(f"{lock_id} {created_at=} is not more than {min_age_hr} hours old, leaving it alone!") |
| 64 | + |
| 65 | + print(f"Removed {removed_count} locks") |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + main() |
0 commit comments