core

Create servers on Hetzner or Lightsail, write their cloud-init files, and deploy to them over SSH.

Multipass for local testing

Multipass runs Ubuntu virtual machines (VMs) on your own computer. Use a VM to test a cloud-init file and a deploy before you create a real server. A VM costs nothing and takes a few minutes to start. Install Multipass and put the multipass command on your PATH.

Multipass wraps the multipass command. launch starts a VM. It takes an optional cloud-init file from multi_init or vps_init, and optional host folders to mount in the VM as mounts={host_path: vm_path}. vms lists the VM names. ip returns the address of a VM. exec_ runs a command inside a VM. rm deletes a VM. Any other multipass subcommand works as a method. For example, mp.info('testvm') runs multipass info testvm. The module creates one instance, mp.

deploy_mp is deploy for a VM. It creates the target directory if it is missing and gives it to the deploy user. Then it copies your app in and starts it. The cell below lists the VMs on the machine that built these docs. That machine had none.


source

deploy_mp

def deploy_mp(
    name, src, path:str='/srv/app', key:NoneType=None, build:bool=True, verbose:bool=True
)->None:

Copy src into Multipass VM name and start it with docker compose.


source

Multipass

def Multipass(
    *args, **kwargs
):

Run the multipass command to manage local Ubuntu VMs for testing.

_mp = Multipass(); _mc = []
_mp._run = lambda *a: _mc.append(a)
_mp.rm('vm1'); _mp.rm('vm2', purge=False)
assert _mc == [('delete', 'vm1', '--purge'), ('delete', 'vm2')], _mc
Multipass().vms()
[]

Cloud-init generation

A new cloud server starts as a bare Ubuntu image. Cloud-init is a program that runs on the first boot of the server. It reads a YAML file supplied when the server is created. It installs packages, creates users, adds SSH keys and runs commands. vps_init and multi_init write that file. Each returns an AttrDict with the YAML text as yaml and the path of the matching private key as key.

vps_init is for a public server on Hetzner or Lightsail. It builds the file with cloud_init_config from fastcloudinit. That function turns on the UFW firewall with only SSH allowed, adds log rotation and reboots at the end. vps_init adds the fail2ban and unattended-upgrades packages. Unless you pass docker=False, it also installs Docker and adds the user to the docker group. Other keyword arguments go to cloud_init_config.

multi_init is for a Multipass VM. It uses the smaller cloud_init_base. The user and Docker setup are the same as in vps_init. multi_init sets no firewall, installs no fail2ban and adds no swap file. It reboots only when there are commands to run. The Docker install counts as commands.

Both functions create one user, deploy by default. The user can run sudo without a password. The user logs in only with the SSH keys in pub_keys. If you omit pub_keys, gen_key uses the ed25519 key pair at ~/.ssh/<hostname>. It makes the key pair when no private key is there. It reuses a private key that is already there and writes a missing .pub file from it. gen_key(hostname, replace=True) makes a new key pair. key is the path of the private key. If you pass pub_keys, key is None. Use pkgs for extra packages and cmds for extra shell commands. The commands run after the Docker install.

vps_init also adds a swap file and sets the kernel swappiness to 10. The swap file is 4 GB by default. A swappiness of 10 makes the server swap only under real memory pressure. Without swap, a small server that runs several containers kills a process when memory runs out. Pass swap=None to skip swap, or a size such as swap='2G'. Pass swappiness to change the value. The commands add the swap file only if /swapfile does not exist, and they run before the Docker install. swap_cmds returns the commands on their own, for a server that already exists.

The first test below passes a key, so multi_init generates none. The second test generates a key pair and deletes it.


source

vps_init

def vps_init(
    hostname, pub_keys:NoneType=None, username:str='deploy', docker:bool=True, pkgs:NoneType=None,
    cmds:NoneType=None, swap:str='4G', swappiness:int=10,
    key_dir:NoneType=None, # folder for the generated key pair when `pub_keys` is None; default `~/.ssh`
    **kw
):

Write a cloud-init file for a public server, generating a key pair if pub_keys is None.


source

swap_cmds

def swap_cmds(
    size:str='4G', swappiness:int=10
):

Return shell commands that add a size swap file once and set the kernel swappiness.


source

gen_key

def gen_key(
    slug, key_dir:NoneType=None, replace:bool=False
):

Make an ed25519 key pair at <key_dir>/<slug> and return its paths and public key text. An existing private key is reused, and its public key is derived from it, unless replace is True.


source

keygen

def keygen(
    path
):

source

multi_init

def multi_init(
    hostname, pub_keys:NoneType=None, username:str='deploy', docker:bool=True, pkgs:NoneType=None,
    cmds:NoneType=None,
    key_dir:NoneType=None, # folder for the generated key pair when `pub_keys` is None; default `~/.ssh`
):

Write a cloud-init file for a local Multipass VM, generating a key pair if pub_keys is None.

ci = multi_init('mylocal', 'ssh-rsa AAAA...')
assert '#cloud-config' in ci.yaml and 'get.docker.com' in ci.yaml and 'ufw' not in ci.yaml
assert 'power_state' in ci.yaml and ci.key is None
print(ci.yaml)

with tempfile.TemporaryDirectory() as kd:
    ci2 = multi_init('mylocal', docker=False, key_dir=kd)
    assert 'get.docker.com' not in ci2.yaml and 'power_state' not in ci2.yaml
    assert ci2.key == Path(kd)/'mylocal' and ci2.key.exists()
    assert Path(str(ci2.key) + '.pub').exists()
    k1 = gen_key('mylocal', kd)
    other = gen_key('other', kd)
    k1.pub.write_text(other.pub_str[0] + '\n')
    k2 = gen_key('mylocal', kd)
    assert k2.pub_str == k1.pub_str != other.pub_str and k1.pub.read_text().strip() == k1.pub_str[0]
    k3 = gen_key('mylocal', kd, replace=True)
    assert k3.pub_str != k1.pub_str
print('multi_init OK')
#cloud-config
hostname: mylocal
preserve_hostname: false
packages:
- curl
package_update: true
package_upgrade: true
disable_root: true
ssh_pwauth: false
users:
- name: deploy
  groups:
  - sudo
  shell: /bin/bash
  sudo:
  - ALL=(ALL) NOPASSWD:ALL
  ssh_authorized_keys:
  - ssh-rsa AAAA...
runcmd:
- curl -fsSL https://get.docker.com | sh
- usermod -aG docker deploy
- systemctl enable --now docker
power_state:
  mode: reboot
  message: Rebooting
  timeout: 1
  condition: true

multi_init OK
ci = vps_init('myserver', 'ssh-rsa AAAA...', docker=True)
assert '#cloud-config' in ci.yaml and 'get.docker.com' in ci.yaml
assert 'fail2ban' in ci.yaml and 'unattended-upgrades' in ci.yaml
assert ci.key is None
assert 'fallocate -l 4G /swapfile' in vps_init('s', 'ssh-rsa AAAA...', docker=True, cmds=['fallocate -l 4G /swapfile']).yaml
assert 'echo hi' in multi_init('m', 'ssh-rsa AAAA...', docker=True, cmds=['echo hi']).yaml
assert 'fallocate -l 4G /swapfile' in ci.yaml and 'vm.swappiness=10' in ci.yaml
y = vps_init('s', 'ssh-rsa AAAA...', swap='2G', swappiness=5).yaml
assert 'fallocate -l 2G /swapfile' in y and 'vm.swappiness=5' in y
assert 'swapfile' not in vps_init('s', 'ssh-rsa AAAA...', swap=None).yaml
print(ci.yaml)
print('vps_init OK')
#cloud-config
hostname: myserver
preserve_hostname: false
packages:
- curl
- fail2ban
- unattended-upgrades
package_update: true
package_upgrade: true
disable_root: true
ssh_pwauth: false
users:
- name: deploy
  groups:
  - sudo
  shell: /bin/bash
  sudo:
  - ALL=(ALL) NOPASSWD:ALL
  ssh_authorized_keys:
  - ssh-rsa AAAA...
runcmd:
- curl -fsSL https://get.docker.com | sh
- usermod -aG docker deploy
- systemctl enable --now docker
- ufw default deny incoming
- ufw default allow outgoing
- ufw logging off
- ufw allow 22/tcp
- ufw --force enable
apt:
  conf: 'APT::Periodic::Update-Package-Lists "1";

    APT::Periodic::Download-Upgradeable-Packages "1";

    APT::Periodic::AutocleanInterval "7";

    APT::Periodic::Unattended-Upgrade "0";

    Unattended-Upgrade::Automatic-Reboot "false";

    '
write_files:
- path: /etc/logrotate.d/00-cloud-init-global
  owner: root:root
  permissions: '0644'
  content: "/var/log/*.log {\n    weekly\n    rotate 7\n    compress\n    su root adm\n    create\n    missingok\n}\n"
power_state:
  mode: reboot
  message: Rebooting
  timeout: 1
  condition: true

vps_init OK

Hetzner

Hetzner manages servers on Hetzner Cloud through the hcloud Python SDK, so you do not need Hetzner’s command-line tool or a config file. It reads the API token from HCLOUD_TOKEN unless you pass token=, and raises ValueError if there is none.

create makes a server and returns its IP address, name, key path and the raw SDK response. Give it the result of vps_init as cloud_init, and the key path comes back with the server. ssh_keys is a different way to log in. It names keys stored in your Hetzner account, and Hetzner adds them to the root user only. They give no access to the deploy user that cloud-init creates, so create refuses to take both. key_names lists the stored keys for that purpose.

servers lists your servers with their IP and status, get returns one by name or None, server_ip returns its address and delete removes it. Deleting a server that does not exist does nothing.


source

Hetzner

def Hetzner(
    token:NoneType=None
):

Create, list and delete Hetzner Cloud servers, using the token in HCLOUD_TOKEN by default.

Integration tests

These cells need HCLOUD_TOKEN and do not run when the docs are built. They list your servers, create a cx23 server in Helsinki, check that servers and server_ip see it, and delete it.

