CBSDfile hooks: pre/post actions

Hook types

CBSDfile supports hook functions that are automatically invoked at specific points in the lifecycle:

Hook When it runs
globals() Before processing any environment (global variables)
preup() Once, before starting to create all environments
preup_<name>() Before creating a specific environment <name>
postcreate_<name>() After creating the <name> environment
postdestroy_<name>() After destroying the <name> environment
postup() Once, after processing all environments

Execution order

  1. globals() — global variables
  2. preup() — global preparation step 3. For each environment
  3. preup_<name>() — specific preparation
  4. Environment creation
  5. postcreate_<name>() — post-install configuration
  6. postup() — finalization

Examples

Loading shared configuration

preup()
{
    # Load common config (e.g., IP addresses from an external file)
    . ../config
}

The ../config file may contain variables:

REDIS_RO_IP="10.0.0.20"
REDIS_RW_IP="10.0.0.21"

Post-install configuration inside a jail

postcreate_web1()
{
    jexec jname=${jname} /bin/sh <<EOF
sysrc nginx_enable="YES"
sysrc php_fpm_enable="YES"
pkg install -y redis
service nginx start
EOF
}

Checking dependencies before creation

preup_redis1()
{
    # Ensure that base-jail exists  
    if ! jstatus jname=base-jail > /dev/null 2>&1; then  
        echo "Creating base-jail..."  
        jcreate jname=base-jail jprofile=base runasap=1  
    fi  
}  

Post-create with file copying

postcreate_app1() {   
    # Copy configs into the jail   
    jscp src=./configs/nginx.conf dest=/usr/local/etc/nginx/nginx.conf jname=${jname}   

    # Copy scripts   
    jscp src=./scripts/setup.sh dest=/tmp/setup.sh jname=${jname}   
    jexec jname=${jname} /bin/sh /tmp/setup.sh  
}  

Variables available in hooks

Inside a hook body, the following are accessible:
- All variables from globals() and <type>_<name>() functions
- $jname — name of the current environment - $rc — return code of the last operation

Commands for execution inside environments

Command Description
jexec jname=<name> <command> Execute a command inside a jail
jscp src=<path> dest=<path> jname=<name> Copy a file from host to jail
bexec <name> <command> Execute a command inside a bhyve VM (via SSH)
bscp <name> <path> <path> Copy a file from host to bhyve VM (via SSH)

For bhyve VMs, the bexec command uses SSH. The bhyve_ssh_wait parameter (enabled by default) waits for the SSH connection to stabilize before execution.

Recommendations

  • preup() — for global preparation and loading shared configurations.
  • postcreate_<name>() — for post-install service configuration and package installation.
  • preup_<name>() — for dependency checks and preliminary preparation.
  • In postcreate, use jexec/bexec to run commands inside the environment and jscp/bscp to copy files.