# tenant/commands/init.py import os from tenant.utils.common import get_secure_password def add_subparser(subparsers): init_parser = subparsers.add_parser("init", help="Initialize a new tenant") default_tenant_name = os.getenv("TENANT_NAME", None) init_parser.add_argument( "tenant_name", help="Name of the tenant", default=default_tenant_name, nargs="?" ) init_parser.add_argument( "--target", default=".", help="Target directory (default: current directory)" ) def execute(args): # If tenant_name is not provided and TENANT_NAME is not set, prompt the user if args.tenant_name is None and os.getenv("TENANT_NAME") is None: tenant_name = input("Please enter the tenant name: ") # Ask the user to confirm the tenant name if the environment variable is set if os.getenv("TENANT_NAME") and args.tenant_name is not None: user_confirmation = input( f"Use '{os.getenv('TENANT_NAME')}' as the tenant name? (yes/no): " ).lower() if user_confirmation in ("yes", "y"): tenant_name = os.getenv("TENANT_NAME") target_directory = args.target tenant_directory = os.path.join(target_directory, tenant_name) # Check if the tenant directory already exists if os.path.exists(tenant_directory): print(f"Error: Tenant directory '{tenant_directory}' already exists.") return # Prompt the user for the GitSync password securely git_sync_password = get_secure_password( prompt="Please insert known password for GitSync: " ) terraform_directory = os.path.join(tenant_directory, "terraform") kubernetes_directory = os.path.join(tenant_directory, "kubernetes") certificates_directory = os.path.join(tenant_directory, "certificates") os.makedirs(terraform_directory) os.makedirs(kubernetes_directory) os.makedirs(certificates_directory) # Create symbolic links for *.tf files source_tf_dir = os.path.join(target_directory, "terraform") target_tf_dir = os.path.join(tenant_directory, "terraform") for filename in os.listdir(source_tf_dir): if filename.endswith(".tf"): source_path = os.path.join(source_tf_dir, filename) target_path = os.path.join(target_tf_dir, filename) # Ensure the source path is correct before creating the symbolic link if os.path.exists(source_path): relative_path = os.path.relpath(source_path, target_tf_dir) os.symlink(relative_path, target_path) else: print( f"Warning: Source file '{filename}' not found in '{source_tf_dir}'." ) print( f"Tenant '{tenant_name}' initialized in '{tenant_directory}' with GitSync password provided." )