|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Generate ~/.dbt/profiles.yml from a Jinja2 template and an optional secrets JSON.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import base64 |
| 7 | +import binascii |
| 8 | +import json |
| 9 | +import os |
| 10 | +from pathlib import Path |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +import click |
| 14 | +import yaml |
| 15 | +from jinja2 import BaseLoader, Environment, StrictUndefined, Undefined |
| 16 | + |
| 17 | + |
| 18 | +class _NullUndefined(Undefined): |
| 19 | + """Render missing variables as empty strings so docker-only runs don't crash.""" |
| 20 | + |
| 21 | + def __str__(self) -> str: |
| 22 | + return "" |
| 23 | + |
| 24 | + def __iter__(self): |
| 25 | + return iter([]) |
| 26 | + |
| 27 | + def __bool__(self) -> bool: |
| 28 | + return False |
| 29 | + |
| 30 | + |
| 31 | +def _yaml_inline(value: Any) -> str: |
| 32 | + """Dump *value* as a compact inline YAML scalar / mapping.""" |
| 33 | + if isinstance(value, Undefined): |
| 34 | + return "{}" |
| 35 | + return yaml.dump(value, default_flow_style=True).strip() |
| 36 | + |
| 37 | + |
| 38 | +@click.command() |
| 39 | +@click.option( |
| 40 | + "--template", |
| 41 | + required=True, |
| 42 | + type=click.Path(exists=True, dir_okay=False, path_type=Path), |
| 43 | + help="Path to the Jinja2 profiles template (e.g. profiles.yml.j2).", |
| 44 | +) |
| 45 | +@click.option( |
| 46 | + "--output", |
| 47 | + required=True, |
| 48 | + type=click.Path(dir_okay=False, path_type=Path), |
| 49 | + help="Destination path for the rendered profiles.yml.", |
| 50 | +) |
| 51 | +@click.option( |
| 52 | + "--schema-name", |
| 53 | + required=True, |
| 54 | + help="Base schema name (e.g. dbt_pkg_<ref> or py_<ref>).", |
| 55 | +) |
| 56 | +@click.option( |
| 57 | + "--secrets-json-env", |
| 58 | + default="CI_WAREHOUSE_SECRETS", |
| 59 | + show_default=True, |
| 60 | + help="Name of the env-var holding the base64-encoded JSON secrets blob.", |
| 61 | +) |
| 62 | +def main( |
| 63 | + template: Path, |
| 64 | + output: Path, |
| 65 | + schema_name: str, |
| 66 | + secrets_json_env: str, |
| 67 | +) -> None: |
| 68 | + """Render a Jinja2 profiles template into a dbt profiles.yml file. |
| 69 | +
|
| 70 | + Resolution order: |
| 71 | + 1. If the env-var named by ``--secrets-json-env`` is set, decode it and |
| 72 | + use its key/value pairs (plus *schema_name*) as template variables. |
| 73 | + 2. Otherwise render the template with only *schema_name* populated (all |
| 74 | + other variables resolve to empty strings — suitable for docker-only |
| 75 | + targets on fork PRs). |
| 76 | + """ |
| 77 | + output.parent.mkdir(parents=True, exist_ok=True) |
| 78 | + |
| 79 | + secrets_b64 = os.environ.get(secrets_json_env, "").strip() |
| 80 | + |
| 81 | + # ── Build template context ────────────────────────────────────────── |
| 82 | + context: dict[str, object] = {"schema_name": schema_name} |
| 83 | + |
| 84 | + if secrets_b64: |
| 85 | + try: |
| 86 | + decoded: dict = json.loads(base64.b64decode(secrets_b64)) |
| 87 | + except (binascii.Error, json.JSONDecodeError) as e: |
| 88 | + raise click.ClickException( |
| 89 | + f"Failed to decode ${secrets_json_env}: {e}" |
| 90 | + ) from e |
| 91 | + if not isinstance(decoded, dict): |
| 92 | + raise click.ClickException( |
| 93 | + f"Expected JSON object for ${secrets_json_env}, " |
| 94 | + f"got {type(decoded).__name__}" |
| 95 | + ) |
| 96 | + for key, value in decoded.items(): |
| 97 | + context[key.lower()] = value |
| 98 | + click.echo( |
| 99 | + f"Loaded {len(decoded)} secret(s) from ${secrets_json_env}.", |
| 100 | + err=True, |
| 101 | + ) |
| 102 | + else: |
| 103 | + click.echo( |
| 104 | + "No secrets found — rendering template for docker-only targets.", |
| 105 | + err=True, |
| 106 | + ) |
| 107 | + |
| 108 | + # ── Render ────────────────────────────────────────────────────────── |
| 109 | + # When secrets are loaded, use StrictUndefined so typos in secret keys |
| 110 | + # fail fast. For docker-only runs (no secrets) use _NullUndefined so |
| 111 | + # cloud placeholders silently resolve to empty strings. |
| 112 | + undefined_cls = StrictUndefined if secrets_b64 else _NullUndefined |
| 113 | + env = Environment( |
| 114 | + loader=BaseLoader(), |
| 115 | + undefined=undefined_cls, |
| 116 | + keep_trailing_newline=True, |
| 117 | + ) |
| 118 | + env.filters["toyaml"] = _yaml_inline |
| 119 | + tmpl = env.from_string(template.read_text()) |
| 120 | + rendered = tmpl.render(**context) |
| 121 | + output.write_text(rendered) |
| 122 | + click.echo(f"Wrote {output}", err=True) |
| 123 | + |
| 124 | + |
| 125 | +if __name__ == "__main__": |
| 126 | + main() |
0 commit comments