destroy.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # Copyright Materialize, Inc. and contributors. All rights reserved.
  2. #
  3. # Use of this software is governed by the Business Source License
  4. # included in the LICENSE file at the root of this repository.
  5. #
  6. # As of the Change Date specified in that file, in accordance with
  7. # the Business Source License, use of this software will be governed
  8. # by the Apache License, Version 2.0.
  9. import argparse
  10. import sys
  11. import boto3
  12. from mypy_boto3_ec2.type_defs import FilterTypeDef
  13. from materialize.cli.scratch import check_required_vars
  14. from materialize.scratch import print_instances, ui, whoami
  15. def configure_parser(parser: argparse.ArgumentParser) -> None:
  16. parser.add_argument(
  17. "instances",
  18. nargs="*",
  19. help="Instance IDs to destroy",
  20. )
  21. parser.add_argument(
  22. "--all-mine",
  23. action="store_true",
  24. help="Destroy all of your instances (incompatible with specifying instance IDs)",
  25. )
  26. parser.add_argument(
  27. "-y",
  28. "--yes",
  29. action="store_true",
  30. help="Don't ask for confirmation before destroying",
  31. )
  32. parser.add_argument("--output-format", choices=["table", "csv"], default="table")
  33. def run(args: argparse.Namespace) -> None:
  34. check_required_vars()
  35. instance_ids = []
  36. filters: list[FilterTypeDef] = [
  37. {
  38. "Name": "instance-state-name",
  39. "Values": ["pending", "running", "stopping", "stopped"],
  40. }
  41. ]
  42. if args.all_mine:
  43. if args.instances:
  44. print(
  45. "scratch: error: cannot specify --all-mine and instance IDs",
  46. file=sys.stderr,
  47. )
  48. sys.exit(1)
  49. filters.append({"Name": "tag:LaunchedBy", "Values": [whoami()]})
  50. elif not args.instances:
  51. print(
  52. "scratch: error: must supply at least one instance ID to destroy",
  53. file=sys.stderr,
  54. )
  55. sys.exit(1)
  56. else:
  57. instance_ids.extend(args.instances)
  58. instances = list(
  59. boto3.resource("ec2").instances.filter(
  60. Filters=filters, InstanceIds=instance_ids
  61. )
  62. )
  63. print("Destroying instances:")
  64. print_instances(instances, args.output_format)
  65. if not args.yes and not ui.confirm("Would you like to continue?"):
  66. sys.exit(0)
  67. for instance in instances:
  68. instance.terminate()
  69. print("Instances destroyed.")