Back to Deployer

API Reference

docs/api.md

8.0.311.2 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

Defines a host or hosts.

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

Inside task can be used to get Host instance of an alias.

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

localhost()

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

Define a local host. Deployer will not connect to this host, but will execute commands locally instead.

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

currentHost()

php
currentHost(): Host

Returns current host.

select()

php
select(string $selector): array

Returns hosts based on provided selector.

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

selectedHosts()

php
selectedHosts(): array

Returns array of hosts selected by user via CLI.

import()

php
import(string $file): void

Import other PHP or MAML recipes.

php
import('recipe/common.php');
php
import(__DIR__ . '/config/hosts.maml');

desc()

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

Set task description.

task()

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

Define a new task and save to tasks list.

Alternatively get a defined task.

ArgumentTypeComment
$namestringName of current task.
$bodycallable or array or nullCallable task, array of other tasks names or nothing to get a defined tasks

before()

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

Call that task before specified task runs.

ArgumentTypeComment
$taskstringThe task before $that should be run.
$dostring or callableThe task to be run.

after()

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

Call that task after specified task runs.

ArgumentTypeComment
$taskstringThe task after $that should be run.
$dostring or callableThe task to be run.

fail()

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

Setup which task run on failure of $task. When called multiple times for a task, previous fail() definitions will be overridden.

ArgumentTypeComment
$taskstringThe task which need to fail so $that should be run.
$dostring or callableThe task to be run.

option()

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

Add users options.

ArgumentTypeComment
$namestringThe option name
$shortcutstring or array or nullThe shortcuts, can be null, a string of shortcuts delimited by
$modeint or nullThe option mode: One of the VALUE_* constants
$descriptionstringA description text
$defaultstring or string[] or int or bool or nullThe default value (must be null for self::VALUE_NONE)

cd()

php
cd(string $path): void

Change the current working directory.

php
cd('~/myapp');
run('ls'); // Will run `ls` in ~/myapp.

become()

php
become(string $user): \Closure

Change the current user.

Usage:

php
$restore = become('deployer');

// do something

$restore(); // revert back to the previous user

within()

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

Execute a callback within a specific directory and revert back to the initial working directory.

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 

Executes given command on remote host.

Examples:

php
run('echo hello world');
run('cd {{deploy_path}} && git status');
run('password %my_secret%', secrets: ['my_secret' => getenv('SECRET')]);
run('curl medv.io', timeout: 5);
php
$path = run('readlink {{deploy_path}}/current');
run("echo $path");

Use | quote filter to safely quote config values as shell arguments:

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

To output literal {{ without replacement, escape with a backslash \{{:

php
run('echo \{{not_replaced}}'); // outputs: {{not_replaced}}
ArgumentTypeComment
$commandstringCommand to run on remote host.
$cwdstring or nullSets the process working directory. If not set {{working_path}} will be used.
$timeoutint or nullSets the process timeout (max. runtime). The timeout in seconds (default: 300 sec; see {{default_timeout}}, null to disable).
$idleTimeoutint or nullSets the process idle timeout (max. time since last output) in seconds.
$secretsarray or nullPlaceholder %secret% for sensitive information.
$envarray or nullArray of environment variables: run('echo $KEY', env: ['key' => 'value']);
$forceOutputbool or nullPrint command output in real-time.
$nothrowbool or nullDon't throw an exception of non-zero exit code.

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 

Execute commands on a local machine.

Examples:

php
$user = runLocally('git config user.name');
runLocally("echo $user");
ArgumentTypeComment
$commandstringCommand to run on localhost.
$cwdstring or nullSets the process working directory. If not set {{working_path}} will be used.
$timeoutint or nullSets the process timeout (max. runtime). The timeout in seconds (default: 300 sec, null to disable).
$idleTimeoutint or nullSets the process idle timeout (max. time since last output) in seconds.
$secretsarray or nullPlaceholder %secret% for sensitive information.
$envarray or nullArray of environment variables: runLocally('echo $KEY', env: ['key' => 'value']);
$forceOutputbool or nullPrint command output in real-time.
$nothrowbool or nullDon't throw an exception of non-zero exit code.
$shellstring or nullShell to run in. Default is bash -s.

test()

php
test(string $command): bool

Run test command. Example:

php
if (test('[ -d {{release_path}} ]')) {
...
}

testLocally()

php
testLocally(string $command): bool

Run test command locally. Example:

testLocally('[ -d {{local_release_path}} ]')

on()

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

Iterate other hosts, allowing to call run a func in callback.

php
on(select('stage=prod, role=db'), function ($host) {
    ...
});
php
on(host('example.org'), function ($host) {
    ...
});
php
on(Deployer::get()->hosts, function ($host) {
    ...
});

invoke()

php
invoke(string $taskName): void

Runs a task.

php
invoke('deploy:symlink');

upload()

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

Upload files or directories to host.

To upload the contents of a directory, include a trailing slash (eg upload('build/', '{{release_path}}/public');). Without the trailing slash, the build directory itself will be uploaded (resulting in {{release_path}}/public/build).

The $config array supports the following keys:

  • flags for overriding the default -azP passed to the rsync command
  • options with additional flags passed directly to the rsync command
  • timeout for Process::fromShellCommandline() (null by default)
  • progress_bar to display upload/download progress
  • display_stats to display rsync set of statistics

Note: due to the way php escapes command line arguments, list-notation for the rsync --exclude={'file','anotherfile'} option will not work. A workaround is to add a separate --exclude=file argument for each exclude to options (also, do not wrap the filename/filter in quotes). An alternative might be to write the excludes to a temporary file (one per line) and use --exclude-from=temporary_file argument instead.

download()

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

Download file or directory from host

info()

php
info(string $message): void

Writes an info message.

warning()

php
warning(string $message): void

Writes an warning message.

writeln()

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

Writes a message to the output and adds a newline at the end.

parse()

php
parse(string $value): string

Parse set values.

set()

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

Setup configuration option.

add()

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

Merge new config params to existing config array.

get()

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

Get configuration value.

has()

php
has(string $name): bool

Check if there is such configuration option.

ask()

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

askChoice()

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

askConfirmation()

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

askHiddenResponse()

php
askHiddenResponse(string $message): string

input()

php
input(): InputInterface

output()

php
output(): OutputInterface

commandExist()

php
commandExist(string $command): bool

Check if command exists

commandSupportsOption()

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

which()

php
which(string $name): string

remoteEnv()

php
remoteEnv(): array

Returns remote environments variables as an array.

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

error()

php
error(string $message): Exception

Creates a new exception.

timestamp()

php
timestamp(): string

Returns current timestamp in UTC timezone in ISO8601 format.

quote()

php
quote(string|int $arg): string

Quotes a string for safe use as a shell argument using ANSI-C $'...' syntax. Safe characters (alphanumeric, /.-+@:=,%) are returned unquoted.

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

Example usage:

php
$result = fetch('{{domain}}', info: $info);
var_dump($info['http_code'], $result);