Skip to content

Commit

Permalink
Crontab: allow sudo with crontab:use_sudo option (#3759)
Browse files Browse the repository at this point in the history
* Add parameter crontab:use_sudo to allow running crontab using sudo.

This makes it possible to overwrite the bin/crontab variable to edit crontab for other users.

e.g.

set("crontab:use_sudo", true);
set("bin/crontab", function () {
  return which('crontab') . " -u www-data";
});

* Add documentation and use cases for crontab:use_sudo

* Regenerate documentation with docgen
  • Loading branch information
jkarwasz-portavice authored Dec 22, 2023
1 parent 11cef74 commit e518a42
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
13 changes: 10 additions & 3 deletions contrib/crontab.php
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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' ]")) {
Expand All @@ -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"));
}

12 changes: 11 additions & 1 deletion docs/contrib/crontab.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down

0 comments on commit e518a42

Please sign in to comment.