Adding Arguments And Options To Deployer Tasks

15th November 2020

I have been adding to my custom Deployer scripts for a number of months and I have now been using it to do more than just deploy my sites. Since it acts as a connection to my website server I have been using Deployer to perform other tasks like creating backups and clearing Drupal caches without having to log into the server to do it. What has helped me here is that I have set out my deployment tasks in a very modular fashion, so although my deployment runs a database backup, I there is nothing to stop me running the database backup command on it's own without doing a full deployment.

This has led me to realise that I sometimes need to control how those tasks run. I might, for example, need to backup my database with a different option so that I include the cache tables if I want to make a full backup of my Drupal site. I have a number of custom tasks in my deploy.php file, but I don't want to have nearly duplicate tasks just to run a slightly different flavour of database backup.

This lead me to look at adding options and arguments to Deployer. Although adding arguments is technically documented on the Deployer site, I had a few problems figuring out what the examples meant, so I decided to create a post to add to the documentation.

If you were not already aware, custom tasks are pretty easy to write. All you need to do is define your task in a task() function, passing in the name of the task and one of the following.

  • A string that defines a command to run.
  • A closure that gets run when the task is run.
  • An array that lists other tasks within the system.

If you use a closure then there are a number of functions that are available within the task scope to run commands or return output to the screen. As a simple example, here is my custom task for clearing the caches on a Drupal site.

  1. task('drush:cr', function () {
  2. $output = run('{{deploy_path}}/current/vendor/bin/drush cr');
  3. writeln('<info>' . $output . '</info>');
  4. });

I could have used the string argument to run this command, but I like to see the output being produced and so use a closure to print the output. I tend to namespace tasks like this, so all of my drush based functions have the format "drush:command", this also helps to group the commands together. In the above example, the run() command runs the command on the remote server and returns the output. The writeln() function will print out the output of the command run. Running the dep command will show this task available in the list of other commands.

  1. $ ../vendor/bin/dep
  2. Deployer v6.8.0
  3.  
  4. Usage:
  5. command [options] [arguments]
  6.  
  7. Options:
  8. -h, --help Display this help message
  9. -q, --quiet Do not output any message
  10. -V, --version Display this application version
  11. --ansi Force ANSI output
  12. --no-ansi Disable ANSI output
  13. -n, --no-interaction Do not ask any interactive question
  14. -f, --file[=FILE] Specify Deployer file
  15. -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  16.  
  17. Available commands:
  18. autocomplete Install command line autocompletion capabilities
  19. help Displays help for a command
  20. init Initialize deployer in your project
  21. list Lists commands
  22. run Run any arbitrary command on hosts
  23. ssh Connect to host through ssh
  24. debug
  25. debug:task Display the task-tree for a given task
  26. drush
  27. drush:cr

To run a backup on my site before I deploy it I have a custom task. This wraps the drush sql-dump command, but also has some other setup to exclude the common cache tables, session tables and watch dog tables that aren't critical to a disaster recovery.

  1. task('drush:backup', function () {
  2. if (test('test -f {{deploy_path}}/current/vendor/bin/drush')) {
  3. // Backup database.
  4. $file = 'hashbangcode-' . date('d-m-Y-Hi') . '.sql';
  5. $output = run('{{deploy_path}}/current/vendor/bin/drush sql-dump --gzip --structure-tables-list=cache,cache_bootstrap,cache_config,cache_container,cache_data,cache_default,cache_discovery,cache_filter,cache_menu,cache_page,history,search_dataset,search_index,search_total,sessions,watchdog --result-file=~/backup/' . $file);
  6. writeln('<info>' . $output . '</info>');
  7.  
  8. // (re)Create symlink.
  9. $symlink = '~/backup/latest.sql.gz';
  10. if (test('test -f ' . $symlink)) {
  11. run('rm -f ' . $symlink);
  12. }
  13. $output = run('ln -s ~/backup/' . $file . '.gz ' . $symlink);
  14. writeln('<info>' . $output . '</info>');
  15. }
  16. });

The final step here is to create a symlink to the backup so that I can download the latest backup without having to remember or figure out the name of the backup file. This means I can just rsync the file latest.sql.gz instead of trying to figure out the name of the file that was created during the backup.