hz = Hetzner()
L(hz.servers()).attrgot('name')
['vedicreader-cx32-hel']
sn = 'fastops-test'
hz.delete(sn)
svr=hz.create(sn, server_type='cx23', location='hel1')
assert svr.ip, 'create() should return an IP'
print(f'create OK: {svr.ip}')
o = lambda: L(hz.servers()).attrgot('name')
print(f'servers() OK: {o()}')
assert sn in o(), f'servers() should include {sn}'
assert hz.server_ip(sn) == svr.ip
hz.delete(sn)
assert sn not in o()
print(f'servers() after delete: {o()}')
print('delete() OK\nAll hcloud tests passed!')
create OK: 89.167.95.57
servers() OK: ['vedicreader-cx32-hel', 'fastops-test']
servers() after delete: ['vedicreader-cx32-hel']
delete() OK
All hcloud tests passed!

Lightsail

Lightsail is the fixed-price virtual private server (VPS) service of Amazon. Lightsail has the same methods as Hetzner: servers, get, server_ip, create and delete. It talks to AWS through boto3. vps_deploy works with either class. boto3 is an optional extra: pip install 'vpseasy[aws]'. Without boto3, Lightsail() raises ImportError. Credentials come from the standard AWS chain. For example, name an SSO profile in AWS_PROFILE or pass profile=. The region defaults to ap-southeast-2 (Sydney).

create is safe to run twice. It does not create an instance that already exists. In both cases it calls server_ip, which waits until the instance is running. server_ip raises TimeoutError after tout seconds (300 by default). If static_ip is True, the default, create then attaches a static IP address named <name>-ip. A static IP that is already allocated is reused. If ports is not None, create sets the open public ports to ports. If snapshots is set, create turns on a daily automatic snapshot at that time. By default only SSH (port 22) is open, because web traffic arrives through the Cloudflare tunnel. The default snapshot time is 16:00 UTC. delete removes the instance. Unless you pass release_ip=False, it also releases the static IP. bucket makes a storage bucket for backups. The Litestream section covers it.

Lightsail runs user data as a shell script. It does not read cloud-config YAML. When the user data starts with #cloud-config, create converts it with cloud_init_sh. Other user data passes through unchanged. The script runs these steps in order: it sets the hostname, turns off password logins, creates the users with their groups, sudo rules and SSH keys, writes files, applies apt settings, installs packages and runs the commands. It turns off password logins only when the YAML sets ssh_pwauth: false. The script does not reboot. It keeps the original YAML in /var/lib/vpseasy/cloud-config.yaml and logs to /var/log/vpseasy-init.log. When it finishes, it creates /var/lib/vpseasy/ready. If a step failed, it creates /var/lib/vpseasy/error instead. chk_cloud_init reads those files.

cloud_init_sh converts these top-level keys: hostname, users, write_files, apt, packages, runcmd, package_update, package_upgrade and ssh_pwauth. It ignores preserve_hostname, disable_root and power_state. It raises ValueError for any other top-level key, for a user key it cannot convert, and for an invalid write_files permission. The conversion exists because cloud-init did not create the users on Ubuntu 24.04 when it ran on YAML placed in /etc/cloud/cloud.cfg.d.


source

cloud_init_sh

def cloud_init_sh(
    cloud_init
):

Convert a vps_init cloud-config into a bash script, for providers such as Lightsail that run user data as a script.


source

Lightsail

def Lightsail(
    region:str='ap-southeast-2', profile:NoneType=None
):

Create, list and delete AWS Lightsail instances through boto3, using the standard AWS credentials.

from fastcore.test import test_eq, test_fail
y = vps_init('lh', 'ssh-ed25519 AAAATEST lh').yaml
ud = cloud_init_sh(y)
subprocess.run(['bash', '-n'], input=ud, text=True, check=True)
assert ud.startswith('#!/bin/bash\n') and y.rstrip() in ud
assert "useradd -m -s /bin/bash deploy" in ud and 'ssh-ed25519 AAAATEST lh' in ud and 'deploy ALL=(ALL) NOPASSWD:ALL' in ud
assert 'get.docker.com' in ud and 'ufw --force enable' in ud and ud.rstrip().endswith('touch /var/lib/vpseasy/ready')
assert '--force-confold' in ud and 'PasswordAuthentication no' in ud and 'rm -f /var/lib/vpseasy/error' in ud
body = ud[ud.index('hostnamectl'):]
assert body.index('useradd') < body.index('apt-get') < body.index('get.docker.com')
test_fail(lambda: cloud_init_sh('#cloud-config\nbootcmd: [echo hi]\n'), contains='bootcmd')
u = cloud_init_sh("#cloud-config\nusers: [default, {name: bob, groups: 'sudo, docker'}]\n")
assert 'usermod -aG sudo,docker bob' in u and 'default' not in u.split('VPSEASY_EOF')[-1]
test_fail(lambda: cloud_init_sh('#cloud-config\nusers: [{name: bob, lock_passwd: true}]\n'), contains='lock_passwd')
w = cloud_init_sh("#cloud-config\nwrite_files: [{path: /etc/x, content: hi, permissions: 0600, owner: 'a b'}]\n")
assert 'chmod 600 /etc/x' in w and "chown 'a b' /etc/x" in w
test_fail(lambda: cloud_init_sh("#cloud-config\nwrite_files: [{path: /etc/x, permissions: '0644; rm -rf /'}]\n"), contains='permissions')
from fastcore.test import test_eq, test_fail
from botocore.stub import Stubber
ls = Lightsail(region='ap-southeast-2')
st = Stubber(ls._c)
def inst(state='running', ip='3.1.2.3'): return {'instance': {'name': 'lh', 'state': {'name': state}, **({'publicIpAddress': ip} if ip else {})}}

st.add_response('get_instances', {'instances': [inst()['instance']]})
with st: test_eq(ls.servers(), [dict(name='lh', ip='3.1.2.3', status='running')])

st.add_response('get_instance', inst('pending', None), {'instanceName': 'lh'})
st.add_response('get_instance', inst(), {'instanceName': 'lh'})
with st: test_eq(ls.server_ip('lh', interval=0), '3.1.2.3')

st.add_response('get_instance', inst(), {'instanceName': 'lh'})
st.add_response('get_instance', inst(), {'instanceName': 'lh'})
with st: r = ls.create('lh', cloud_init='#cloud-config\n', static_ip=False, ports=None, snapshots=None)
test_eq(r.ip, '3.1.2.3')

st.add_client_error('get_instance', service_error_code='NotFoundException', expected_params={'instanceName': 'nope'})
with st: test_eq(ls.get('nope'), None)
st.assert_no_pending_responses()
st = Stubber(ls._c)
st.add_client_error('get_instance', service_error_code='NotFoundException', expected_params={'instanceName': 'lh'})
st.add_response('create_instances', {'operations': []}, {'instanceNames': ['lh'], 'availabilityZone': 'ap-southeast-2a',
                'blueprintId': 'ubuntu_24_04', 'bundleId': 'small_3_2', 'userData': cloud_init_sh('#cloud-config\n')})
st.add_response('get_instance', inst(), {'instanceName': 'lh'})
st.add_client_error('allocate_static_ip', service_error_code='InvalidInputException', service_message='Static IP already in use')
st.add_response('attach_static_ip', {'operations': []}, {'staticIpName': 'lh-ip', 'instanceName': 'lh'})
st.add_response('get_static_ip', {'staticIp': {'name': 'lh-ip', 'ipAddress': '13.5.5.5'}}, {'staticIpName': 'lh-ip'})
st.add_response('put_instance_public_ports', {'operation': {}}, {'instanceName': 'lh', 'portInfos': [dict(fromPort=22, toPort=22, protocol='tcp')]})
st.add_response('enable_add_on', {'operations': []}, {'resourceName': 'lh', 'addOnRequest': {'addOnType': 'AutoSnapshot', 'autoSnapshotAddOnRequest': {'snapshotTimeOfDay': '16:00'}}})
with st: r = ls.create('lh', cloud_init='#cloud-config\n')
test_eq(r.ip, '13.5.5.5')
st.assert_no_pending_responses()

st.add_response('get_instance', inst('pending', None), {'instanceName': 'lh'})
with st: test_fail(lambda: ls.server_ip('lh', tout=0.05, interval=0.1), exc=TimeoutError)
st = Stubber(ls._c)
st.add_client_error('get_buckets', service_error_code='NotFoundException', expected_params={'bucketName': 'lh-backups'})
st.add_response('create_bucket', {'bucket': {'name': 'lh-backups'}, 'operations': []}, {'bucketName': 'lh-backups', 'bundleId': 'small_1_0'})
st.add_response('create_bucket_access_key', {'accessKey': {'accessKeyId': 'AKIAEXAMPLE000000001', 'secretAccessKey': 's3cr3t'}, 'operations': []}, {'bucketName': 'lh-backups'})
with st: b = ls.bucket('lh-backups')
assert 's3cr3t' not in repr(b) and b.secret == 's3cr3t'
test_eq(b, AttrDict(bucket='lh-backups', region='ap-southeast-2', endpoint='https://s3.ap-southeast-2.amazonaws.com', key_id='AKIAEXAMPLE000000001', secret='s3cr3t'))

st.add_response('get_buckets', {'buckets': [{'name': 'lh-backups'}]}, {'bucketName': 'lh-backups'})
st.add_response('create_bucket_access_key', {'accessKey': {'accessKeyId': 'AKIAEXAMPLE000000002', 'secretAccessKey': 's2'}, 'operations': []}, {'bucketName': 'lh-backups'})
with st: test_eq(ls.bucket('lh-backups').key_id, 'AKIAEXAMPLE000000002')
st.assert_no_pending_responses()

SSH helpers

These functions call the system ssh and rsync commands. No Python SSH library is needed. They share these arguments. user (or u) is the login name, deploy by default. The private key comes from the first of these that applies: the path in key (or k); then ~/.ssh/<name> if you pass name; then the key that ssh picks by itself. If you pass name and the file ~/.ssh/<name> does not exist, the function raises FileNotFoundError. key_pass is the passphrase of an encrypted key. password is a login password for servers that accept one. Pass True to either to be asked for it. Every function that connects takes port, the SSH port, which is 22 by default. The first connection to a new host adds it to known_hosts without asking.

run_ssh runs one or more commands on the host, joined with &&. It returns their output. If the commands wrote to stderr, run_ssh appends that text after ;;. If a command fails, run_ssh raises IOError. With check=False it returns (exit code, output) instead. stdin_data is sent to the remote command’s standard input.

sync copies a local directory to path on the host with rsync. If path is missing or not writable, sync first creates it with sudo and gives it to user. sync deletes remote files that are not in src. Point it at a directory that belongs to the app alone. exclude skips files that match a pattern. include copies only the files that match a pattern. A pattern that ends in / takes a whole directory. extra adds rsync flags such as --checksum.

