Back to Deployer

API Reference

docs/api.md

8.0.416.4 KB
Original Source
<!-- DO NOT EDIT THIS FILE! --> <!-- Instead edit src/functions.php --> <!-- Then run bin/docgen -->

API Reference

host()

php
host(string ...$hostname): Host|ObjectProxy

Define one or more hosts for deployment.

php
host('example.org');
host('prod.example.org', 'staging.example.org');

Inside a task, returns the Host instance for the given alias:

php
task('test', function () {
    $port = host('example.org')->get('port');
});

localhost()

php
localhost(string ...$hostnames): Localhost|ObjectProxy

Define a local host. Commands run on the local machine instead of over SSH.

php
localhost('ci'); // Alias and hostname will be "ci".

currentHost()

php
currentHost(): Host

Return the host the current task is running on.

php
task('whoami', function () {
    writeln(currentHost()->getAlias());
});

select()

php
select(string $selector): array

Return hosts matching a selector expression.

php
on(select('stage=prod, role=db'), function (Host $host) {
    // Runs on hosts tagged stage=prod AND role=db.
});

selectedHosts()

php
selectedHosts(): array

Return the hosts the user picked on the command line.

import()

php
import(string $file): void

Import another recipe (PHP or MAML).

Built-in recipe/* and contrib/* paths are already on PHP's include path, so they can be imported by relative path. Use __DIR__ for files inside your own project.

php
import('recipe/common.php');                  // built-in recipe
import('contrib/rsync.php');                  // contrib recipe
import(__DIR__ . '/config/hosts.maml');       // local file

desc()

php
desc(?string $title = null): ?string

Set the description for the next task defined with task().

php
desc('Restart php-fpm');
task('restart', function () {
    run('sudo systemctl restart php-fpm');
});

Calling desc() with no argument returns the pending description.

task()

php
task(string $name, callable|array|null $body = null): Task

Define a task, or return an already defined one.

Pass a callback to define a single task:

php
task('deploy:run', function () {
    run('echo deploying');
});

Pass an array of task names to define a group task:

php
task('deploy', ['deploy:update_code', 'deploy:vendors', 'deploy:symlink']);

Pass only the name to fetch an existing task:

php
task('deploy')->desc('Run full deploy');
ArgumentTypeComment
$namestringTask name.
$bodycallable or array or nullCallback, list of task names, or null to fetch an existing task.

before()

php
before(string $task, string|callable $do): ?Task

Run a task (or callback) before another task.

php
before('deploy:symlink', 'deploy:cache:warmup');

before('deploy:symlink', function () {
    run('echo about to symlink');
});
ArgumentTypeComment
$taskstringName of the task to attach the hook to.
$dostring or callableTask name or callback to run.

after()

php
after(string $task, string|callable $do): ?Task

Run a task (or callback) after another task.

php
after('deploy:symlink', 'deploy:cleanup');

after('deploy:failed', function () {
    run('echo something went wrong');
});
ArgumentTypeComment
$taskstringName of the task to attach the hook to.
$dostring or callableTask name or callback to run.

fail()

php
fail(string $task, string|callable $do): ?Task

Run a task (or callback) when another task fails.

Calling fail() again for the same task replaces the previous handler.

php
fail('deploy', 'deploy:unlock');

fail('deploy', function () {
    run('echo rollback triggered');
});
ArgumentTypeComment
$taskstringName of the task whose failure triggers $do.
$dostring or callableTask name or callback to run on failure.

option()

php
option(string $name, $shortcut = null, ?int $mode = null, string $description = '', $default = null): void

Add a CLI option to the dep binary.

php
use Symfony\Component\Console\Input\InputOption;

option('tag', null, InputOption::VALUE_REQUIRED, 'Release tag');

task('deploy', function () {
    $tag = input()->getOption('tag');
});
ArgumentTypeComment
$namestringOption name (long form, no leading dashes).
$shortcutstring or array or nullSingle-letter shortcut, `
$modeint or nullOne of the InputOption::VALUE_* constants.
$descriptionstringHelp text shown in dep --help.
$defaultstring or string[] or int or bool or nullDefault value (must be null for VALUE_NONE).

cd()

php
cd(string $path): void

Change the current working directory.

Both cd() and the cwd: argument of run() change the working directory for executed commands. The difference: cd() changes it for the rest of the current task, while cwd: overrides it for a single run() call only.

php
set('deploy_path', '~/deployer.org');

task('task1', function () {
    cd('{{deploy_path}}');

    run('pwd');
    // output: /home/deployer/deployer.org

    run('pwd', cwd: '/usr'); // Override working dir for this run only.
    // output: /usr

    run('pwd');
    // output: /home/deployer/deployer.org
});

Note that cd() only changes the working directory within a single task. The next task starts fresh.

php
task('task2', function () {
    run('pwd'); // cd from previous task is not used.
    // output: /home/deployer
});

task('all', [
   'task1',
   'task2',
]);

become()

php
become(string $user): \Closure

Switch the user that run() uses for subsequent commands.

Returns a closure that restores the previous user when called.

php
$restore = become('deployer');
run('whoami'); // deployer
$restore();

within()

php
within(string $path, callable $callback): mixed

Run a callback inside a working directory, then restore the previous one.

Use this when you need a scoped cd() that does not leak to the rest of the task.

php
within('{{release_path}}', function () {
    run('composer install');
});

run()

php
run(
    string  $command,
    ?string $cwd = null,
    ?array  $env = null,
    #[\SensitiveParameter]
    ?array  $secrets = null,
    ?bool   $nothrow = false,
    ?bool   $forceOutput = false,
    ?int    $timeout = null,
    ?int    $idleTimeout = null,
): string 

Run a command on the current remote host and return its trimmed stdout.

php
run('echo hello world');
run('cd {{deploy_path}} && git status');
run('curl medv.io', timeout: 5);

$path = run('readlink {{deploy_path}}/current');
run("echo $path");

Pass secrets via %name% placeholders so they are redacted in logs:

php
run('curl -u admin:%token% https://api.example', secrets: ['token' => getenv('TOKEN')]);

Use the | quote filter to escape config values as shell arguments:

php
run('echo {{ message | quote }}');
run('grep -r {{ pattern | quote }} {{release_path}}');

To emit a literal {{, escape it with a backslash:

php
run('echo \{{not_replaced}}'); // outputs: {{not_replaced}}
ArgumentTypeComment
$commandstringCommand to run on the remote host.
$cwdstring or nullWorking directory for this run. Defaults to {{working_path}} (set by cd()).
$timeoutint or nullMax runtime in seconds (default: {{default_timeout}}, 300; null disables).
$idleTimeoutint or nullMax seconds without output before aborting.
$secretsarray or nullMap of %name% placeholders to redacted values.
$envarray or nullEnvironment variables: run('echo $KEY', env: ['KEY' => 'value']);
$forceOutputbool or nullPrint command output in real time.
$nothrowbool or nullReturn output instead of throwing on non-zero exit.

runLocally()

php
runLocally(
    string  $command,
    ?string $cwd = null,
    ?int    $timeout = null,
    ?int    $idleTimeout = null,
    #[\SensitiveParameter]
    ?array  $secrets = null,
    ?array  $env = null,
    ?bool   $forceOutput = false,
    ?bool   $nothrow = false,
    ?string $shell = null,
): string 

Run a command on the local machine and return its trimmed stdout.

php
$branch = runLocally('git rev-parse --abbrev-ref HEAD');
runLocally('npm run build', timeout: 600);
ArgumentTypeComment
$commandstringCommand to run locally.
$cwdstring or nullWorking directory for this run. Defaults to {{working_path}}.
$timeoutint or nullMax runtime in seconds (default 300, null disables).
$idleTimeoutint or nullMax seconds without output before aborting.
$secretsarray or nullMap of %name% placeholders to redacted values.
$envarray or nullEnvironment variables: runLocally('echo $KEY', env: ['KEY' => 'value']);
$forceOutputbool or nullPrint command output in real time.
$nothrowbool or nullReturn output instead of throwing on non-zero exit.
$shellstring or nullShell to run in. Default bash -s.

test()

php
test(string $command): bool

Return whether a shell test command succeeds on the remote host.

php
if (test('[ -d {{release_path}} ]')) {
    run('rm -rf {{release_path}}');
}

testLocally()

php
testLocally(string $command): bool

Return whether a shell test command succeeds on the local machine.

php
if (testLocally('[ -f .env ]')) {
    upload('.env', '{{release_path}}/.env');
}

on()

php
on($hosts, callable $callback): void

Run a callback on each given host.

php
on(select('stage=prod, role=db'), function (Host $host) {
    run('mysqldump app > /tmp/backup.sql');
});

on(host('example.org'), function (Host $host) {
    run('uptime');
});

on(Deployer::get()->hosts, function (Host $host) {
    run('uname -a');
});

invoke()

php
invoke(string $taskName): void

Run another task by name from inside the current task.

php
task('deploy', function () {
    invoke('deploy:update_code');
    invoke('deploy:symlink');
});

upload()

php
upload($source, string $destination, array $config = []): void

Upload files or directories to the current host via rsync.

To copy the contents of a directory, end the source with /:

php
upload('build/', '{{release_path}}/public'); // copies contents of build/
upload('build',  '{{release_path}}/public'); // copies the build/ dir itself

$config keys:

  • flags: replaces the default -azP flags
  • options: extra flags appended to the rsync command
  • timeout: process timeout in seconds (null = no limit)
  • progress_bar: show transfer progress
  • display_stats: show rsync statistics

Note: PHP shell-escaping breaks rsync's --exclude={'a','b'} brace list. Pass each exclude as its own --exclude=... option, or use --exclude-from=<file>.

download()

php
download(string $source, string $destination, array $config = []): void

Download a file or directory from the current host via rsync.

php
download('{{deploy_path}}/.dep/database.sql', 'backup/database.sql');

$config accepts the same keys as upload().

info()

php
info(string $message): void

Print an info message, prefixed with info and the host alias.

php
info('Deployed release {{release_name}}');

warning()

php
warning(string $message): void

Print a warning message.

writeln()

php
writeln(string $message, int $options = 0): void

Write a line to the output, prefixed with the current host alias.

The message is parsed for {{config}} placeholders before printing.

parse()

php
parse(string $value): string

Replace {{name}} placeholders in a string with values from the current config.

php
$current = parse('{{deploy_path}}/current');

set()

php
set(string $name, $value): void

Set a global config value.

php
set('keep_releases', 5);
set('shared_files', ['.env']);

add()

php
add(string $name, array $array): void

Append values to an array config option.

php
add('shared_files', ['.env']);
add('shared_dirs', ['storage/logs']);

get()

php
get(string $name, $default = null)

Return a config value, or $default if it isn't set.

Callable values are resolved on first access and cached.

php
$branch = get('branch', 'main');

has()

php
has(string $name): bool

Return whether a config option is set.

ask()

php
ask(string $message, ?string $default = null, ?array $autocomplete = null): ?string

Prompt the user for a string, on the current host.

Returns $default in quiet mode (-q).

php
$branch = ask('Branch to deploy?', 'main');
$tag    = ask('Tag?', null, ['v1.0', 'v1.1', 'v1.2']);

askChoice()

php
askChoice(string $message, array $availableChoices, $default = null, bool $multiselect = false)

Prompt the user to pick one or more values from a list.

php
$color = askChoice('Pick a color', ['red', 'green', 'blue'], 0);
ArgumentTypeComment
$defaultmixedKey into $availableChoices, or null for no default.

askConfirmation()

php
askConfirmation(string $message, bool $default = false): bool

Prompt the user with a yes/no question. Returns $default in quiet mode.

php
if (askConfirmation('Drop the database?')) {
    run('mysql -e "DROP DATABASE app"');
}

askHiddenResponse()

php
askHiddenResponse(string $message): string

Prompt the user for input without echoing it. Use for passwords and tokens.

input()

php
input(): InputInterface

Return the Symfony Console input, e.g. to read CLI options.

php
$tag = input()->getOption('tag');

output()

php
output(): OutputInterface

Return the Symfony Console output, e.g. to check verbosity.

commandExist()

php
commandExist(string $command): bool

Return whether a command is available on the current host's PATH.

php
if (!commandExist('git')) {
    throw error('git is required to deploy');
}

commandSupportsOption()

php
commandSupportsOption(string $command, string $option): bool

Return whether a command's man page or --help output mentions the given option.

Useful for picking newer flags only when the installed version supports them.

php
$progress = commandSupportsOption('rsync', '--info=progress2') ? '--info=progress2' : '--progress';

which()

php
which(string $name): string

Return the absolute path of a command on the current host.

Tries command -v, then which, then type -p.

php
$php = which('php');
run("$php -v");

remoteEnv()

php
remoteEnv(): array

Return the remote host's environment as an associative array.

php
$remotePath = remoteEnv()['PATH'];
run('echo $PATH', env: ['PATH' => "/home/user/bin:$remotePath"]);

error()

php
error(string $message): Exception

Build a Deployer Exception with {{config}} placeholders parsed in the message.

php
if (!commandExist('git')) {
    throw error('git is required on {{alias}}');
}

timestamp()

php
timestamp(): string

Return the current UTC timestamp in ISO 8601 format.

quote()

php
quote(string|int $arg): string

Quote a string for safe use as a shell argument (ANSI-C $'...' syntax).

Strings made of safe characters (alphanumeric, /.-+@:=,%) are returned unquoted. Throws on null bytes.

php
run('git log --format=' . quote($format));
run('echo ' . quote("it's a test"));  // echo $'it\'s a test'

fetch()

php
fetch(string $url, string $method = 'get', array $headers = [], ?string $body = null, ?array &$info = null, bool $nothrow = false): string

Make an HTTP request and return the response body.

Pass $info by reference to capture status code, headers, and timing (same shape as PHP's curl_getinfo). Use nothrow: true to receive the body even on non-2xx responses.

php
$body = fetch('{{domain}}/health', info: $info);
if ($info['http_code'] !== 200) {
    throw error("health check failed: {$info['http_code']}");
}

fetch('https://api.example.com/notify', 'post',
    ['Authorization' => 'Bearer {{token}}'],
    json_encode(['release' => '{{release_name}}']),
);