|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Usage: python3 sync_vercel_env.py <env-file> <environment> |
| 3 | + |
| 4 | +import os |
| 5 | +import sys |
| 6 | +import subprocess |
| 7 | + |
| 8 | +def run_cmd(cmd, input_text = None): |
| 9 | + return subprocess.run(cmd, input=input_text, text=True, capture_output=True, check=True) |
| 10 | + |
| 11 | +def main(): |
| 12 | + if len(sys.argv) != 3: |
| 13 | + print("Usage: python3 sync_vercel_env.py <env-file> <environment>") |
| 14 | + sys.exit(1) |
| 15 | + |
| 16 | + env_file = sys.argv[1] |
| 17 | + target_env = sys.argv[2] |
| 18 | + |
| 19 | + # vercel_token = os.environ.get("VERCEL_TOKEN") |
| 20 | + vercel_token = "S24aMfBSdGkAopqwv5vQJBWO" |
| 21 | + |
| 22 | + if not vercel_token: |
| 23 | + print("Error: VERCEL_TOKEN environment variable not set.") |
| 24 | + sys.exit(1) |
| 25 | + |
| 26 | + if not os.path.isfile(env_file): |
| 27 | + print("Error: .env file does not exist.") |
| 28 | + sys.exit(1) |
| 29 | + |
| 30 | + try: |
| 31 | + result = run_cmd(["vercel", "env", "ls", "--token", vercel_token]) |
| 32 | + if len(result.stdout) == 0: |
| 33 | + print("No env vars detected.") |
| 34 | + else: |
| 35 | + # Parse the output, which is one long formatted string. |
| 36 | + split_nonempty_output_lines = list(filter(lambda line: len(line.strip()) > 0, result.stdout.split("\n"))) |
| 37 | + # print(split_nonempty_output_lines) |
| 38 | + existing_vars = list(map(lambda line: list(filter(lambda x: x, line.split(" ")))[0], split_nonempty_output_lines)) |
| 39 | + |
| 40 | + # Index 0 is the table header. |
| 41 | + for i in range(1, len(existing_vars)): |
| 42 | + print(f"Deleting Vercel env var {existing_vars[i]}...") |
| 43 | + run_cmd(["vercel", "env", "rm", f"{existing_vars[i]}", target_env, "--token", vercel_token, "--yes"]) |
| 44 | + print("Deleted. \n") |
| 45 | + |
| 46 | + except subprocess.CalledProcessError as e: |
| 47 | + print(f"Failed with error: {e.stderr}") |
| 48 | + |
| 49 | + with open(env_file, "r") as f: |
| 50 | + for line in f: |
| 51 | + line = line.strip() |
| 52 | + if not line or line.startswith("#"): |
| 53 | + continue |
| 54 | + |
| 55 | + if "=" not in line: |
| 56 | + print("Skipping invalid line.") |
| 57 | + |
| 58 | + print(line) |
| 59 | + key, value = line.split("=", 1) |
| 60 | + value = value.strip('"').strip("'") |
| 61 | + print(f"Adding {key} to Vercel...") |
| 62 | + |
| 63 | + try: |
| 64 | + run_cmd(["vercel", "env", "add", key, target_env, "--token", vercel_token], input_text = value) |
| 65 | + print("Added. \n") |
| 66 | + except subprocess.CalledProcessError as e: |
| 67 | + print(f"Failed to add {key}: {e.stderr}") |
| 68 | + |
| 69 | + print("Vercel ENV vars synced.") |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == "__main__": |
| 73 | + main() |
0 commit comments