sync raises CalledProcessError when rsync fails. Nothing runs on a half-copied folder. sync returns the rsync exit code. With check=False, a failed rsync returns its exit code instead of raising.

sync_paths copies chosen paths instead of a whole folder. Use it for content that changes without a rebuild, such as the files behind a bind mount. Each path under src goes to the same path under path. sync_paths runs one rsync per path. --delete removes only files inside that path. It never reaches the rest of the folder on the server. A path that is missing from src is skipped. rsync’s --mkpath creates missing remote folders. delete=False, mkpath=False and itemize=False turn off the matching rsync flags.

last names a pattern. rsync holds the files that match it back from a first pass and sends them in a second pass. Use last when something on the server watches for one kind of file. With last='*.json', an audio file is in place before the JSON file that names it.

A path that names the folder itself raises ValueError. Examples are ., '' and /. A path that resolves to the folder, or leaves it through .. or a symlink, also raises ValueError. Its --delete would reach the whole folder.

dry_run=True lists the changes without making them. With host=None, the copy goes to a local folder. sync_paths returns the rsync commands it ran. rsync_cmds returns the commands without running them. It raises the same ValueError.

deploy runs sync. Then it runs docker compose up -d --remove-orphans in path. It adds --build unless you pass build=False. It starts Compose only if Docker works for the user and path holds a docker-compose.yml. Otherwise it stops after the copy. chk_docker is the Docker check on its own. It returns True or False. After a build, deploy keeps the new image and the image it replaced with keep_image. rollback can then return to either image. keep=0 turns this off. After the build, prune=True deletes dangling images and the build cache. Without pruning, they grow by the size of an image on every deploy. Pruning leaves kept images, because they carry tags.

ssh_cmd, res_key and askpass_env are the functions the others share. ssh_cmd returns the ssh command line. res_key looks up the key. askpass_env is a context manager that answers a password prompt. They are public for callers that run their own ssh or rsync. _ssh, _res_key and _askpass_env remain as aliases.


source

deploy

def deploy(
    host, src:str='.', path:str='/srv/app', user:str='deploy', build:bool=True, key:NoneType=None,
    name:NoneType=None, include:NoneType=None, exclude:NoneType=None, extra:NoneType=None, key_pass:NoneType=None,
    password:NoneType=None, verbose:bool=False, port:int=22, prune:bool=True, keep:int=3, svc:str='app',
    img:NoneType=None
):

Copy src to path on host, then run docker compose up there if Docker and a Compose file are present.


source

chk_docker

def chk_docker(
    host, u:str='deploy', k:NoneType=None, name:NoneType=None, key_pass:NoneType=None, password:NoneType=None,
    verbose:bool=False, port:int=22
)->bool:

Return True if Docker is running on host and u can use it.


source

sync_paths

def sync_paths(
    host, paths, src:str='.', path:str='/srv/app', user:str='deploy', key:NoneType=None, name:NoneType=None,
    port:int=22, key_pass:NoneType=None, password:NoneType=None, exclude:NoneType=None, delete:bool=True,
    mkpath:bool=True, itemize:bool=True, dry_run:bool=False, last:NoneType=None, verbose:bool=True
):

Copy each of paths under src to the same path under path on host, or in a local folder when host is None, and return the commands run.


source

rsync_cmds

def rsync_cmds(
    paths, src, dest, ssh_e:NoneType=None, exclude:NoneType=None, delete:bool=True, mkpath:bool=True,
    itemize:bool=True, dry_run:bool=False, last:NoneType=None
):

Return one rsync command per path in paths, from under src to the same path under dest. When last is given, each path first gets a command that leaves out last. Raise ValueError for a path that names src or leaves it.


source

sync

def sync(
    host, src:str='.', path:str='/srv/app', user:str='deploy', key:NoneType=None, name:NoneType=None,
    include:NoneType=None, exclude:NoneType=None, extra:NoneType=None, key_pass:NoneType=None,
    password:NoneType=None, port:int=22, verbose:bool=False, check:bool=True
):

Copy local directory src to path on host with rsync, delete remote files that are not in src, raise CalledProcessError if rsync fails and check is True, and return rsync’s exit code.


source

run_ssh

def run_ssh(
    host, *cmds, user:str='deploy', key:NoneType=None, name:NoneType=None, port:int=22, key_pass:NoneType=None,
    password:NoneType=None, check:bool=True, verbose:bool=False, stdin_data:NoneType=None
):

Run cmds on host over SSH, joined with &&. Return the output, or (exit code, output) when check is False. Raise IOError on failure when check is True.


source

askpass_env

def askpass_env(
    pw
):

Answer the SSH passphrase or password prompt with pw through SSH_ASKPASS; does nothing when pw is empty.


source

res_key

def res_key(
    key:NoneType=None, name:NoneType=None
):

Return key if given. Otherwise return the path ~/.ssh/<name> if name is given, and raise FileNotFoundError if that file is missing. Otherwise return None.


source

ssh_cmd

def ssh_cmd(
    host, user, key, port:int=22
):

Return the ssh command line for user@host, with the key and port when given.

assert _ssh('1.2.3.4', 'deploy', None, 22) == ['ssh', '-o', 'StrictHostKeyChecking=accept-new', 'deploy@1.2.3.4']
assert _ssh('1.2.3.4', 'deploy', '/k', 2222)[-3:] == ['-p', '2222', 'deploy@1.2.3.4']
assert '-i' in _ssh('h', 'u', '/my/key', 22)
print('_ssh_base OK')
assert _res_key('/tmp/mykey') == '/tmp/mykey'
try: _res_key(name='__no_such_vpseasy_key__')
except FileNotFoundError as e: assert '__no_such_vpseasy_key__' in str(e)
print('_res_key OK')
assert (_ssh, _res_key, _askpass_env) == (ssh_cmd, res_key, askpass_env)
_ssh_base OK
_res_key OK
from unittest.mock import patch
_calls = []
with patch('subprocess.run', lambda c, **kw: _calls.append(c) or AttrDict(stdout=b'', stderr=b'', returncode=0)):
    sync('1.2.3.4', '/tmp/src', key='/k', port=2222)
assert _calls[0][:-1] == _ssh('1.2.3.4', 'deploy', '/k', 2222)
assert _calls[1][_calls[1].index('-e')+1] == 'ssh -o StrictHostKeyChecking=accept-new -i /k -p 2222'
print('sync port OK')
sync port OK
import subprocess as _sp
def _fake(c, check=False, **kw):
    if c[0] == 'rsync' and check: raise _sp.CalledProcessError(23, c)
    return AttrDict(stdout=b'', stderr=b'', returncode=0 if c[0] != 'rsync' else 23)
with patch('subprocess.run', _fake):
    try: sync('1.2.3.4', '/tmp/src', key='/k'); raise AssertionError('sync ignored a failed rsync')
    except _sp.CalledProcessError: pass
with patch('subprocess.run', _fake): test_eq(sync('1.2.3.4', '/tmp/src', key='/k', check=False), 23)
print('sync check OK')
sync check OK
import shutil
if shutil.which('rsync'):
    _s, _t = Path(tempfile.mkdtemp()), Path(tempfile.mkdtemp())
    for f in ('a/x.mp3', 'a/x.json', 'b/y.txt', 'code.py'): (_s/f).parent.mkdir(parents=True, exist_ok=True); (_s/f).write_text(f)
    (_t/'a').mkdir(); (_t/'a/old.txt').write_text('gone'); (_t/'keep.txt').write_text('kept')
    cs = sync_paths(None, ['a/', 'b/', 'missing/'], _s, _t, exclude=['*.txt'], last='*.json', verbose=False)
    test_eq([c[-2:] for c in cs], [[f'{_s}/a/', f'{_t}/a/']] * 2 + [[f'{_s}/b/', f'{_t}/b/']] * 2)
    test_eq(sorted(str(f.relative_to(_t)) for f in _t.rglob('*') if f.is_file()), ['a/old.txt', 'a/x.json', 'a/x.mp3', 'keep.txt'])
    assert cs[0][cs[0].index('*.json') - 1] == '--exclude' and '*.json' not in cs[1]
    shutil.rmtree(_t/'a'); sync_paths(None, ['a/'], _s, _t, dry_run=True, verbose=False); assert not (_t/'a').exists()
c = rsync_cmds(['a/'], '/s', 'deploy@h:/srv', 'ssh -p 2222', delete=False, itemize=False)
test_eq(c, [['rsync', '-azh', '--mkpath', '-e', 'ssh -p 2222', '/s/a/', 'deploy@h:/srv/a/']])
_v = Path(tempfile.mkdtemp()); (_v/'d').mkdir()
test_eq(rsync_cmds(['d'], _v, '/x')[0][-2:], [f'{_v}/d/', '/x/d/'])
test_eq(rsync_cmds(['f.txt'], _v, '/x')[0][-2:], [f'{_v}/f.txt', '/x/f.txt'])
_calls, _u = [], Path(tempfile.mkdtemp())
(_u/'nbs').mkdir()
with patch('subprocess.run', lambda c, **kw: _calls.append(c)): sync_paths('1.2.3.4', ['nbs/'], _u, key='/k', port=2222, verbose=False)
test_eq(_calls[0][_calls[0].index('-e')+1], 'ssh -o StrictHostKeyChecking=accept-new -i /k -p 2222')
test_eq(_calls[0][-1], 'deploy@1.2.3.4:/srv/app/nbs/')
print('sync_paths OK')
sync_paths OK
_r = Path(tempfile.mkdtemp()); (_r/'a').mkdir(); (_r/'self').symlink_to(_r); (_r/'out').symlink_to(tempfile.mkdtemp())
for bad in ('.', '', '/', './', 'a/..', '..', '../x', 'self', 'out'):
    test_fail(lambda: sync_paths(None, [bad], _r, tempfile.mkdtemp(), verbose=False), contains='deploy root')
    test_fail(lambda: rsync_cmds(['a/', bad], _r, '/x'), contains='deploy root')
test_eq(len(rsync_cmds(['a/', '/a', 'missing/'], _r, '/x')), 3)

sync quotes the remote path and the key path, so a space in either stays inside one shell word. The cell records the commands with a stand-in for subprocess.run and shows the remote command.