To listen to user input outside of the command being run there are two options, both of which are defined globally. That is key to understanding how they work as you define your user input at the top of your deploy.php file and all tasks have access to potentially listen to that input. The two types of input we have are 'option' and 'argument'. I'll go into each of those now as they both have differences.

Argument

An argument works by appending additional arguments to the end of the command line, after the name of the task being run.

For example, if we want to change the database function using an argument we define it in the deploy.php file like this.

  1. use Symfony\Component\Console\Input\InputArgument;
  2.  
  3. argument('include-cache-backup', InputArgument::OPTIONAL, 'Adds the cache tables to the backup command.', false);

As you can probably tell, Deployer uses Symfony components. This means that the argument() function is a wrapper around the creation of an InputArgument object. Most of the parameters to the argument() function are self explanatory, but the final parameter here is the default option that is set if the user hasn't entered the paramter.

Note that Deployer already has one argument called "stage", which means that this argument needs to be set first in the command line. The stage argument is the name of the server you are deploying to, as defined in your host() function and is useful when deploying to different servers. For example, let's say that you have two servers setup, one called prod, and one called stage. You might define them like this.

  1. host('prod')
  2. ->hostname('stage.domain.com')
  3. ->set('deploy_path', '/var/www/html/website')
  4.  
  5. host('stage')
  6. ->hostname('domain.com')
  7. ->set('deploy_path', '/var/www/html/website')

With this in place you provide the 'stage' argument to deploy to the relevant host. For example, to deploy to 'prod' you would supply the 'prod' parameter to the command.

../vendor/bin/dep deploy prod

By adding additional arguments you need to introduce them before the server you want to deploy to, otherwise the argument you defined would receive the text 'prod', which was intended for the first argument. The previous command, with the addition of the include-cache-backup would become this.

../vendor/bin/dep deploy yes prod

This passes the value of 'yes' to the include-cache-backup argument and 'prod' to the stage argument. There is also absolutely no information on the command line output that you have added an additional argument to your script. Because of this it is really important that you document any additional arguments you add to your Deploy script. Without that you would have to read the code to figure out that the 'prod' argument is being passed to the wrong argument.

To listen to the arguments being sent to the command you need to use the input() function to extract the incoming input from the user. In the following example we are extracting data from the supplied argument. Arguments aren't named, just extracted in the order they are defined, so include-cache-backup will map to the first argument sent to the command.

  1. task('test:argument', function () {
  2. $includeCacheBackup = null;
  3. if (input()->hasArgument('include-cache-backup')) {
  4. $includeCacheBackup = input()->getArgument('include-cache-backup');
  5. }
  6. writeln('include-cache-backup ' . var_export($includeCacheBackup, true));
  7. });

This will print out "yes" on the command line when running the examples above against this task. Obviously you will need to do some careful checking to make sure that the incoming argument is correct before trying to use it. The hasArgument() method is really important to include as it means you can run your commands without any arguments. I find it best practice to assume some sensible default value instead of throwing an error if the argument isn't present. As we provided a default for our argument when setting things up we will always receive 'false' if the argument is not present.

This is probably not the right type of input to use for a switch that changes how a task operates.

Option

An option works by listening to flags that you add to the command and work entirely separately from the arguments input type. For example, if we want to change the database backup task using an option we define it in the deploy.php file like this.

  1. use Symfony\Component\Console\Input\InputOption;
  2.  
  3. option('include-cache-backup', 'i', InputOption::VALUE_OPTIONAL, 'Adds the cache tables to the backup command.', false);

With this in place, Deploy adds our custom option to the list of options in the command line output. Again, the 'false' at the end of the parameter list is the default value of the option. Running the dep command without any input shows this in the list of options.

  1. $ ../vendor/bin/dep
  2. Deployer v6.8.0
  3.  
  4. Usage:
  5. command [options] [arguments]
  6.  
  7. Options:
  8. -h, --help Display this help message
  9. ... snip ...
  10. -i, --include-cache-backup[=INCLUDE-CACHE-BACKUP] Adds the cache tables to the backup command. [default: false]

