CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-fabric

A Python library and command-line tool for streamlining SSH usage in application deployment and systems administration.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

context-management.mddocs/

Context Management

Temporary state modification tools for managing directories, environment settings, output control, and SSH tunneling. Context managers ensure clean state restoration after operations complete and enable sophisticated nested operations with predictable behavior.

Capabilities

Directory Management

Context managers for temporarily changing working directories on both local and remote systems.

def cd(path):
    """
    Context manager for remote directory changes.
    
    Args:
        path (str): Remote directory path to change to
        
    Context: Changes remote working directory temporarily
    """

def lcd(path):
    """
    Context manager for local directory changes.
    
    Args:
        path (str): Local directory path to change to
        
    Context: Changes local working directory temporarily
    """

Usage Examples:

from fabric.api import cd, lcd, run, local

# Remote directory context
with cd('/var/www/myapp'):
    run('git pull origin master')
    run('npm install')
    run('npm run build')
    
# Nested directory contexts
with cd('/opt'):
    run('ls -la')
    with cd('applications'):
        run('pwd')  # Shows /opt/applications
    run('pwd')  # Back to /opt

# Local directory context
with lcd('local-project'):
    local('npm run build')
    local('tar czf ../build.tar.gz dist/')

# Combine local and remote operations
with lcd('build'):
    local('webpack --mode production')
    with cd('/var/www'):
        run('rm -rf old-build')
        # Upload happens from local 'build' directory context

Environment Settings

Comprehensive context manager for temporarily modifying Fabric's global environment and execution settings.

def settings(*args, **kwargs):
    """
    Context manager for temporary environment variable overrides and nested context managers.
    
    Args:
        *args: Other context managers to nest
        **kwargs: Environment variables to temporarily override
        
    Context: Temporarily modifies env settings and restores on exit
    """

Usage Examples:

from fabric.api import settings, run, sudo, hide, env

# Temporarily change execution settings
with settings(warn_only=True):
    result = run('command-that-might-fail')
    if result.failed:
        print("Command failed, but continuing...")

# Override connection settings
with settings(user='deploy', key_filename='/path/to/deploy_key'):
    run('git pull')
    sudo('systemctl restart nginx')

# Combine multiple settings
with settings(warn_only=True, parallel=True, pool_size=10):
    run('apt-get update')

# Nest context managers within settings
with settings(hide('stdout', 'stderr'), warn_only=True):
    result = run('silent-command')

# Temporarily modify complex settings
original_hosts = env.hosts
with settings(hosts=['server1.com', 'server2.com']):
    run('uptime')
# env.hosts automatically restored to original_hosts

Output Control

Context managers for controlling what output is displayed or hidden during command execution.

def hide(*groups):
    """
    Context manager to hide output groups.
    
    Args:
        *groups: Output groups to hide ('running', 'stdout', 'stderr', 'warnings', 'everything')
        
    Context: Suppresses specified output types
    """

def show(*groups):
    """
    Context manager to show output groups.
    
    Args:
        *groups: Output groups to show ('running', 'stdout', 'stderr', 'warnings', 'everything')
        
    Context: Enables specified output types
    """

def quiet():
    """
    Context manager equivalent to hide('everything') and settings(warn_only=True).
    
    Context: Suppresses all output and continues on failures
    """

Usage Examples:

from fabric.api import hide, show, quiet, run, local

# Hide specific output types
with hide('stdout'):
    result = run('long-command-with-verbose-output')
    # Only see running/stderr output, capture stdout in result

# Hide everything except errors
with hide('running', 'stdout'):
    run('noisy-command')

# Show only specific output
with show('stderr'):
    run('command-with-important-errors')

# Completely quiet execution
with quiet():
    result = run('risky-command')
    if result.failed:
        print(f"Command failed silently: {result.return_code}")

# Nested output control
with hide('running'):
    print("Starting deployment...")
    with quiet():
        run('backup-database')  # Silent backup
    run('deploy-application')  # Show stdout but not running lines

Environment Variables

Context manager for temporarily setting shell environment variables that will be available to executed commands.

def shell_env(**kw):
    """
    Context manager to set shell environment variables.
    
    Args:
        **kw: Environment variables to set (key=value pairs)
        
    Context: Sets environment variables for command execution
    """

Usage Examples:

from fabric.api import shell_env, run, local

# Set environment variables for commands
with shell_env(NODE_ENV='production', PORT='3000'):
    run('npm start')

# Database connection settings
with shell_env(DB_HOST='localhost', DB_USER='myapp'):
    run('python manage.py migrate')

# Temporarily override PATH
with shell_env(PATH='/usr/local/bin:/usr/bin:/bin'):
    run('which python')

# Multiple environment contexts
with shell_env(RAILS_ENV='production'):
    with shell_env(SECRET_KEY_BASE='abc123'):
        run('rails server')

# Local environment variables
with shell_env(BUILD_ENV='staging'):
    local('webpack --mode development')