def _fake(cmd, *a, **k): _rec.append(cmd); return _sp.CompletedProcess(cmd, 0, b'', b'')
_rec = []
with patch.object(subprocess, 'run', _fake): sync('h', '.', path='/srv/my app', key='/k/my key')
_mk, _rs = _rec
assert '/srv/my app' in shlex.split(_mk[-1])
assert '/k/my key' in shlex.split(_rs[_rs.index('-e')+1])
_mk[-1]

sync protects Compose bind sources inside the remote deploy root from deletion. Local files in those bind sources still transfer. A bind source that names the whole deploy root raises ValueError. sync_paths applies the same protection within each selected path. Both functions read the local Compose file. Named volumes stored by Docker and bind sources outside the deploy root need no rsync protection. Add other paths with exclude. Keep the local Compose file available when syncing. Compose variable interpolation and override files, including automatic override files, are not resolved. Add their bind sources with exclude.

deploy removes dangling images and prunes build cache older than 168 hours after a successful deploy. Set prune=False to skip pruning. The default protects recent build cache while limiting old cache growth.

with tempfile.TemporaryDirectory() as td:
    root = Path(td)
    (root/'nested').mkdir()
    (root/'data').mkdir()
    (root/'docker-compose.yml').write_text(yaml.safe_dump(dict(services=dict(app=dict(volumes=[
        './data:/app/data', './nested/backups:/app/backups',
        dict(type='bind', source='/srv/app/archive', target='/archive'), './settings.json:/settings.json',
        'named:/named'])))))
    _rec = []
    with patch.object(subprocess, 'run', _fake): sync('h', root, exclude=['extra'])
    cmd = _rec[-1]
    rules = [cmd[i+1] for i, v in enumerate(cmd) if v == '--filter']
    assert all('P ' + p in rules for p in ['/data', '/nested/backups', '/archive', '/settings.json']), rules
    assert cmd[cmd.index('--exclude')+1] == 'extra'
    cmds = rsync_cmds(['nested/', 'data/'], root, 'deploy@h:/srv/app')
    assert len(cmds) == 2, cmds
    assert 'P /backups' in cmds[0], cmds
    assert 'P /***' in cmds[1], cmds
    (root/'docker-compose.yml').write_text(yaml.safe_dump(dict(services=dict(app=dict(volumes=['.:/app'])))))
    with patch.object(subprocess, 'run', _fake):
        test_fail(lambda: sync('h', root), contains='whole deploy root')
rules
_prune_calls = []
with patch.dict(deploy.__globals__, sync=lambda *a, **kw: None,
                chk_docker=lambda **kw: True, _chk_compose=lambda **kw: True,
                _img=lambda *a: 'app',
                run_ssh=lambda host, cmd, **kw: _prune_calls.append(cmd) or ''):
    deploy('h', build=False, keep=0)
    assert any('docker builder prune -f --filter until=168h' in c for c in _prune_calls), _prune_calls
    _prune_calls.clear()
    deploy('h', build=False, keep=0, prune=False)
    assert not any('prune' in c for c in _prune_calls)
_prune_calls
with tempfile.TemporaryDirectory() as td:
    root, dest = Path(td)/'src', Path(td)/'dest'
    (root/'nested'/'data').mkdir(parents=True)
    (dest/'nested'/'data').mkdir(parents=True)
    (root/'nested'/'settings.json').write_text('new content')
    (dest/'nested'/'settings.json').write_text('old')
    (dest/'nested'/'data'/'production.db').write_text('keep')
    (dest/'nested'/'stale.txt').write_text('remove')
    (root/'docker-compose.yml').write_text(yaml.safe_dump(dict(services=dict(app=dict(volumes=[
        './nested/data:/data', './nested/settings.json:/settings.json'])))))
    sync_paths(None, ['nested/'], src=root, path=dest, verbose=False)
    assert (dest/'nested'/'data'/'production.db').read_text() == 'keep'
    assert (dest/'nested'/'settings.json').read_text() == 'new content'
    assert not (dest/'nested'/'stale.txt').exists()
    (dest/'nested'/'data'/'production.db').read_text()
r = hz._c.servers.get_by_name('vedicreader-cx32-hel')
run_ssh(r.public_net.ipv4.ip,user='vedicgit', password=True)
'Welcome to Ubuntu 24.04.2 LTS (GNU/Linux 6.8.0-60-generic x86_64)\n\n * Documentation:  https://help.ubuntu.com\n * Management:     https://landscape.canonical.com\n * Support:        https://ubuntu.com/pro\n\n System information as of Thu Jun  4 11:41:42 PM UTC 2026\n\n  System load:  0.08               Processes:             182\n  Usage of /:   35.6% of 74.79GB   Users logged in:       0\n  Memory usage: 63%                IPv4 address for eth0: 46.62.133.112\n  Swap usage:   0%                 IPv6 address for eth0: 2a01:4f9:c012:ef36::1\n\n * Strictly confined Kubernetes makes edge and IoT secure. Learn how MicroK8s\n   just raised the bar for easy, resilient and secure K8s cluster deployment.\n\n   https://ubuntu.com/engage/secure-kubernetes-at-the-edge\n\nExpanded Security Maintenance for Applications is not enabled.\n\n58 updates can be applied immediately.\nTo see these additional updates run: apt list --upgradable\n\nEnable ESM Apps to receive additional future security updates.\nSee https://ubuntu.com/esm or run: sudo pro status\n\n\n*** System restart required *** ;; Pseudo-terminal will not be allocated because stdin is not a terminal.'

Verification helpers

create returns as soon as the provider accepts the request, while the server is still booting and cloud-init is still working. Copying files at that point fails or races the setup, so these functions wait.

wait_ssh tries a trivial SSH command every interval seconds until it succeeds, and raises TimeoutError after tout seconds. chk_cloud_init asks once whether setup has finished and returns done, running or error. On a server set up by a cloud_init_sh script it reads that script’s marker files in /var/lib/vpseasy. Elsewhere it checks for /var/lib/cloud/instance/boot-finished, the file cloud-init writes when it is done. It returns unknown if the command printed nothing. wait_ready, further down, runs both in a loop.


source

chk_cloud_init

def chk_cloud_init(
    host, u:str='deploy', k:NoneType=None, name:NoneType=None, key_pass:NoneType=None, password:NoneType=None,
    verbose:bool=True, port:int=22
)->str:

Return done, running or error for the setup of host, read from the cloud-init or cloud_init_sh marker files.


source

wait_ssh

def wait_ssh(
    host, u:str='deploy', k:NoneType=None, name:NoneType=None, p:int=22, tout:int=300, interval:int=5,
    key_pass:NoneType=None, password:NoneType=None, verbose:bool=True
):

Retry an SSH connection to host until it works, raising TimeoutError after tout seconds.

assert chk_docker('localhost', name='__no_such_vpseasy_key__') is False
print('chk_docker: bad key → False OK')

try: wait_ssh('1.2.3.4', tout=0); assert False
except TimeoutError as e: assert '1.2.3.4' in str(e)
print('wait_ssh: tout=0 → TimeoutError OK')
chk_docker: bad key → False OK
wait_ssh: tout=0 → TimeoutError OK

wait_ready waits for SSH with wait_ssh. wait_ssh retries every interval seconds and raises TimeoutError after tout seconds. Then wait_ready calls chk_cloud_init every interval seconds until it returns done. chk_cloud_init returns done, running or error. wait_ready raises RuntimeError when the status is error. A slow server gets retries extra rounds of tout seconds each. wait_ready prints a message before each extra round. After the last round it raises TimeoutError.

vps_deploy is the function most people want. It takes a server name, a local directory and a provider such as Hetzner() or Lightsail(). If the provider has no server with that name, vps_deploy creates one from vps_init(name). That call makes a new key pair at ~/.ssh/<name>. vps_deploy then removes any old known_hosts entry for the new IP address. If the server exists, vps_deploy uses the key at ~/.ssh/<name>, or key if you pass one. In both cases it then runs wait_ready and deploy. It returns an AttrDict with the IP address as ip, the server name as name and the key path as key. Extra keyword arguments go to the create method of the provider. Examples are server_type= for Hetzner and bundle= for Lightsail. For an existing server, vps_deploy does not call create, and these arguments have no effect. vps_deploy checks for the server before it creates one. Running it again redeploys to the same server.

hetzner_deploy is vps_deploy with a Hetzner provider. It takes the Hetzner arguments image, server_type and location. hz is an existing Hetzner client. hetzner_deploy remains for code written before Lightsail support.

The tests after these two functions use a fake provider. They check both paths without touching a real server.


source

wait_ready

def wait_ready(
    host, u:str='deploy', k:NoneType=None, name:NoneType=None, tout:int=300, interval:int=5, retries:int=2,
    key_pass:NoneType=None, password:NoneType=None, verbose:bool=False, port:int=22
):

Wait until SSH answers on host, then until cloud-init reports done, giving slow setups retries extra rounds.


source

hetzner_deploy

def hetzner_deploy(
    name, # server name, also the key file name under ~/.ssh when `key` is not given
    src, # local path to sync and deploy
    hz:NoneType=None, image:str='ubuntu-24.04', server_type:str='cx23', location:NoneType=None, *,
    user:str='deploy', # login user on the server; also the user a new server's cloud-init creates
    key:NoneType=None, # path of the SSH private key, whose `.pub` file a new server authorizes; overrides the lookup of `~/.ssh/<name>`
    path:str='/srv/app', # remote path to sync to and deploy at
    build:bool=True, # pass `--build` to `docker compose up` when True
    include:NoneType=None, # rsync include (whitelist) patterns
    exclude:NoneType=None, # rsync exclude (blacklist) patterns
    extra:NoneType=None, # extra rsync flags passed to `sync`, such as '--checksum' or ['--ignore-times','--partial']
    key_pass:NoneType=None, # passphrase of an encrypted SSH key; True asks for it
    password:NoneType=None, # login password of the server; True asks for it
    tout:int=600, # seconds to wait for SSH, and for each round of cloud-init polling
    retries:int=2, # extra rounds of cloud-init polling before raising TimeoutError
    verbose:bool=True, # print progress while waiting and deploying
    port:int=22, # SSH port on the server
    prune:bool=True, # delete dangling images and build cache older than 168 hours after deploy
    keep:int=3, # timestamped images of the app kept for `rollback`; 0 keeps none
    svc:str='app', # the Compose service whose image is kept
    img:NoneType=None, # that image's name when the Compose project is not named after `path`
):

