diff --git a/contrib/crontab.php b/contrib/crontab.php index 536798a57..2717135df 100644 --- a/contrib/crontab.php +++ b/contrib/crontab.php @@ -34,6 +34,9 @@ return get('application', 'application'); }); +// Use sudo to run crontab. When running crontab with sudo, you can use the `-u` parameter to change a crontab for a different user. +set('crontab:use_sudo', false); + desc('Sync crontab jobs'); task('crontab:sync', function () { $cronJobsLocal = array_map( @@ -80,6 +83,8 @@ function setRemoteCrontab(array $lines): void { + $sudo = get('crontab:use_sudo') ? 'sudo' : ''; + $tmpCrontabPath = sprintf('/tmp/%s', uniqid('crontab_save_')); if (test("[ -f '$tmpCrontabPath' ]")) { @@ -90,16 +95,18 @@ function setRemoteCrontab(array $lines): void run("echo '" . $line . "' >> $tmpCrontabPath"); } - run('{{bin/crontab}} ' . $tmpCrontabPath); + run("$sudo {{bin/crontab}} " . $tmpCrontabPath); run('unlink ' . $tmpCrontabPath); } function getRemoteCrontab(): array { - if (!test("{{bin/crontab}} -l >> /dev/null 2>&1")) { + $sudo = get('crontab:use_sudo') ? 'sudo' : ''; + + if (!test("$sudo {{bin/crontab}} -l >> /dev/null 2>&1")) { return []; } - return explode(PHP_EOL, run("{{bin/crontab}} -l")); + return explode(PHP_EOL, run("$sudo {{bin/crontab}} -l")); } diff --git a/docs/contrib/crontab.md b/docs/contrib/crontab.md index fb8d97d47..45017d838 100644 --- a/docs/contrib/crontab.md +++ b/docs/contrib/crontab.md @@ -32,11 +32,21 @@ return get('application', 'application'); ``` +### crontab:use_sudo +[Source](https://github.com/deployphp/deployer/blob/master/contrib/crontab.php#L38) + +Use sudo to run crontab. When running crontab with sudo, you can use the `-u` parameter to change a crontab for a different user. + +```php title="Default value" +false +``` + + ## Tasks ### crontab:sync -[Source](https://github.com/deployphp/deployer/blob/master/contrib/crontab.php#L38) +[Source](https://github.com/deployphp/deployer/blob/master/contrib/crontab.php#L41) Sync crontab jobs.