The user is asking for a Python script to automate web application deployment, but it's a broad request. I’ll need to clarify details about the environment and stack they're using, like whether it's Docker, cloud, or bare metal. Since they haven’t specified much, I should prepare a generic, yet practical script. I think a flexible deploy.py that reads configs, runs commands through subprocess or paramiko, and manages virtualenv would be good. I'll include a concise code listing with a minimal explanation.Detailing deployment script requirements
I realize I might need to include dependencies like fabric or paramiko, or even use built-in libraries such as subprocess to run SSH commands. I should provide a script that follows a pattern for a web application (like Flask or Node). The script will handle tasks such as pulling code from Git, building dependencies, running tests, and deploying remotely. It’ll accept an environment argument for staging or production, use a config YAML for server settings, and utilize subprocess and paramiko for execution and uploads. If paramiko is included, the user will need to install it.Providing deployment script guidelines
I need to be careful not to create commands that could cause damage, like using rm -rf /. The deployment script can simply work within a designated remote directory. I’ll also mention security considerations, like using SSH keys instead of storing passwords.
For the script, I plan to use argparse to handle parameters like environment names and options like --skip-tests or --rollback. I could embed the config directly in the script for simplicity, but a separate deploy_config.yml file could make it easier to customize.
I think the user wants actual code, so I'll outline functionalities, provide the deploy.py script with about 200 lines and comments, and include a sample configuration. I'll keep everything concise!Defining script flow and steps
I need to keep the script concise but useful. The plan includes accepting options for --env (staging or production), --branch (defaulting to main), and --no-tests.
The steps will be:
Pull the latest code from Git.
Run tests using pytest, if they're not disabled.
Create a timestamped tar.gz of the app directory, excluding unnecessary files.
Connect to the remote server using Paramiko with details from the config.
Upload the tar file to the remote releases/ directory.
Extract the tarball, install dependencies, run migrations, update the current symlink, and restart the systemd service.
Optionally, keep the last N releases and remove older ones. I'll assume the remote server runs on Linux with systemd for the service management.Outlining deployment script design
I’m working on a deployment script and need an organized approach. First, I'll define a CONFIG dictionary to store configurations for different environments, like staging, including details such as host, user, SSH key, and directory paths. I'll ensure to use Paramiko for SSH connections and tarfile for creating tarballs.
The flow involves parsing arguments for environment, branch, and options. I’ll implement steps like pulling the latest code, running tests (if not skipped), connecting to remote servers, and executing commands for setup and migration. The script will handle remote command execution efficiently. I’ll define optional migration and build commands in the configuration and ensure to keep the script easy to customize while still being robust!Finalizing deployment script design
I’m working on a deployment script and need to ensure we handle everything safely and efficiently. I’ll be using paramiko for SSH operations and shlex to avoid command injection issues. I plan to include installation instructions for paramiko, but keep it minimal.
The script will allow for remote commands to be executed within the appropriate directory, while also implementing checks for return codes and user configurations for SSH connections and service names. I’ll provide a way for users to customize their own configs with placeholder values and ensure they can run local tests. Finally, I’ll clearly define command structures to avoid failures and maintain security throughout the process.Finalizing deployment script design
I’m treating remote paths as plain strings with slashes. For example, I’ll configure venv_bin_pip using the virtual environment directory provided in the config. Using shlex.quote ensures safe quoting for branch names, but I need to be cautious about double-quoting when forming commands. I'll also print commands for clarity during execution. My final response will include concise steps: install dependencies, provide the script, and explain how to adapt the config and run it, focusing on clarity without unnecessary disclaimers. Below is a self-contained example of a Python deployment script that:
Runs local tests
SSHes into a remote server
Updates the app from Git
Installs dependencies into a virtualenv
Runs optional build/migration commands
Restarts the app’s systemd service
You can adapt the config section for your own servers and stack.
1. Install dependency
bash
pip install paramiko
2. deploy.py
python
3. How to use
Edit the CONFIG dict to match:
Remote host, user, SSH key
remote_dir (where your app’s git repo lives)
venv_dir (virtualenv on remote)
service_name (systemd unit)
Optional migrate_cmd / build_cmd
Make the script executable (optional):
bash
chmod +x deploy.py
Deploy:
bash
# Deploy "main" branch to staging, running tests first
./deploy.py --env staging
# Deploy feature branch without running tests
./deploy.py --env staging --branch feature/login --skip-tests
You can extend this by adding rollback logic, packaging artifacts instead of git pull, or integrating it into a CI/CD pipeline.
#!/usr/bin/env python3
"""
Simple deployment script for web applications.
Features:
- Run local tests.
- SSH into remote server.
- git fetch / pull the specified branch.
- Install dependencies into a virtualenv.
- Run optional build / migration commands.
- Restart a systemd service.
Edit the CONFIG dictionary below to match your environments.
"""
import argparse
import os
import sys
import shlex
import subprocess
import paramiko
# ---------------------------------------------------------------------------
# Configuration: EDIT THIS SECTION
# ---------------------------------------------------------------------------
CONFIG = {
"staging": {
"host": "staging.example.com",
"port": 22,
"user": "deploy",
"ssh_key": "~/.ssh/id_rsa",
# Directory on remote server containing the git repo
"remote_dir": "/var/www/myapp",
# Directory of the Python virtualenv on the remote server
"venv_dir": "/var/www/myapp/venv",
# systemd service name for your app
"service_name": "myapp",
# Optional commands run from remote_dir (can be None)
# Examples:
# "venv/bin/python manage.py migrate"
# "venv/bin/flask db upgrade"
"migrate_cmd": None,
"build_cmd": None,
# Whether to use sudo for systemctl restart
"use_sudo": True,
},
# Example production config (uncomment and edit):
# "production": {
# "host": "prod.example.com",
# "port": 22,
# "user": "deploy",
# "ssh_key": "~/.ssh/id_rsa",
# "remote_dir": "/var/www/myapp",
# "venv_dir": "/var/www/myapp/venv",
# "service_name": "myapp",
# "migrate_cmd": "venv/bin/python manage.py migrate",
# "build_cmd": "venv/bin/python manage.py collectstatic --noinput",
# "use_sudo": True,
# },
}
# Default local test command (edit if needed)
DEFAULT_TEST_CMD = "pytest"
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def run_local_tests(cmd: str) -> None:
"""Run local test command before deploying."""
print(f"[LOCAL] Running tests: {cmd}")
try:
subprocess.run(cmd, shell=True, check=True)
except subprocess.CalledProcessError as exc:
print(f"[LOCAL] Tests failed with exit code {exc.returncode}. Aborting.")
sys.exit(exc.returncode)
print("[LOCAL] Tests passed.")
def connect_ssh(env_cfg: dict) -> paramiko.SSHClient:
"""Create and return an SSH client connected to the remote server."""
host = env_cfg["host"]
port = env_cfg.get("port", 22)
user = env_cfg["user"]
key_path = env_cfg.get("ssh_key")
if key_path:
key_path = os.path.expanduser(key_path)
print(f"[SSH] Connecting to {user}@{host}:{port} ...")
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
hostname=host,
port=port,
username=user,
key_filename=key_path,
look_for_keys=True,
timeout=15,
)
print("[SSH] Connected.")
return ssh
def run_remote(
ssh: paramiko.SSHClient,
cmd: str,
cwd: str | None = None,
use_sudo: bool = False,
) -> None:
"""
Run a command on the remote host.
:param cmd: Command to run (NOT executed through a shell locally).
:param cwd: If provided, run `cd cwd && cmd`.
:param use_sudo: If True, prefix with `sudo`.
"""
full_cmd = cmd
if cwd:
full_cmd = f"cd {shlex.quote(cwd)} && {cmd}"
if use_sudo:
full_cmd = f"sudo {full_cmd}"
print(f"[REMOTE] $ {full_cmd}")
stdin, stdout, stderr = ssh.exec_command(full_cmd)
# Stream output
for line in stdout:
print("[REMOTE][OUT] " + line, end="")
for line in stderr:
print("[REMOTE][ERR] " + line, end="")
exit_status = stdout.channel.recv_exit_status()
if exit_status != 0:
print(f"[REMOTE] Command failed with exit code {exit_status}. Aborting.")
ssh.close()
sys.exit(exit_status)
def deploy(env_name: str, branch: str) -> None:
"""Main deployment logic."""
if env_name not in CONFIG:
print(f"Unknown environment: {env_name}")
print(f"Available: {', '.join(CONFIG.keys())}")
sys.exit(1)
env_cfg = CONFIG[env_name]
remote_dir = env_cfg["remote_dir"]
venv_dir = env_cfg["venv_dir"]
service_name = env_cfg["service_name"]
migrate_cmd = env_cfg.get("migrate_cmd")
build_cmd = env_cfg.get("build_cmd")
use_sudo = env_cfg.get("use_sudo", True)
# Prepare some paths / arguments
branch_quoted = shlex.quote(branch)
pip_path = f"{venv_dir.rstrip('/')}/bin/pip"
ssh = connect_ssh(env_cfg)
try:
# 1. Update code from git
run_remote(ssh, "git fetch origin", cwd=remote_dir)
run_remote(ssh, f"git checkout {branch_quoted}", cwd=remote_dir)
run_remote(ssh, f"git pull origin {branch_quoted}", cwd=remote_dir)
# 2. Install dependencies into virtualenv
run_remote(
ssh,
f"{shlex.quote(pip_path)} install -r requirements.txt",
cwd=remote_dir,
)
# 3. Optional build step (e.g. collectstatic, webpack, etc.)
if build_cmd:
run_remote(ssh, build_cmd, cwd=remote_dir)
# 4. Optional migrations (Django, Alembic, etc.)
if migrate_cmd:
run_remote(ssh, migrate_cmd, cwd=remote_dir)
# 5. Restart application service
run_remote(
ssh,
f"systemctl restart {shlex.quote(service_name)}",
use_sudo=use_sudo,
)
print(f"[DONE] Deployment to '{env_name}' complete.")
finally:
ssh.close()
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main() -> None:
parser = argparse.ArgumentParser(
description="Automate deployment of a web application."
)
parser.add_argument(
"--env",
required=True,
help=f"Target environment ({', '.join(CONFIG.keys())})",
)
parser.add_argument(
"--branch",
default="main",
help="Git branch to deploy (default: main)",
)
parser.add_argument(
"--skip-tests",
action="store_true",
help="Skip running local tests before deployment.",
)
parser.add_argument(
"--test-cmd",
default=DEFAULT_TEST_CMD,
help=f"Local test command to run (default: {DEFAULT_TEST_CMD})",
)
args = parser.parse_args()
if not args.skip_tests:
run_local_tests(args.test_cmd)
deploy(args.env, args.branch)
if __name__ == "__main__":
main()