Run vps_deploy on Hetzner, with hz or a new Hetzner() client.


source

vps_deploy

def vps_deploy(
    name, # server name, also the key file name under ~/.ssh when `key` is not given
    src, # local path to sync and deploy
    provider, # Hetzner(), Lightsail() or anything with get, server_ip and create
    user:str='deploy', # login user on the server; also the user a new server's cloud-init creates
    key:NoneType=None, # path of the SSH private key, whose `.pub` file a new server authorizes; overrides the lookup of `~/.ssh/<name>`
    path:str='/srv/app', # remote path to sync to and deploy at
    build:bool=True, # pass `--build` to `docker compose up` when True
    include:NoneType=None, # rsync include (whitelist) patterns
    exclude:NoneType=None, # rsync exclude (blacklist) patterns
    extra:NoneType=None, # extra rsync flags passed to `sync`, such as '--checksum' or ['--ignore-times','--partial']
    key_pass:NoneType=None, # passphrase of an encrypted SSH key; True asks for it
    password:NoneType=None, # login password of the server; True asks for it
    tout:int=600, # seconds to wait for SSH, and for each round of cloud-init polling
    retries:int=2, # extra rounds of cloud-init polling before raising TimeoutError
    verbose:bool=True, # print progress while waiting and deploying
    port:int=22, # SSH port on the server
    prune:bool=True, # delete dangling images and build cache older than 168 hours after deploy
    keep:int=3, # timestamped images of the app kept for `rollback`; 0 keeps none
    svc:str='app', # the Compose service whose image is kept
    img:NoneType=None, # that image's name when the Compose project is not named after `path`
    **create_kw
):

Create server name on provider if it does not exist, wait for its setup, deploy src, and return its ip, name and key.

@contextmanager
def patch_to_fakes(calls):
    'Replace `wait_ready`, `deploy`, `vps_init` and `subprocess` with fakes where `vps_deploy` resolves them. No key or `known_hosts` file is touched.'
    g = vps_deploy.__globals__
    ks = 'wait_ready', 'deploy', 'vps_init', 'subprocess'
    o = {k: g[k] for k in ks}
    g['wait_ready'] = lambda *a, **k: calls.append(('wait_ready', a, k))
    g['deploy'] = lambda *a, **k: calls.append(('deploy', a, k))
    g['vps_init'] = lambda name, *a, **k: AttrDict(yaml='#cloud-config\n', key='/tmp/k')
    g['subprocess'] = AttrDict(run=lambda *a, **k: calls.append(('ssh-keygen', a, k)))
    try: yield
    finally: g.update(o)

class FakeProvider:
    def __init__(self, made=()): self.made, self.kw = list(made), None
    def get(self, name): return {'name': name} if name in self.made else None
    def server_ip(self, name): return '192.0.2.9'
    def create(self, name, cloud_init=None, **kw): self.made.append(name); self.kw = kw; return AttrDict(ip='192.0.2.9', name=name, key='/tmp/k')

calls, fp = [], FakeProvider()
with patch_to_fakes(calls): r = vps_deploy('svc', '.', fp, verbose=False, bundle='nano_3_0')
test_eq(r, AttrDict(ip='192.0.2.9', name='svc', key='/tmp/k'))
test_eq([c[0] for c in calls], ['ssh-keygen', 'wait_ready', 'deploy'])
test_eq(fp.kw, dict(bundle='nano_3_0'))

calls, fp = [], FakeProvider(made=['svc'])
with patch_to_fakes(calls): r = vps_deploy('svc', '.', fp, key='/tmp/other', verbose=False)
test_eq(r, AttrDict(ip='192.0.2.9', name='svc', key='/tmp/other'))
test_eq(fp.kw, None)

calls, fp = [], FakeProvider(made=['svc'])
with patch_to_fakes(calls): vps_deploy('svc', '.', fp, key='/tmp/other', verbose=False, port=2222, keep=5, prune=False)
test_eq((calls[0][2]['port'], calls[1][2]['port'], calls[1][2]['keep'], calls[1][2]['prune']), (2222, 2222, 5, False))

Rollback

A deploy builds a new image and replaces the running container. A bad build takes the site down. deploy keeps the image that it replaces. rollback starts that image again.

Compose names the image that it builds for a service after the project folder and the service. The folder /srv/app with the service app builds app-app:latest. Compose removes characters other than lower-case letters, digits, - and _ from the folder name. vpseasy does the same, and it also drops a leading - or _. Pass img when the project has another name, set by name: in the Compose file or by COMPOSE_PROJECT_NAME. vps_deploy passes img on to deploy.

After each build, keep_image tags the new image with its build time in UTC, such as app-app:20261019T063000. It tags the image that ran before as app-app:prev. It also gives that image its build time when the image has none. Then it deletes the timestamped tags past the newest keep by build time. keep is three by default. It never deletes the tags of the running image and of prev. An image with two timestamps counts once. A build whose second another build already holds takes the next free second. deploy runs keep_image even when the restart after the build fails. The new build already holds latest. A build keeps its tag until it falls out of the newest keep, whatever rollbacks happen in between.

A failed docker rmi leaves the tag in place. This happens when a stopped container still uses the tag. The deploy continues. Pruning after the build deletes only dangling images and the build cache. Tagged images stay. kept_images lists the kept tags, newest first, with their image IDs.

rollback points the service at a kept image and restarts it. Without to, it picks the newest kept image that is older than the running one. Calling it twice goes back two builds. With to, it uses that tag, which is a timestamp or prev. rollback raises ValueError when no kept image is older than the running one. It also raises ValueError when the tag to is not on the server.

Before it switches, rollback tags the running image prev. prev always names the image that ran before the current one. rollback(host, 'prev') undoes the last deploy or rollback. A rollback moves only the tags latest and prev. The running image keeps its timestamp. rollback(host, to=<its tag>) returns to it after any number of rollbacks. vpseasy 0.0.25 and earlier tagged the replaced image undo. vpseasy no longer writes or reads that tag. The restart is docker compose up -d --no-build --force-recreate for the one service. Compose uses the retagged image and does not build.

A rollback restores the image and nothing else. Files that sync copied to the server stay as the last deploy left them. Examples are the Compose file, the Caddyfile and bind-mounted folders. Volumes and databases also stay as they were. The next deploy builds from your source again. It keeps the rolled-back image like any other.


source

rollback

def rollback(
    host, to:NoneType=None, path:str='/srv/app', svc:str='app', img:NoneType=None, user:str='deploy',
    key:NoneType=None, name:NoneType=None, port:int=22, key_pass:NoneType=None, password:NoneType=None,
    verbose:bool=True
):

Point svc at the kept image to, or the newest kept image older than the running one, tag the running one prev, restart svc, and return the tag.


source

keep_image

def keep_image(
    host, path:str='/srv/app', svc:str='app', img:NoneType=None, keep:int=3, prev:NoneType=None, **kw
):

Tag the image that svc runs, and the image prev when given, with their build times. Tag prev as prev. Delete the timestamped tags past the newest keep, except those of the two images. Return the running tag.


source

kept_images

def kept_images(
    host, path:str='/srv/app', svc:str='app', img:NoneType=None, **kw
)->list:

Return the timestamped images kept of svc on host, as (tag, image id) pairs, newest first.

class FakeDocker:
    'A fake server. The commands that `run_ssh` sends read and change a table of images, their build times and their tags.'
    def __init__(self, tags=None):
        self.tags, self.cmds, self.kw, self.n = dict(tags or {}), [], [], 0
        self.imgs = {i: '' for i in self.tags.values()}
    def __call__(self, host, *cmds, **kw):
        self.kw.append(kw); out = []
        for c in cmds:
            self.cmds.append(c); w = c.replace("'", '').split()
            if c.startswith('docker image inspect'):
                i = self.tags.get(w[5], w[5] if w[5] in self.imgs else '')
                out.append(self.imgs.get(i, '') if 'Created' in w[4] else i)
            elif c.startswith('docker image ls'): out += [f'{t.split(":")[1]} {i}' for t, i in self.tags.items() if t.split(':')[0] == w[3]]
            elif c.startswith('docker image prune'): self.imgs = {i: t for i, t in self.imgs.items() if i in self.tags.values()}
            elif c.startswith('docker tag'): self.tags[w[3]] = self.tags.get(w[2], w[2])
            elif c.startswith('docker rmi'): [self.tags.pop(t) for t in w[2:] if ':' in t]
            elif c.startswith('ls '): out.append(w[1])
            elif '--build' in c:
                self.n += 1; i = self.tags['app-app:latest'] = f'sha256:new{self.n}'
                self.imgs[i] = f'2026-10-{10+self.n:02d}T00:00:00.123456789Z'
        return '\n'.join(out)

@contextmanager
def fake_server(fd, ts):
    'Send `run_ssh` and `sync` to `fd`, and make `time.strftime` return the stamps in `ts` in turn.'
    g = rollback.__globals__; o = {k: g[k] for k in ('run_ssh', 'sync')}
    g['run_ssh'], g['sync'] = fd, lambda *a, **k: 0
    try:
        with patch('time.strftime', side_effect=ts): yield
    finally: g.update(o)

fd = FakeDocker()
ts = [f'2026101{i}T000000' for i in range(10)]
with fake_server(fd, ts):
    deploy('h', key='/k', port=2222)
    test_eq(fd.tags, {'app-app:latest': 'sha256:new1', 'app-app:20261011T000000': 'sha256:new1'})
    for _ in range(4): deploy('h', key='/k', port=2222)
    assert all(k['port'] == 2222 for k in fd.kw)
    test_eq(kept_images('h'), [('20261015T000000', 'sha256:new5'), ('20261014T000000', 'sha256:new4'), ('20261013T000000', 'sha256:new3')])
    test_eq(fd.tags['app-app:prev'], 'sha256:new4')
    assert any(c.startswith('docker image prune -f') for c in fd.cmds)
    test_eq(rollback('h', verbose=False), '20261014T000000')
    test_eq((fd.tags['app-app:latest'], fd.tags['app-app:prev']), ('sha256:new4', 'sha256:new5'))
    assert fd.cmds[-1] == 'cd /srv/app && docker compose up -d --no-build --force-recreate app'
    test_eq(rollback('h', verbose=False), '20261013T000000')
    test_eq(rollback('h', to='20261015T000000', verbose=False), '20261015T000000')
    test_fail(lambda: rollback('h', to='20250101T000000', verbose=False), contains='not on h')
    deploy('h', keep=0, prune=False)
    test_eq(len(kept_images('h')), 3)

