Create a Custom Drush Command for Configuration Export
Drupal configuration can drift when developers change views, content types, permissions and site settings across different environments. An export creates a portable snapshot of those YAML-backed settings, but the standard Drush command leaves destination handling, validation and release metadata to the operator. A project-specific command can make that workflow predictable without duplicating Drupal’s export logic.
The purpose is not to replace drush config:export. The custom command should delegate to it, then add the safeguards your team needs: a stable command name, an overwrite check, a dry-run option, multisite support and a checksum beside the generated archive. That separation lets Drupal continue handling dependent configuration while your deployment process gains a consistent interface.
The examples below target Drupal 10 with Drush 11. Configuration exports include site, module and theme configuration, but not database content, uploaded files or credentials stored outside Drupal configuration. They also deserve the same operational care as deployment artefacts, particularly when they contain API keys, SMTP settings or integration tokens.
Many Australian Drupal teams work across agency offices in Melbourne, Sydney and Brisbane, sometimes with administrators in different states. An export might run in a Sydney staging environment during the arvo while approval happens in Melbourne. AEDT and AEST change with daylight saving, while Brisbane remains on AEST, so release timestamps should use UTC rather than relying on a colleague’s local clock.
Why a custom export command is useful
The built-in command is dependable and familiar, but its interface is general-purpose. A wrapper such as site:config-export gives an agency or organisation one agreed entry point across development, continuous integration and production runbooks. It also leaves room to attach project-specific validation without changing the underlying export.
That distinction matters during handovers. A managed hosting provider may have its own deployment conventions, while a Drupal agency may use Git and a continuous integration pipeline. A small command inside the project gives both groups the same operation, and it gives support staff a clearer error when somebody exports into the wrong directory or overwrites the previous release.
Prepare Drupal and Drush
Create a small custom module, such as config_export_command, and place it under version control beside the rest of the site. Drush discovers command services declared in the module’s drush.services.yml. The wider Drupal command guidance provides useful context when adapting this pattern to an existing project.
The service definition should point to the command class and apply the drush.command tag:
services:
config_export_command.export:
class: Drupal\config_export_command\Command\ExportConfigurationCommand
autowire: true
tags:
- { name: drush.command }
After installing or enabling the module, clear caches and confirm that Drush can see the command. The exact discovery command varies slightly between Drush releases, but drush list is the quickest check. If the command is absent, inspect the service tag, namespace and module installation before changing the handler itself.
Define the export workflow
A useful interface accepts a required destination and optional controls. The destination should be a directory, not the intended archive filename, because Drupal normally creates config.tar.gz inside it. A dry run should check obvious problems without writing an export, while a force option should permit deliberate replacement of an existing archive.
| Requirement | Built-in export | Custom command |
|---|---|---|
| Configuration engine | Drupal and Drush core | Delegates to the built-in export |
| Destination | Standard path handling | Validated directory and overwrite protection |
| Automation | Core options and exit status | Dry run, named options and checksum generation |
| Multisite | Core URI options | Project-specific site option |
| Maintenance | Changes with each Drush release | Stable interface with versioned tests |
The wrapper deliberately treats the core command as the export engine. That avoids reimplementing subtle rules around dependent configuration, module installation and configuration storage. The custom layer should only establish organisational policy around where the result goes and what happens after it is created.
Implement the command handler
The following class uses Drush attributes, checks the destination, delegates to config:export and writes a SHA-256 checksum after a successful run:
<?php
namespace Drupal\config_export_command\Command;
use Drush\Attributes as CLI;
use Drush\Commands\DrushCommands;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\DependencyInjection\ContainerInterface;
final class ExportConfigurationCommand extends DrushCommands
{
public function __construct(ContainerInterface $container)
{
parent::__construct($container);
}
#[CLI\Command(
name: 'site:config-export',
aliases: ['site:export-config']
)]
#[CLI\Argument(
name: 'destination',
description: 'Directory that will receive config.tar.gz.'
)]
#[CLI\Option(
name: 'site',
description: 'Multisite hostname defined in sites.php.'
)]
#[CLI\Option(
name: 'force',
description: 'Replace an existing configuration archive.'
)]
#[CLI\Option(
name: 'dry-run',
description: 'Validate the request without exporting.'
)]
public function exportConfiguration(
string $destination,
array $options = [
'site' => NULL,
'force' => FALSE,
'dry-run' => FALSE,
]
): int {
$destination = rtrim($destination, '/\\');
$archive = $destination . DIRECTORY_SEPARATOR . 'config.tar.gz';
if ($destination === '' || $archive === DIRECTORY_SEPARATOR) {
$this->io()->error('A valid destination directory is required.');
return Command::FAILURE;
}
if (is_file($archive) && !$options['force']) {
$this->io()->error(
"The archive already exists at $archive. Use --force to replace it."
);
return Command::FAILURE;
}
if (is_dir($destination) && !is_writable($destination)) {
$this->io()->error("The destination is not writable: $destination");
return Command::FAILURE;
}
if ($options['dry-run']) {
$this->io()->success("Dry run passed for $destination.");
return Command::SUCCESS;
}
if (!is_dir($destination)
&& !mkdir($destination, 0775, TRUE)
&& !is_dir($destination)
) {
$this->io()->error("Could not create $destination.");
return Command::FAILURE;
}
if ($options['force'] && is_file($archive)) {
unlink($archive);
}
$arguments = [
'destination' => $destination,
'--yes' => TRUE,
];
if (!empty($options['site'])) {
$arguments['--uri'] = $options['site'];
}
$coreCommand = $this->getApplication()->find('config:export');
$status = $coreCommand->run(
new ArrayInput($arguments),
new BufferedOutput()
);
if ($status !== Command::SUCCESS) {
return $status;
}
if (!is_file($archive)) {
$this->io()->error("The export completed without creating $archive.");
return Command::FAILURE;
}
$hash = hash_file('sha256', $archive);
file_put_contents(
$archive . '.sha256',
$hash . ' ' . basename($archive) . PHP_EOL,
LOCK_EX
);
$this->io()->success("Configuration exported to $archive.");
return Command::SUCCESS;
}
}
Running the same process with ArrayInput keeps Drush’s existing export logic intact, including site selection through the global URI option. Because the handler always passes confirmation to the nested export, keep it limited to exporting and never reuse that behaviour for an import command. Confirm the exact attribute names and command API against the Drush major version used by the project.
Test the command before deployment
Begin with command discovery and a dry run, then export into a temporary directory on the same server that will produce the release. Inspect the archive, compare drush config:status before and after, and import it into a disposable database using the same Drupal version and contributed modules. A successful archive alone does not prove that the target environment can apply it.
Protect the generated file with appropriate operating-system permissions and store it in an access-controlled release system. This matters for Australian managed-hosting and public-sector projects, where procurement conditions and the Privacy Act may influence where staging data and artefacts are stored. The law does not impose one universal hosting location, so teams should document the applicable data-residency and access requirements rather than assume every environment is equivalent.
For a remote Pilbara or Alice Springs site with an expensive or intermittent connection, generating the small configuration archive on staging and transferring it through the normal release channel is usually more reliable than running the whole deployment across that link. The checksum can then prove that the received file matches the original.
A dependable operating routine
The following practices keep the command useful after the initial release and make it safe for different operators to use:
- Pin the Drupal, Drush and custom module versions used by each release.
- Export into a fresh directory outside the public web root.
- Restrict write access to the deployment identity and release storage.
- Verify the SHA-256 checksum before importing the artefact.
- Test imports against a disposable database with matching extensions.
- Record the site UUID and multisite hostname in release metadata.
- Keep content, media and database migrations in separate procedures.
A tested wrapper gives Australian development teams a stable interface across agencies, hosting panels and regional deployments. The built-in command remains responsible for Drupal’s configuration export, while the custom layer provides predictable paths, overwrite protection and auditable checksums without hiding how the underlying release works.