Write a CLI tool with argparse that has subcommands `deploy` and `rollback`.
IntermediateHands-onPython for DevOps
Answer
import argparse
def deploy(a): print(f"deploying {a.version} to {a.env}")
def rollback(a): print(f"rolling back {a.env}")
p = argparse.ArgumentParser(prog="shipit")
sub = p.add_subparsers(dest="cmd", required=True)
d = sub.add_parser("deploy"); d.add_argument("version"); d.set_defaults(func=deploy)
r = sub.add_parser("rollback"); r.set_defaults(func=rollback)
for sp in (d, r):
sp.add_argument("--env", choices=["dev", "staging", "prod"], required=True)
args = p.parse_args()
args.func(args)
Key trick → set_defaults(func=...) sends each subcommand to its handler with no if/elif chain, and choices= validates input for free.
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.Intermediate