fd = FakeDocker({'web-site:latest': 'sha256:a', 'web-site:20261001T000000': 'sha256:a'})
with fake_server(fd, ts):
    test_fail(lambda: rollback('h', path='/srv/web', svc='site', verbose=False), contains='no kept image')
    test_eq(keep_image('h', '/srv/web', 'site'), '20261001T000000')
    test_eq(_img('/srv/My.App', 'app', None), 'myapp-app')
    test_eq(_img('/srv/_web', 'app', None), 'web-app')
fd = FakeDocker({'app-app:latest': 'sha256:b', 'app-app:20261001T000000': 'sha256:a'})   # a running image from before 0.0.26 has no timestamp
_fd = lambda host, *c, **kw: fd(host, *c, **kw) + ' ;; Warning: Permanently added 1.2.3.4'   # ssh's stderr on a first connection
with fake_server(_fd, ['20261002T000000']):
    test_eq(rollback('h', verbose=False), '20261001T000000')
    test_eq((fd.tags['app-app:latest'], fd.tags['app-app:prev'], fd.tags['app-app:20261002T000000']), ('sha256:a', 'sha256:b', 'sha256:b'))
print('keep_image and rollback OK')
fd = FakeDocker()
def reachable(keep=3):
    'Every tagged image exists, and so do the newest `keep` builds, `latest` and `prev`.'
    built = sorted(fd.imgs.values(), reverse=True)
    newest = {f'sha256:new{n}' for n in range(max(fd.n - keep, 0) + 1, fd.n + 1)}
    assert set(fd.tags.values()) <= set(fd.imgs), (fd.tags, fd.imgs)
    assert newest <= set(fd.imgs), (newest, fd.imgs)
    assert all(i in {i for t, i in kept_images('h')} for i in newest), (newest, fd.tags)
cur = lambda: (fd.tags['app-app:latest'], fd.tags.get('app-app:prev'))
with fake_server(fd, ts):
    for _ in range(3): deploy('h'); reachable()
    test_eq(cur(), ('sha256:new3', 'sha256:new2'))
    test_eq(kept_images('h'), [('20261013T000000', 'sha256:new3'), ('20261012T000000', 'sha256:new2'), ('20261011T000000', 'sha256:new1')])
    test_eq(rollback('h', verbose=False), '20261012T000000'); reachable(); test_eq(cur(), ('sha256:new2', 'sha256:new3'))
    test_eq(rollback('h', verbose=False), '20261011T000000'); reachable(); test_eq(cur(), ('sha256:new1', 'sha256:new2'))
    test_fail(lambda: rollback('h', verbose=False), contains='no kept image')
    test_eq(rollback('h', 'prev', verbose=False), 'prev'); reachable(); test_eq(cur(), ('sha256:new2', 'sha256:new1'))
    test_eq(rollback('h', 'prev', verbose=False), 'prev'); reachable(); test_eq(cur(), ('sha256:new1', 'sha256:new2'))
    test_eq(rollback('h', '20261013T000000', verbose=False), '20261013T000000'); reachable(); test_eq(cur(), ('sha256:new3', 'sha256:new1'))
    deploy('h'); reachable(); test_eq(cur(), ('sha256:new4', 'sha256:new3'))
    test_eq(set(fd.imgs), {f'sha256:new{n}' for n in range(2, 5)})   # new1 fell out of the newest three and was neither latest nor prev
    rollback('h', '20261012T000000', verbose=False); deploy('h'); reachable(); test_eq(cur(), ('sha256:new5', 'sha256:new2'))
    test_eq(set(fd.imgs), {'sha256:new2', 'sha256:new3', 'sha256:new4', 'sha256:new5'})   # new2 stays as prev past the newest three
fd = FakeDocker({'app-app:latest': 'sha256:a'}); fd.imgs['sha256:a'] = '2026-10-01T00:00:00Z'   # a build whose restart fails still gets its tag, and the one before it `prev`
def _fail(host, *c, **kw):
    r = fd(host, *c, **kw)
    if any('--build' in x for x in c): raise IOError('port is already allocated')
    return r
with fake_server(_fail, ts):
    test_fail(lambda: deploy('h'), contains='port is already allocated')
    test_eq((cur(), sorted(t for t in fd.tags if t[8:9].isdigit())), (('sha256:new1', 'sha256:a'), ['app-app:20261001T000000', 'app-app:20261011T000000']))
fd = FakeDocker()   # builds sharing a second (reproducible builds) get distinct tags
_c = FakeDocker.__call__
def _same(host, *c, **kw):
    r = _c(fd, host, *c, **kw)
    for i in fd.imgs: fd.imgs[i] = '1980-01-01T00:00:00Z'
    return r
with fake_server(_same, ts):
    for _ in range(4): deploy('h'); reachable()
    test_eq([t for t, _ in kept_images('h')], ['19800101T000003', '19800101T000002', '19800101T000001'])
fd = FakeDocker({'app-app:latest': 'sha256:c', 'app-app:20261003T000000': 'sha256:c', 'app-app:20261002T000000': 'sha256:b', 'app-app:20261001T000000': 'sha256:b', 'app-app:20260930T000000': 'sha256:a'})
with fake_server(fd, ts): keep_image('h', keep=3)
test_eq(set(fd.tags.values()), {'sha256:a', 'sha256:b', 'sha256:c'})   # an image tagged twice takes one of the three places
print('rollback sequences OK')

After a deploy

wait_http requests url until it answers 200. It tries up to tries times, poll seconds apart. Each request times out after timeout seconds. It returns True when the URL answers 200 and False when the tries run out. Use it after deploy and before anything that needs the new version to be live, such as purging a CDN cache. ua sets the User-Agent header. Cloudflare refuses some library agents. Give ua a name of your own. wait_http verifies HTTPS against the operating system trust store through truststore. A root certificate added there, such as the certificate of a company proxy, verifies as it does in a browser. wait_http prints an error message when it differs from the previous one. A wait that does not succeed shows why.

server_health reads the state of a server over one SSH call. It returns an AttrDict with these fields. ram and used are memory in MB. swap and swap_used are swap in MB. pct is the percentage of RAM in use, counting swap. load is the three load averages as one string. disk is the use of the root disk. containers has one line for each container with its memory and CPU from docker stats.


source

server_health

def server_health(
    host, user:str='deploy', key:NoneType=None, name:NoneType=None, port:int=22, key_pass:NoneType=None,
    password:NoneType=None
)->fastcore.basics.AttrDict:

Return memory and swap in MB, RAM use with swap in percent, the load averages, root disk use and each container from host.


source

wait_http

def wait_http(
    url, ua:str='vpseasy', tries:int=40, poll:int=15, timeout:int=10
)->bool:

Ask for url until it answers 200, up to tries times poll seconds apart, printing each new error, and return whether it did.

import http.server, threading
class _H(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200 if self.headers['User-Agent'] == 'me' else 403); self.end_headers()
    def log_message(self, *a): pass
_srv = http.server.HTTPServer(('127.0.0.1', 0), _H); threading.Thread(target=_srv.serve_forever, daemon=True).start()
_u = f'http://127.0.0.1:{_srv.server_port}/health'
test_eq((wait_http(_u, ua='me', tries=1), wait_http(_u, tries=2, poll=0), wait_http('http://127.0.0.1:9/', tries=1)), (True, False, False))
_srv.shutdown()

import io, ssl, urllib.error, urllib.request
from contextlib import redirect_stdout
from unittest import mock
_cert = urllib.error.URLError(ssl.SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] unable to get local issuer certificate'))
with mock.patch.object(urllib.request, 'urlopen', side_effect=_cert) as _uo, mock.patch.object(time, 'sleep') as _sl:
    with redirect_stdout(io.StringIO()) as _p: test_eq(wait_http('https://e.test/', tries=3, poll=5), False)
test_eq((_uo.call_count, _sl.call_count, _p.getvalue().count('CERTIFICATE_VERIFY_FAILED')), (3, 2, 1))
import truststore; test_eq(type(_uo.call_args.kwargs['context']), truststore.SSLContext)

_so = '3820 2410\n4095 512\n0.52 0.40 0.31\n12G/38G (33%)\napp-app-1 1.9GiB / 3GiB 2.1%\ncaddy 40MiB / 256MiB 0.0%'
g = server_health.__globals__; _o = g['run_ssh']; g['run_ssh'] = lambda host, *c, **kw: _so
try: h = server_health('h')
finally: g['run_ssh'] = _o
test_eq((h.ram, h.used, h.swap, h.swap_used, h.pct, h.load, h.disk), (3820, 2410, 4095, 512, 76, '0.52 0.40 0.31', '12G/38G (33%)'))
test_eq(h.containers, ['app-app-1 1.9GiB / 3GiB 2.1%', 'caddy 40MiB / 256MiB 0.0%'])
_w = "\n".join(_so.splitlines()[:4]) + " ;; Warning: Permanently added '1.2.3.4' (ED25519) to the list of known hosts."
g['run_ssh'] = lambda host, *c, **kw: _w
try: h = server_health('h')
finally: g['run_ssh'] = _o
test_eq((h.disk, h.containers), ('12G/38G (33%)', []))
print('wait_http and server_health OK')
wait_http http://127.0.0.1:33691/health: HTTP Error 403: Forbidden
wait_http http://127.0.0.1:9/: <urlopen error [Errno 111] Connection refused>
wait_http and server_health OK

Lightsail live test

The next cell creates real AWS resources. It runs only when the environment variable VPSEASY_LIVE has a non-empty value. It creates a nano_3_2 instance with vps_init user data and no snapshot. It waits for the setup, then checks that the deploy user and Docker exist. It creates a bucket and an access key. At the end it deletes the instance, its static IP and the bucket. Run it with VPSEASY_LIVE=1 AWS_PROFILE=<sso profile> uv run nbdev-test --path nbs/00_core.ipynb.

