tf-project 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tf_project/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """tf_project — redistributable Terraform project wrapper."""
2
+
3
+ from tf_project.__version__ import __version__
4
+ from tf_project.banner import BannerError, ProjectInfoNotFoundError
5
+ from tf_project.config import Config, ConfigError, ConfigNotFoundError
6
+ from tf_project.state import MyState
7
+ from tf_project.terraform import TerraformExit
8
+
9
+ __all__ = [
10
+ "BannerError",
11
+ "Config",
12
+ "ConfigError",
13
+ "ConfigNotFoundError",
14
+ "MyState",
15
+ "ProjectInfoNotFoundError",
16
+ "TerraformExit",
17
+ "__version__",
18
+ ]
tf_project/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from tf_project.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
tf_project/banner.py ADDED
@@ -0,0 +1,140 @@
1
+ """Tfvars banner parsing and validation.
2
+
3
+ A banner is a single-line JSON object embedded in a `#` comment at the top
4
+ of a tfvars file, e.g.:
5
+
6
+ # {"header":"terraform","project":"api","state_key":"shared/api.tfstate"}
7
+
8
+ The `header` field must equal `"terraform"` for the line to be recognised.
9
+ Other supported fields are validated lazily by the per-field parsers below.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import pathlib
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ if TYPE_CHECKING:
19
+ from tf_project.config import Config
20
+
21
+
22
+ class ProjectInfoNotFoundError(RuntimeError):
23
+ """No `# {...}` JSON banner with `header == "terraform"` was found."""
24
+
25
+
26
+ class BannerError(ValueError):
27
+ """A field inside a terraform banner failed validation."""
28
+
29
+ def __init__(self, tfvars: pathlib.Path, message: str) -> None:
30
+ self.tfvars = tfvars
31
+ super().__init__(f"banner in {tfvars}: {message}")
32
+
33
+
34
+ def find_project_info(tfvars: pathlib.Path) -> dict[str, Any]:
35
+ """Locate the `# {...}` banner line; return its parsed JSON object."""
36
+ with tfvars.open("r") as fin:
37
+ for line in fin:
38
+ if not line.startswith("#"):
39
+ continue
40
+ maybe_json = line.lstrip("#").strip()
41
+ try:
42
+ data = json.loads(maybe_json)
43
+ except json.JSONDecodeError:
44
+ continue
45
+ if isinstance(data, dict) and data.get("header") == "terraform":
46
+ return data
47
+ raise ProjectInfoNotFoundError(
48
+ f"Project info banner not found in {tfvars}. "
49
+ 'Expected a comment line like `# {"header": "terraform", "project": "<name>"}`.'
50
+ )
51
+
52
+
53
+ def parse_project(info: dict[str, Any], *, tfvars: pathlib.Path) -> str:
54
+ name = info.get("project")
55
+ if not isinstance(name, str) or not name:
56
+ raise BannerError(tfvars, "`project` must be a non-empty string")
57
+ return name
58
+
59
+
60
+ def parse_env(info: dict[str, Any], *, tfvars: pathlib.Path) -> dict[str, str]:
61
+ raw = info.get("env")
62
+ if raw is None:
63
+ return {}
64
+ if not isinstance(raw, dict):
65
+ raise BannerError(tfvars, "`env` must be a JSON object")
66
+ out: dict[str, str] = {}
67
+ for key, value in raw.items():
68
+ if not isinstance(key, str) or not isinstance(value, str):
69
+ raise BannerError(tfvars, f"`env` must map string keys to string values; got {key!r}={value!r}")
70
+ out[key] = value
71
+ return out
72
+
73
+
74
+ def parse_backend_config(info: dict[str, Any], *, tfvars: pathlib.Path) -> dict[str, str]:
75
+ raw = info.get("backend_config")
76
+ if raw is None:
77
+ return {}
78
+ if not isinstance(raw, dict):
79
+ raise BannerError(tfvars, "`backend_config` must be a JSON object")
80
+ out: dict[str, str] = {}
81
+ for key, value in raw.items():
82
+ if not isinstance(key, str) or not isinstance(value, str):
83
+ raise BannerError(
84
+ tfvars,
85
+ f"`backend_config` must map string keys to string values; got {key!r}={value!r}",
86
+ )
87
+ out[key] = value
88
+ return out
89
+
90
+
91
+ def _parse_state_key(info: dict[str, Any], *, tfvars: pathlib.Path) -> str | None:
92
+ value = info.get("state_key")
93
+ if value is None:
94
+ return None
95
+ if not isinstance(value, str) or not value:
96
+ raise BannerError(tfvars, "`state_key` must be a non-empty string")
97
+ return value
98
+
99
+
100
+ def resolve_backend_config(
101
+ info: dict[str, Any],
102
+ *,
103
+ tfvars: pathlib.Path,
104
+ config: "Config",
105
+ ) -> dict[str, str]:
106
+ """Compute the final `-backend-config` k/v map for this tfvars.
107
+
108
+ Precedence (later wins):
109
+ 1. Synthesised `key = <state_key_prefix><tfvars-stem>.tfstate`
110
+ (only if `state_key_prefix` is set).
111
+ 2. `[tf_project.backend_config]` from config.
112
+ 3. `backend_config` table from the banner.
113
+ 4. `state_key` from the banner — final word on `key`.
114
+ """
115
+ merged: dict[str, str] = {}
116
+ if config.state_key_prefix:
117
+ merged["key"] = f"{config.state_key_prefix}{tfvars.stem}.tfstate"
118
+ merged.update(config.backend_config)
119
+ merged.update(parse_backend_config(info, tfvars=tfvars))
120
+ state_key = _parse_state_key(info, tfvars=tfvars)
121
+ if state_key is not None:
122
+ merged["key"] = state_key
123
+ return merged
124
+
125
+
126
+ def render_summary(
127
+ info: dict[str, Any],
128
+ *,
129
+ tfvars: pathlib.Path,
130
+ config: "Config",
131
+ ) -> dict[str, Any]:
132
+ """Validate every banner field and return a structured summary."""
133
+ project = parse_project(info, tfvars=tfvars)
134
+ return {
135
+ "tfvars": str(tfvars),
136
+ "project": project,
137
+ "source_root": str(config.terraform_dir / project),
138
+ "backend_config": resolve_backend_config(info, tfvars=tfvars, config=config),
139
+ "env": parse_env(info, tfvars=tfvars),
140
+ }
tf_project/cli.py ADDED
@@ -0,0 +1,362 @@
1
+ """Typer CLI for tf_project."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import pathlib
7
+ import sys
8
+ from typing import Annotated
9
+
10
+ import typer
11
+
12
+ from tf_project import banner, commands, self_commands, terraform
13
+ from tf_project.__version__ import __version__
14
+ from tf_project.commands import WRAPPED_SUBCOMMANDS
15
+ from tf_project.config import Config, ConfigError
16
+
17
+ SELF_SUBCOMMAND = "self"
18
+ GLOBAL_FLAGS = {"--verbose", "--dry-run"}
19
+
20
+ PASSTHROUGH_CTX = {
21
+ "allow_extra_args": True,
22
+ "ignore_unknown_options": True,
23
+ }
24
+
25
+ app = typer.Typer(
26
+ name="tf-project",
27
+ help=(
28
+ "Custom Terraform project wrapper. Unknown subcommands are forwarded "
29
+ "to `terraform` verbatim. Global flags: --verbose (echo terraform "
30
+ "argv to stderr), --dry-run (print argv and skip execution)."
31
+ ),
32
+ no_args_is_help=True,
33
+ )
34
+
35
+
36
+ def _config(ctx: typer.Context) -> Config:
37
+ if not isinstance(ctx.obj, Config):
38
+ ctx.obj = Config.discover()
39
+ return ctx.obj
40
+
41
+
42
+ def _version_callback(value: bool) -> None:
43
+ if value:
44
+ typer.echo(__version__)
45
+ raise typer.Exit()
46
+
47
+
48
+ @app.callback()
49
+ def root(
50
+ ctx: typer.Context,
51
+ version: Annotated[
52
+ bool,
53
+ typer.Option("--version", callback=_version_callback, is_eager=True, help="Show version and exit."),
54
+ ] = False,
55
+ ) -> None:
56
+ """Custom Terraform project wrapper."""
57
+
58
+
59
+ TargetsOption = Annotated[
60
+ list[str] | None,
61
+ typer.Option(
62
+ "--target",
63
+ "-t",
64
+ metavar="RESOURCE",
65
+ help="Limit operation to a specific resource address (repeatable).",
66
+ ),
67
+ ]
68
+ ReplacesOption = Annotated[
69
+ list[str] | None,
70
+ typer.Option(
71
+ "--replace",
72
+ "-r",
73
+ metavar="RESOURCE",
74
+ help="Force replacement of a specific resource address (repeatable).",
75
+ ),
76
+ ]
77
+
78
+
79
+ @app.command("init", context_settings=PASSTHROUGH_CTX, help="Initialize Terraform backend for a given tfvars file.")
80
+ def init(
81
+ ctx: typer.Context,
82
+ tfvars: Annotated[
83
+ pathlib.Path,
84
+ typer.Argument(exists=True, file_okay=True, dir_okay=False, readable=True),
85
+ ],
86
+ ) -> None:
87
+ commands.do_init(_config(ctx), tfvars=tfvars, extra=ctx.args)
88
+
89
+
90
+ @app.command("plan", context_settings=PASSTHROUGH_CTX, help="Run `terraform plan` against the initialized project.")
91
+ def plan(
92
+ ctx: typer.Context,
93
+ targets: TargetsOption = None,
94
+ replaces: ReplacesOption = None,
95
+ ) -> None:
96
+ commands.do_plan(_config(ctx), targets=targets, replaces=replaces, extra=ctx.args)
97
+
98
+
99
+ @app.command("apply", context_settings=PASSTHROUGH_CTX, help="Apply the saved tfplan.")
100
+ def apply(
101
+ ctx: typer.Context,
102
+ force: Annotated[bool, typer.Option("--force", help="Apply even if the tfvars changed since the plan.")] = False,
103
+ ) -> None:
104
+ commands.do_apply(_config(ctx), force=force, extra=ctx.args)
105
+
106
+
107
+ @app.command(
108
+ "refresh",
109
+ context_settings=PASSTHROUGH_CTX,
110
+ help="Apply directly (without a saved plan), optionally targeted.",
111
+ )
112
+ def refresh(
113
+ ctx: typer.Context,
114
+ targets: TargetsOption = None,
115
+ ) -> None:
116
+ commands.do_refresh(_config(ctx), targets=targets, extra=ctx.args)
117
+
118
+
119
+ @app.command("destroy", context_settings=PASSTHROUGH_CTX, help="Run `terraform destroy`, optionally targeted.")
120
+ def destroy(
121
+ ctx: typer.Context,
122
+ targets: TargetsOption = None,
123
+ ) -> None:
124
+ commands.do_destroy(_config(ctx), targets=targets, extra=ctx.args)
125
+
126
+
127
+ @app.command(
128
+ "fmt",
129
+ context_settings=PASSTHROUGH_CTX,
130
+ help="Recursively `terraform fmt` the terraform/ and tfvars/ trees.",
131
+ )
132
+ def fmt(ctx: typer.Context) -> None:
133
+ commands.do_fmt(_config(ctx), extra=ctx.args)
134
+
135
+
136
+ @app.command("output", context_settings=PASSTHROUGH_CTX, help="Print `terraform output -json`.")
137
+ def output(ctx: typer.Context) -> None:
138
+ commands.do_output(_config(ctx), extra=ctx.args)
139
+
140
+
141
+ @app.command("state-mv", context_settings=PASSTHROUGH_CTX, help="Move a resource in the Terraform state.")
142
+ def state_mv(
143
+ ctx: typer.Context,
144
+ source: Annotated[str, typer.Argument(help="Source resource address")],
145
+ destination: Annotated[str, typer.Argument(help="Destination resource address")],
146
+ ) -> None:
147
+ commands.do_state_mv(_config(ctx), source=source, destination=destination, extra=ctx.args)
148
+
149
+
150
+ @app.command("status", help="Print a one-line summary of the current init state.")
151
+ def status(ctx: typer.Context) -> None:
152
+ report = commands.status_report(_config(ctx))
153
+ if not report.initialized:
154
+ typer.echo("Not initialized. Run `tfp init <tfvars>` first.", err=True)
155
+ raise typer.Exit(code=1)
156
+ typer.echo(f"tfvars = {report.tfvars}")
157
+ typer.echo(f"source_root = {report.source_root}")
158
+ typer.echo(f"backend_key = {report.backend_key or '(none)'}")
159
+ typer.echo(f"env keys = {', '.join(report.env_keys) or '(none)'}")
160
+ typer.echo(f"plan = {'ready' if report.plan_ready else 'absent'}")
161
+
162
+
163
+ # ---- `self` subcommand group --------------------------------------------------
164
+
165
+ self_app = typer.Typer(name="self", help="Manage tf_project itself.", no_args_is_help=True)
166
+ app.add_typer(self_app, name="self")
167
+
168
+ self_config_app = typer.Typer(name="config", help="Inspect the active configuration.", no_args_is_help=True)
169
+ self_app.add_typer(self_config_app, name="config")
170
+
171
+ self_state_app = typer.Typer(name="state", help="Inspect or reset the saved init state.", no_args_is_help=True)
172
+ self_app.add_typer(self_state_app, name="state")
173
+
174
+ self_banner_app = typer.Typer(name="banner", help="Inspect tfvars banners.", no_args_is_help=True)
175
+ self_app.add_typer(self_banner_app, name="banner")
176
+
177
+ self_lock_app = typer.Typer(
178
+ name="lock",
179
+ help="Inspect or break the remote-state lock. Azure backend only.",
180
+ no_args_is_help=True,
181
+ )
182
+ self_app.add_typer(self_lock_app, name="lock")
183
+
184
+
185
+ @self_app.command("init", help="Bootstrap a tf_project config in the current directory.")
186
+ def self_init() -> None:
187
+ try:
188
+ path = self_commands.do_self_init(pathlib.Path.cwd())
189
+ except self_commands.SelfCommandError as exc:
190
+ typer.echo(str(exc), err=True)
191
+ raise typer.Exit(code=1) from exc
192
+ typer.echo(f"Wrote tf_project config to {path}")
193
+
194
+
195
+ @self_config_app.command("print", help="Print the effective configuration.")
196
+ def self_config_print(
197
+ ctx: typer.Context,
198
+ as_json: Annotated[bool, typer.Option("--json", help="Emit JSON instead of a human-readable listing.")] = False,
199
+ ) -> None:
200
+ typer.echo(self_commands.do_self_config_print(_config(ctx), as_json=as_json))
201
+
202
+
203
+ @self_config_app.command("path", help="Print the path of the config file in use.")
204
+ def self_config_path() -> None:
205
+ typer.echo(str(self_commands.do_self_config_path(pathlib.Path.cwd())))
206
+
207
+
208
+ @self_state_app.command("show", help="Print the saved init state as JSON.")
209
+ def self_state_show(ctx: typer.Context) -> None:
210
+ try:
211
+ typer.echo(self_commands.do_self_state_show(_config(ctx)))
212
+ except self_commands.SelfCommandError as exc:
213
+ typer.echo(str(exc), err=True)
214
+ raise typer.Exit(code=1) from exc
215
+
216
+
217
+ @self_state_app.command("clear", help="Delete the saved init state file.")
218
+ def self_state_clear(ctx: typer.Context) -> None:
219
+ cfg = _config(ctx)
220
+ removed = self_commands.do_self_state_clear(cfg)
221
+ if removed:
222
+ typer.echo(f"Removed {cfg.state_file}")
223
+ else:
224
+ typer.echo(f"No state file at {cfg.state_file} — nothing to do.")
225
+
226
+
227
+ @self_app.command("doctor", help="Run environment sanity checks.")
228
+ def self_doctor(ctx: typer.Context) -> None:
229
+ checks = self_commands.do_self_doctor(_config(ctx))
230
+ width = max(len(c.name) for c in checks)
231
+ failures = 0
232
+ for check in checks:
233
+ status = "OK " if check.ok else "FAIL"
234
+ typer.echo(f"[{status}] {check.name.ljust(width)} {check.detail}")
235
+ if not check.ok:
236
+ failures += 1
237
+ if failures:
238
+ raise typer.Exit(code=1)
239
+
240
+
241
+ @self_banner_app.command("check", help="Parse and validate a tfvars banner without running terraform.")
242
+ def self_banner_check(
243
+ ctx: typer.Context,
244
+ tfvars: Annotated[
245
+ pathlib.Path,
246
+ typer.Argument(exists=True, file_okay=True, dir_okay=False, readable=True),
247
+ ],
248
+ ) -> None:
249
+ summary = self_commands.do_self_banner_check(_config(ctx), tfvars=tfvars)
250
+ typer.echo(json.dumps(summary, indent=2, sort_keys=True))
251
+
252
+
253
+ @self_lock_app.command("status", help="Show the Azure blob-lease state of the remote tfstate.")
254
+ def self_lock_status(ctx: typer.Context) -> None:
255
+ try:
256
+ status = self_commands.do_self_lock_status(_config(ctx))
257
+ except self_commands.SelfCommandError as exc:
258
+ typer.echo(str(exc), err=True)
259
+ raise typer.Exit(code=1) from exc
260
+ typer.echo(f"locked = {status.locked}")
261
+ typer.echo(f"lease_state = {status.lease_state}")
262
+ typer.echo(f"lease_duration = {status.lease_duration or '(n/a)'}")
263
+ if status.lock_id:
264
+ typer.echo(f"lock_id = {status.lock_id}")
265
+ typer.echo(f"lock_who = {status.lock_who or '(unknown)'}")
266
+ typer.echo(f"lock_operation = {status.lock_operation or '(unknown)'}")
267
+ typer.echo(f"lock_created = {status.lock_created or '(unknown)'}")
268
+ typer.echo(f"\nTo release via terraform: tfp force-unlock {status.lock_id}")
269
+ if status.locked:
270
+ raise typer.Exit(code=2)
271
+
272
+
273
+ @self_lock_app.command(
274
+ "break",
275
+ help="Break the Azure blob lease on the remote tfstate. Use after a hard kill that left the state locked.",
276
+ )
277
+ def self_lock_break(
278
+ ctx: typer.Context,
279
+ yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip the confirmation prompt.")] = False,
280
+ ) -> None:
281
+ if not yes:
282
+ typer.confirm(
283
+ "Break the remote-state lease? This may corrupt state if terraform is still running.",
284
+ abort=True,
285
+ )
286
+ try:
287
+ self_commands.do_self_lock_break(_config(ctx))
288
+ except self_commands.SelfCommandError as exc:
289
+ typer.echo(str(exc), err=True)
290
+ raise typer.Exit(code=1) from exc
291
+ typer.echo("Lease broken.")
292
+
293
+
294
+ # ---- Top-level dispatcher -----------------------------------------------------
295
+
296
+
297
+ def _strip_global_flags(argv: list[str]) -> tuple[list[str], bool, bool]:
298
+ """Pull `--verbose` / `--dry-run` out of argv, stopping at the first `--`."""
299
+ out: list[str] = []
300
+ verbose = False
301
+ dry_run = False
302
+ seen_dash_dash = False
303
+ for arg in argv:
304
+ if arg == "--":
305
+ seen_dash_dash = True
306
+ out.append(arg)
307
+ continue
308
+ if not seen_dash_dash and arg == "--verbose":
309
+ verbose = True
310
+ continue
311
+ if not seen_dash_dash and arg == "--dry-run":
312
+ dry_run = True
313
+ continue
314
+ out.append(arg)
315
+ return out, verbose, dry_run
316
+
317
+
318
+ def _split_passthrough(argv: list[str]) -> tuple[bool, list[str]]:
319
+ """Decide whether to passthrough to `terraform` and, if so, what to forward."""
320
+ for i, arg in enumerate(argv):
321
+ if arg.startswith("-"):
322
+ continue
323
+ if arg in WRAPPED_SUBCOMMANDS or arg == SELF_SUBCOMMAND:
324
+ return (False, [])
325
+ return (True, argv[i:])
326
+ return (False, [])
327
+
328
+
329
+ def main() -> None:
330
+ """Entry point: handle global flags, route, and translate errors to exit codes."""
331
+ args, verbose, dry_run = _strip_global_flags(sys.argv[1:])
332
+ terraform.set_runtime_options(dry_run=dry_run, verbose=verbose)
333
+
334
+ try:
335
+ is_passthrough, forwarded = _split_passthrough(args)
336
+ if is_passthrough:
337
+ cfg = Config.discover()
338
+ commands.do_passthrough(cfg, forwarded)
339
+ return
340
+ sys.argv = [sys.argv[0], *args]
341
+ app()
342
+ except terraform.TerraformExit as exc:
343
+ sys.exit(exc.code)
344
+ except banner.BannerError as exc:
345
+ typer.echo(str(exc), err=True)
346
+ sys.exit(1)
347
+ except banner.ProjectInfoNotFoundError as exc:
348
+ typer.echo(str(exc), err=True)
349
+ sys.exit(1)
350
+ except commands.StateNotInitializedError as exc:
351
+ typer.echo(str(exc), err=True)
352
+ sys.exit(1)
353
+ except commands.StaleTfplanError as exc:
354
+ typer.echo(str(exc), err=True)
355
+ sys.exit(1)
356
+ except ConfigError as exc:
357
+ typer.echo(f"config error: {exc}", err=True)
358
+ sys.exit(1)
359
+
360
+
361
+ if __name__ == "__main__":
362
+ main()