To use the new option we just add it as a flag to the command. It doesn't matter if this goes before or after the 'stage' argument as it will not interfere with the arguments.

$ ../vendor/bin/dep deploy --include-cache-backup=true

Note that the second parameter to the option() function is the shortcut. This can be used to simplify the option on the command line. The following command is equivalent to the above example.

$ ../vendor/bin/dep deploy -i true

To listen to the options being used with the command you need to use the input() function to extract the incoming input from the user. In the following example we are extracting data from the supplied option with the name 'include-cache-backup'. Options are named so they can be extracted by the name of the option set when defined.

  1. task('test:option', function () {
  2. $includeCacheBackup = null;
  3. if (input()->hasOption('include-cache-backup')) {
  4. $includeCacheBackup = input()->getOption('include-cache-backup');
  5. }
  6. writeln('include-cache-backup ' . var_export($includeCacheBackup, true));
  7. });

This will print out the string 'true' when running the examples above against this task. Again, you should probably make sure that the incoming parameters are correctly formatted before trying to use them. The option is passed to the task as a string so you need to do your own casting to ensure it's the correct type. Essentially, don't trust user input.

As options don't interfere with the default running of Deployer, and are self documenting on the command line, they make sense to use before looking at arguments. In fact, I would highly recommend you don't use arguments unless you have a very good reason to do so. Options should be your go to option when accepting user input to a Deployer script. 

The New Backup Function

With that knowledge in hand, let's look at recreating my database backup task with the option of either including or excluding the cache tables. By default, I don't want the script to include the cache tables in the backup, so the default option is false. If the user adds the --include-cache-backup option then they can either pass in 'yes' or nothing at all as we detect that option as well. This means that just passing the flag to the script is enough to enable the option and turn off the cache table backup.

Note that I'm not directly using the incoming value from the user, I'm deliberately only using it to detect what I should be doing later in the script. This is especially important when running raw commands on a remote server, which is essentially what we are doing here.

  1. use Symfony\Component\Console\Input\InputOption;
  2.  
  3. option('include-cache-backup', 'i', InputOption::VALUE_OPTIONAL, 'Adds the cache tables to the backup command.', false);
  4.  
  5. task('drush:backup', function () {
  6. if (test('test -f {{deploy_path}}/current/vendor/bin/drush')) {
  7. // Define filename.
  8. $file = 'hashbangcode-' . date('d-m-Y-Hi') . '.sql';
  9.  
  10. // Detect option.
  11. $includeCacheBackup = false;
  12. if (input()->hasOption('include-cache-backup')) {
  13. $includeCacheBackupInput = input()->getOption('include-cache-backup');
  14. if ($includeCacheBackupInput == 'yes' || $includeCacheBackupInput == '') {
  15. $includeCacheBackup = true;
  16. }
  17. }
  18.  
  19. // React to option.
  20. if ($includeCacheBackup === TRUE) {
  21. $structureTablesList = '';
  22. }
  23. else {
  24. $structureTablesList = '--structure-tables-list=cache,cache_bootstrap,cache_config,cache_container,cache_data,cache_default,cache_discovery,cache_filter,cache_menu,cache_page,history,search_dataset,search_index,search_total,sessions,watchdog ';
  25. }
  26.  
  27. // Backup database.
  28. $output = run('{{deploy_path}}/current/vendor/bin/drush sql-dump ' . $structureTablesList . '--gzip --result-file=~/backup/' . $file);
  29. writeln('<info>' . $output . '</info>');
  30.  
  31. // (re)Create symlink.
  32. $symlink = '~/backup/latest.sql.gz';
  33. if (test('test -f ' . $symlink)) {
  34. run('rm -f ' . $symlink);
  35. }
  36. $output = run('ln -s ~/backup/' . $file . '.gz ' . $symlink);
  37. writeln('<info>' . $output . '</info>');
  38. }
  39. });

This works very well. I could improve this though better generating the backup command instead of just plugging strings together. Also, because the --include-cache-backup option is defined as a global option then it can be used no matter now the drush:backup task is called. Which means that I can either use it directly by calling drush:backup or indirectly through the default drush task.

Add new comment

The content of this field is kept private and will not be shown publicly.