if os.environ.get('VPSEASY_LIVE'):
    import secrets
    ln, bn = 'vpseasy-live-test', f'vpseasy-live-test-bkt-{secrets.token_hex(3)}'
    lsl, kp = Lightsail(), gen_key('vpseasy-live-test', key_dir=tempfile.mkdtemp())
    try:
        r = lsl.create(ln, bundle='nano_3_2', cloud_init=vps_init(ln, kp.pub_str), snapshots=None)
        print('instance ip', r.ip)
        wait_ready(r.ip, k=kp.key, tout=600, verbose=True)
        print(run_ssh(r.ip, 'id && docker --version', key=kp.key))
        b = lsl.bucket(bn)
        bk = lsl._c.get_buckets(bucketName=bn)['buckets'][0]
        print('bucket endpoint', b.endpoint, 'reported url', bk['url'], 'location', bk['location'])
    finally:
        lsl.delete(ln)
        with suppress(lsl._c.exceptions.NotFoundException):
            for k in lsl._c.get_bucket_access_keys(bucketName=bn)['accessKeys']:
                lsl._c.delete_bucket_access_key(bucketName=bn, accessKeyId=k['accessKeyId'])
            lsl._c.delete_bucket(bucketName=bn, forceDelete=True)
    test_eq([s for s in lsl.servers() if s['name'] == ln], [])

SSH key helpers

load_pub_keys reads public keys from files and returns their text as a list, ready to pass as pub_keys to vps_init or multi_init. With no arguments it reads every ~/.ssh/id_*.pub. Paths that do not exist are skipped. To make a new key pair instead, use gen_key from the cloud-init section.


source

load_pub_keys

def load_pub_keys(
    paths:NoneType=None
)->list:

Return the text of each SSH public key file in paths, or of every ~/.ssh/id_*.pub if paths is None.

keys = load_pub_keys()
print(f'Found {len(keys)} local SSH key(s)')

_f = Path(tempfile.mktemp(suffix='.pub'))
_f.write_text('ssh-ed25519 TESTKEY comment')
assert load_pub_keys([str(_f)]) == ['ssh-ed25519 TESTKEY comment']
_f.unlink()
assert load_pub_keys(['/no_such_key.pub']) == []
print('load_pub_keys OK')

_d = Path(tempfile.mkdtemp())
kp = gen_key('testkey', key_dir=_d)
assert kp.key.exists() and kp.pub.exists()
assert kp.pub_str[0].startswith('ssh-ed25519')
kp2 = gen_key('testkey', key_dir=_d)
assert kp2.pub_str[0].startswith('ssh-ed25519')
import shutil; shutil.rmtree(_d)
print('gen_key OK')
Found 0 local SSH key(s)
load_pub_keys OK
gen_key OK

Integration tests: SSH and verification helpers

These cells need Multipass and do not run when the docs are built. They launch a small Ubuntu VM with a key generated by multi_init, then try wait_ssh, chk_cloud_init, run_ssh, deploy_mp and sync with each of its filter options, and delete the VM at the end.

# --- setup: auto-generate key pair, inject via multi_init, launch VM ---
_VM = 'testvm'
mp = Multipass()
try: mp.rm(_VM)
except: pass

ci = multi_init(_VM, docker=False) # generates ~/.ssh/fastops-vpstest{,.pub}
vm = mp.launch(_VM, image='24.04', cpus=1, memory='512M', disk='5G', cloud_init=ci)
ip = mp.ip(vm.name)
_key = vm.key
print(f'VM at {ip}, key: {_key}')
Retrieving image: 100%Verifying image:  - Preparing image for testvm  Configuring testvm  Starting testvm  Waiting for initialization to complete  Launched: testvm
VM at 192.168.2.66, key: /Users/71293/.ssh/testvm
# wait_ssh / chk_cloud_init / run_ssh
assert wait_ssh(ip, k=_key, tout=30) is True; print('wait_ssh OK')
status = chk_cloud_init(ip, name=_VM, verbose=True)
assert status in ('done', 'running'), f'unexpected: {status!r}'; print(f'chk_cloud_init: {status}')
assert run_ssh(ip, 'echo hi', key=_key).strip() == 'hi'; print('run_ssh OK')
SSH to host 192.168.2.66 check succeeded
wait_ssh OK
Resolved SSH key from name slug: /Users/71293/.ssh/testvm
Ran SSH command on 192.168.2.66: test -f /var/lib/cloud/instance/boot-finished && echo 'status: done' || echo 'status: running' → (0, 'status: done')
chk_cloud_init: done
run_ssh OK
# sync: full dir / exclude / include (whitelist)
_src = Path(tempfile.mkdtemp())
(_src/'a.txt').write_text('hello')
(_src/'b.log').write_text('log')
(_src/'sub').mkdir(); (_src/'sub'/'c.txt').write_text('sub')

deploy_mp(_VM, _src, path='/tmp/app')  # sanity check deploy_mp with build=False
assert run_ssh(ip, 'ls /tmp/app', key=_key).split() == ['a.txt', 'b.log', 'sub']

sync(ip, _src, '/tmp/t1', key=_key)
assert run_ssh(ip, 'cat /tmp/t1/a.txt', key=_key).strip() == 'hello'; print('sync full OK')

sync(ip, _src, '/tmp/t2', key=_key, exclude=['*.log'])
assert run_ssh(ip, 'ls /tmp/t2', key=_key).split() == ['a.txt', 'sub']; print('sync exclude OK')

sync(ip, _src, '/tmp/t3', key=_key, include=['a.txt'])
assert run_ssh(ip, 'ls /tmp/t3', key=_key).strip() == 'a.txt'; print('sync include OK')

sync(ip, _src, '/tmp/t4', key=_key, include=['sub/'])
assert run_ssh(ip, 'cat /tmp/t4/sub/c.txt', key=_key).strip() == 'sub'; print('sync include-dir OK')
Resolved SSH key from name slug: /Users/71293/.ssh/testvm
Ran SSH command on 192.168.2.66: [ -d /tmp/app -a -w /tmp/app ] || sudo  sh -c 'mkdir -p /tmp/app && chown deploy:deploy /tmp/app' → (0, '')
Ensured remote path /tmp/app exists and is writable by deploy
Resolved SSH key from name slug: /Users/71293/.ssh/testvm
Running rsync: rsync -azh --info=progress2 --delete -e ssh -o StrictHostKeyChecking=accept-new -i /Users/71293/.ssh/testvm /var/folders/kg/9vdw4mdd1fs58svgh4k1qhr09x7dqh/T/tmp85dq_szb/ deploy@192.168.2.66:/tmp/app/
             11 100%    5.86kB/s    0:00:00 (xfr#3, to-chk=0/5)
Rsync completed successfully
Resolved SSH key from name slug: /Users/71293/.ssh/testvm
Docker check failed:  ;; bash: line 1: docker: command not found
             11 100%    5.86kB/s    0:00:00 (xfr#3, to-chk=0/5)
sync full OK
              8 100%    2.93kB/s    0:00:00 (xfr#2, to-chk=0/4)
sync exclude OK
              5 100%    0.00kB/s    0:00:00 (xfr#1, to-chk=0/3)
sync include OK
              3 100%    0.00kB/s    0:00:00 (xfr#1, to-chk=0/3)
sync include-dir OK
# extra= forwards arbitrary rsync flags. str and list both accepted via listify().
sync(ip, _src, '/tmp/t5', key=_key, extra='--checksum')
assert run_ssh(ip, 'cat /tmp/t5/a.txt', key=_key).strip() == 'hello'; print('sync extra=str (--checksum, hash-match) OK')

sync(ip, _src, '/tmp/t6', key=_key, extra=['--ignore-times', '--partial'])
assert run_ssh(ip, 'cat /tmp/t6/a.txt', key=_key).strip() == 'hello'; print('sync extra=list (--ignore-times re-copies all) OK')

# extra= composes with include/exclude
sync(ip, _src, '/tmp/t7', key=_key, extra='--checksum', exclude=['*.log'])
assert run_ssh(ip, 'ls /tmp/t7', key=_key).split() == ['a.txt', 'sub']; print('sync extra + exclude OK')
             11 100%    5.86kB/s    0:00:00 (xfr#3, to-chk=0/5)
sync extra=str (--checksum, hash-match) OK
             11 100%    5.86kB/s    0:00:00 (xfr#3, to-chk=0/5)
sync extra=list (--ignore-times re-copies all) OK
              8 100%    2.93kB/s    0:00:00 (xfr#2, to-chk=0/4)
sync extra + exclude OK
# --- teardown ---
mp.rm(_VM); print('VM removed')
VM removed

Docker Compose helpers

Most small web apps deployed with vpseasy run as the same group of containers. The app container is the app itself. A Caddy container is the web server in front of it. A cloudflared container, usually present, connects to a Cloudflare tunnel. With the tunnel, the server needs no open web ports. The containers share a network named web. Caddy keeps its certificates and settings in two named volumes, caddy_data and caddy_config. caddy_stack writes the Compose file for this group in one call.

caddy_stack takes the domain and a Dockerfile object from dockeasy, such as fasthtml_app(). It saves Dockerfile, Caddyfile and docker-compose.yml into root, or into the current directory when you omit root. It returns the Compose object. vols are container directories whose contents stay on the disk of the server. vols_to_binds turns each one into a bind mount from a folder of the same name beside the Compose file. For example, /app/data is stored in ./data. The app reads environment variables from env_file, which is .env by default. cloudflared=False leaves the tunnel out and makes Caddy listen on ports 80 and 443. conf puts the Caddyfile at another path. Other keyword arguments go to caddy_svc from dockeasy, for example email= or dns=.

app_kw, caddy_kw and cloudflared_kw add settings to one service each, such as mem_limit='3g' or init=True. A volumes list in them is added to the volumes of the service. It does not replace them. For example, caddy_kw=dict(volumes=['./static:/srv/static:ro']) lets Caddy serve files from the deploy folder. Pass your own dockeasy Caddyfile as caddyfile to write it instead of the Caddyfile built from the options. Pass write_caddyfile=False to leave the Caddyfile alone. Without conf, the Caddyfile is in root beside the Compose file and is mounted as ./Caddyfile. The stack works wherever root is. The next section covers the litestream argument.

The caddy_stack call without root shows the Compose file for a FastHTML app with one data volume. It saves the files in the current directory.


source

caddy_stack

def caddy_stack(
    domain, df, vols:NoneType=None, env_file:str='.env', cloudflared:bool=True, root:NoneType=None,
    conf:NoneType=None, litestream:NoneType=None, app_kw:NoneType=None, caddy_kw:NoneType=None,
    cloudflared_kw:NoneType=None, caddyfile:NoneType=None, write_caddyfile:bool=True, **kw
):

Build a Compose file with the app, Caddy, and optionally cloudflared and Litestream, saving it with its Dockerfile and Caddyfile in root.


source

vols_to_binds

def vols_to_binds(
    vols
):

Turn container paths such as /app/data into Compose bind mounts such as ./data:/app/data.

assert vols_to_binds(['/app/data', '/app/backups']) == ['./data:/app/data', './backups:/app/backups']
assert vols_to_binds('/app/data') == ['./data:/app/data']
print('vols_to_binds OK')

_d = Path(tempfile.mkdtemp())
c = caddy_stack('myapp.example.com', fasthtml_app(), vols=['/app/data'], root=_d, conf=str(_d/'Caddyfile'))
d = c.to_dict()
assert set(d['services']) == {'app', 'caddy', 'cloudflared'}
assert 'web' in d['networks']
assert 'caddy_data' in d['volumes'] and 'caddy_config' in d['volumes']
assert d['services']['app']['volumes'] == ['./data:/app/data']
assert (_d/'Dockerfile').exists() and (_d/'docker-compose.yml').exists() and (_d/'Caddyfile').exists()
print('caddy_stack OK')
vols_to_binds OK
caddy_stack OK
caddy_stack('myapp.example.com', fasthtml_app(), vols=['/app/data'])
services:
  app:
    build: .
    volumes:
    - ./data:/app/data
    env_file:
    - .env
    restart: unless-stopped
    networks:
    - web
  caddy:
    image: caddy:2
    depends_on:
    - app
    volumes:
    - ./Caddyfile:/etc/caddy/Caddyfile
    - caddy_data:/data
    - caddy_config:/config
    networks:
    - web
    restart: unless-stopped
  cloudflared:
    image: cloudflare/cloudflared:latest
    command: tunnel --no-autoupdate run --url http://caddy
    environment:
    - TUNNEL_TOKEN=${CF_TUNNEL_TOKEN}
    networks:
    - web
    restart: unless-stopped
networks:
  web: null
volumes:
  caddy_data: null
  caddy_config: null
_d = Path(tempfile.mkdtemp())
c = caddy_stack('ex.com', fasthtml_app(), vols=['/app/data'], root=_d, app_kw=dict(init=True, mem_limit='3g'),
                caddy_kw=dict(mem_limit='256m', volumes=['./static:/srv/static:ro']), cloudflared_kw=dict(mem_limit='256m'),
                caddyfile=Caddyfile('ex.com').cloudflared().encode('gzip'))
s = c.to_dict()['services']
test_eq(list(s['app']), ['build', 'volumes', 'env_file', 'restart', 'networks', 'init', 'mem_limit'])
test_eq(s['caddy']['volumes'], ['./Caddyfile:/etc/caddy/Caddyfile', 'caddy_data:/data', 'caddy_config:/config', './static:/srv/static:ro'])
test_eq((s['caddy']['mem_limit'], s['cloudflared']['mem_limit']), ('256m', '256m'))
assert '\tencode gzip' in (_d/'Caddyfile').read_text()
(_d/'Caddyfile').write_text('mine')
caddy_stack('ex.com', fasthtml_app(), root=_d, write_caddyfile=False)
test_eq((_d/'Caddyfile').read_text(), 'mine')
print('caddy_stack service settings OK')

Litestream

Litestream copies every change to a SQLite database into an S3-compatible storage bucket. It can restore the database from that copy. The bucket can come from Lightsail.bucket, AWS S3 or Cloudflare R2.

litestream_conf writes the Litestream config file and returns its text. dbs are absolute paths inside the container. A relative path raises ValueError. If you pass vols, each database must sit inside one of them. Otherwise litestream_conf raises ValueError, because the Litestream container cannot see the database. Each database is stored at <prefix>/<db path> in the bucket. Two databases with the same file name do not collide. region is auto by default. snapshot sets the snapshot interval, 24h by default. retention sets how long Litestream keeps snapshots, 72h by default. The config also sets a validation interval of 12 hours. Litestream reads the access key from LITESTREAM_ACCESS_KEY_ID and LITESTREAM_SECRET_ACCESS_KEY. Put both in .env. The config format was tested against litestream/litestream:0.5 (v0.5.17). Litestream ignores config keys that it does not recognise, without a warning.

litestream_svc returns the arguments for a Litestream service in Compose.svc(). It mounts the volumes of the app and the config file. It runs replicate unless you pass another command as cmd.

You will rarely call either function directly. caddy_stack(..., litestream=dict(dbs=..., bucket=..., endpoint=..., region=..., prefix=...)) writes the config and adds the services. A one-shot litestream-restore service runs restore -if-db-not-exists -if-replica-exists. That command restores a database only when the file is missing and a copy exists in the bucket. The app waits for the restore service to finish successfully. A fresh server gets its data back before the app can create an empty database. The long-running litestream service starts after the app. With more than one database, each database has its own restore service.


source

litestream_svc

def litestream_svc(
    vols:str='/app/data', conf:str='litestream.yml', env_file:str='.env', image:str='litestream/litestream:0.5',
    cmd:str='replicate', restart:str='unless-stopped', **kw
):

Return Compose.svc() arguments for a Litestream container that mounts the app volumes and the config.


source

litestream_conf

def litestream_conf(
    dbs, bucket, endpoint:NoneType=None, region:str='auto', prefix:NoneType=None, conf:str='litestream.yml',
    retention:str='72h', snapshot:str='24h', vols:NoneType=None
):

Write a Litestream 0.5 config that copies each SQLite database to <prefix>/<db path> in an S3-compatible bucket, and return its text.

_d = Path(tempfile.mkdtemp())
y = litestream_conf(['/app/data/palana.db'], 'lh-backups', endpoint='https://s3.ap-southeast-2.amazonaws.com',
                    region='ap-southeast-2', prefix='littlehours', conf=_d/'litestream.yml')
assert 'replica:' in y and 'replicas:' not in y
assert 'path: littlehours/app/data/palana.db' in y and 'restore-if-db-not-exists' not in y
y3 = litestream_conf(['/app/data/a.db', '/app/cache/a.db'], 'b', conf=_d/'y3.yml')
assert 'path: app/data/a.db' in y3 and 'path: app/cache/a.db' in y3
assert '${LITESTREAM_ACCESS_KEY_ID}' in y and '${LITESTREAM_SECRET_ACCESS_KEY}' in y
test_eq((_d/'litestream.yml').read_text(), y)
y2 = litestream_conf(['/app/data/a.db'], 'b', endpoint='https://acct.r2.cloudflarestorage.com', conf=_d/'l.yml')
assert 'region: auto' in y2 and 'endpoint: https://acct.r2.cloudflarestorage.com' in y2
test_fail(lambda: litestream_conf(['data/a.db'], 'b'), contains='absolute')
test_fail(lambda: litestream_conf(['/tmp/a.db'], 'b', vols=['/app/data'], conf=_d/'x.yml'), contains='/tmp/a.db')
test_fail(lambda: litestream_conf(['/app/database.db'], 'b', vols=['/app/data'], conf=_d/'x.yml'), contains='/app/database.db')

s = litestream_svc()
test_eq(s['image'], 'litestream/litestream:0.5')
test_eq(s['command'], 'replicate')
test_eq(s['volumes'], ['./data:/app/data', './litestream.yml:/etc/litestream.yml'])
test_eq(s['env_file'], ['.env'])
assert 'env_file' not in litestream_svc(env_file=None)
_d = Path(tempfile.mkdtemp())
ls_kw = dict(dbs=['/app/data/palana.db'], bucket='lh-backups', endpoint='https://s3.ap-southeast-2.amazonaws.com', region='ap-southeast-2')
c = caddy_stack('lh.example.com', fasthtml_app(), vols=['/app/data'], root=_d, conf=_d/'Caddyfile', litestream=ls_kw)
d = c.to_dict()
svcs = d['services']
assert {'litestream', 'litestream-restore'} <= set(svcs)
test_eq(svcs['app']['depends_on'], {'litestream-restore': {'condition': 'service_completed_successfully'}})
test_eq(svcs['litestream-restore']['command'], 'restore -if-db-not-exists -if-replica-exists /app/data/palana.db')
test_eq(svcs['litestream-restore']['restart'], 'no')
test_eq(svcs['litestream']['command'], 'replicate')
test_eq(svcs['litestream']['depends_on'], ['app'])
test_eq(svcs['litestream']['volumes'], ['./data:/app/data', './litestream.yml:/etc/litestream.yml'])
assert (_d/'litestream.yml').exists()
assert "restart: 'no'" in str(c)
d2 = caddy_stack('lh.example.com', fasthtml_app(), vols=['/app/data'], root=_d, conf=_d/'Caddyfile',
                 litestream=ls_kw | dict(dbs=['/app/data/a.db', '/app/data/b.db'])).to_dict()['services']
test_eq(set(d2['app']['depends_on']), {'litestream-restore-app-data-a', 'litestream-restore-app-data-b'})
test_fail(lambda: caddy_stack('lh.example.com', fasthtml_app(), vols=['/app/data'], root=_d, conf=_d/'Caddyfile',
                              litestream=ls_kw | dict(dbs=['/srv/x.db'])), contains='/srv/x.db')
assert 'depends_on' not in caddy_stack('lh.example.com', fasthtml_app(), vols=['/app/data'], root=_d, conf=_d/'Caddyfile').to_dict()['services']['app']

source

mv_skill_md

def mv_skill_md(
    dry_run:bool=True, dir:NoneType=None
)->None:

Copy the bundled SKILL.md to .agents/skills/vpseasy/ and ~/.claude/skills/vpseasy/, or only print the targets if dry_run.

import io, sys, tempfile, os
_d = Path(tempfile.mkdtemp())
(_d/'SKILL.md').write_text('test-skill')   # provide a src so function doesn't bail early
_saved_cwd = os.getcwd(); os.chdir(_d)
_buf = io.StringIO(); sys.stdout, _saved = _buf, sys.stdout
mv_skill_md(dry_run=True, dir=str(_d))
sys.stdout = _saved; os.chdir(_saved_cwd)
_out = _buf.getvalue()
assert '.agents/skills/vpseasy/SKILL.md' in _out, _out
assert '.claude/skills/vpseasy/SKILL.md' in _out, _out
print('mv_skill_md dry_run OK')
mv_skill_md dry_run OK