Path Modification

Context manager for temporarily modifying the PATH environment variable.

def path(path, behavior='append'):
    """
    Context manager to modify PATH environment variable.
    
    Args:
        path (str): Path to add to PATH variable
        behavior (str): How to modify PATH ('append', 'prepend', 'replace')
        
    Context: Temporarily modifies PATH environment variable
    """

Usage Examples:

from fabric.api import path, run

# Add to end of PATH
with path('/usr/local/bin'):
    run('which node')  # Will find node in /usr/local/bin

# Add to beginning of PATH (takes precedence)
with path('/opt/python3.9/bin', behavior='prepend'):
    run('python --version')  # Uses /opt/python3.9/bin/python

# Temporarily replace PATH entirely
with path('/bin:/usr/bin', behavior='replace'):
    run('echo $PATH')  # Only shows /bin:/usr/bin

# Nested path modifications
with path('/usr/local/bin'):
    with path('/opt/custom/bin', behavior='prepend'):
        run('which custom-tool')  # Finds in /opt/custom/bin first

Command Prefixing

Context manager for prefixing all commands with a specific command sequence.

def prefix(command):
    """
    Context manager to prefix commands with given command + '&&'.
    
    Args:
        command (str): Command to prefix before all subsequent commands
        
    Context: Prefixes all commands with specified command
    """

Usage Examples:

from fabric.api import prefix, run

# Activate virtual environment for all commands
with prefix('source venv/bin/activate'):
    run('python --version')  # Runs: source venv/bin/activate && python --version
    run('pip install -r requirements.txt')

# Set up environment before commands
with prefix('export NODE_ENV=production'):
    run('npm start')

# Chain multiple prefixes
with prefix('cd /var/www/myapp'):
    with prefix('source .env'):
        run('python manage.py collectstatic')
        run('python manage.py migrate')

# Database commands with connection setup
with prefix('export PGPASSWORD=secret'):
    run('psql -U myuser -d mydb -c "SELECT version();"')

SSH Tunneling

Context manager for creating SSH reverse tunnels during command execution.

def remote_tunnel(remote_port, local_port=None, local_host="localhost", remote_bind_address="127.0.0.1"):
    """
    Context manager for SSH reverse tunnels.
    
    Args:
        remote_port (int): Port on remote host to tunnel
        local_port (int): Local port to tunnel to (default: same as remote_port)
        local_host (str): Local host to tunnel to (default: localhost)
        remote_bind_address (str): Remote address to bind to (default: 127.0.0.1)
        
    Context: Creates SSH reverse tunnel for duration of context
    """

Usage Examples:

from fabric.api import remote_tunnel, run, local

# Tunnel remote database to local port
with remote_tunnel(5432):  # Remote PostgreSQL port 5432 -> local 5432
    local('pg_dump -h localhost -p 5432 -U user remote_db > backup.sql')

# Tunnel to different local port
with remote_tunnel(3306, 13306):  # Remote MySQL 3306 -> local 13306
    local('mysql -h localhost -P 13306 -u user -p remote_db < migration.sql')

# Access remote web service locally
with remote_tunnel(8080, 8080):
    local('curl http://localhost:8080/api/status')

# Multiple tunnels
with remote_tunnel(5432):  # Database
    with remote_tunnel(6379, 16379):  # Redis
        local('python manage.py migrate')  # Uses tunneled database
        local('redis-cli -p 16379 ping')  # Uses tunneled Redis

Convenience Shortcuts

Pre-configured context managers for common use cases.

def warn_only():
    """
    Context manager equivalent to settings(warn_only=True).
    
    Context: Continue execution on command failures
    """

Usage Examples:

from fabric.api import warn_only, quiet, settings, run

# Continue on failures without stopping
with warn_only():
    run('service that-might-not-exist stop')
    run('rm file-that-might-not-exist')

# Common pattern combinations
with settings(hide('warnings'), warn_only=True):
    result = run('optional-cleanup-command')

# Equivalent to quiet() but more explicit
with settings(hide('everything'), warn_only=True):
    run('background-task')

Nesting and Composition

Context managers can be freely nested and combined:

from fabric.api import *

# Complex nested context
with settings(hosts=['web1.com', 'web2.com']):
    with cd('/var/www/myapp'):
        with shell_env(RAILS_ENV='production'):
            with hide('stdout'):
                with warn_only():
                    run('bundle exec rake assets:precompile')

# Equivalent using settings composition
with settings(
    hosts=['web1.com', 'web2.com'],
    cd('/var/www/myapp'),
    shell_env(RAILS_ENV='production'),
    hide('stdout'),
    warn_only=True
):
    run('bundle exec rake assets:precompile')

Install with Tessl CLI

npx tessl i tessl/pypi-fabric

docs

context-management.md

core-operations.md

decorators-tasks.md

file-operations.md

index.md

tile.json