Skip to content

Instantly share code, notes, and snippets.

@falkben
Created December 8, 2022 22:56
Show Gist options
  • Save falkben/2efbbbffbae5afb9279149c5353df106 to your computer and use it in GitHub Desktop.
Save falkben/2efbbbffbae5afb9279149c5353df106 to your computer and use it in GitHub Desktop.
run.py command for running terraform commands in different environments and modules
#!/usr/bin/env python3
"""Script to execute terraform commands in the correct environment per module
Examples:
# init backend for lambdas module inside sandbox environment
./run.py sb lambdas init
# deploy platform module for dev environment
./run.py dev platform
MIT License
Copyright (c) 2022 Ben Falk
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import annotations
import argparse
import os
import subprocess
from pathlib import Path
from typing import Sequence
ENVIRONS = ["sb", "dev", "test", "ops"]
def run_command(args: Sequence[str]) -> int:
# current directory of script
cwd = os.path.dirname(os.path.realpath(__file__))
exit_code = subprocess.run(args, cwd=cwd)
return exit_code.returncode
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser("Runs terraform commands in modules, loading the correct backend per environment")
parser.add_argument(
"environment",
type=str,
choices=ENVIRONS,
help="Environment to deploy to (e.g. sb/dev/test/ops)",
)
parser.add_argument("module", type=str, help="Module to run (e.g. buckets, lambdas, platform)")
parser.add_argument("command", type=str, help="terraform command to run (e.g. init, plan, apply, destroy)")
args, unknown_args = parser.parse_known_args(argv)
# validate environment/module exists
assert (Path(args.environment) / Path(args.module)).exists()
cmd_args = ["terraform", f"-chdir=./{args.environment}/{args.module}", args.command]
if args.command == "init":
cmd_args.append(f"-backend-config=../backend.hcl")
# add any extra arguments passed in
cmd_args += unknown_args
return run_command(cmd_args)
if __name__ == "__main__":
raise SystemExit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment