Leveraging WP-CLI Aliases in Your WordPress Development Workflow

I made a few modifications to this, including the change noted by @nickkeenan to automate both the script itself, while removing the hardcoded host name in the script, and creating a wp-cli.local.yml file in the project root so that you can use the @dev alias with wp-cli from anywhere in the project :slight_smile:

Put this block in Vagrantfile after config.vm.provision provisioner do |ansible|:

    # Run script to update local SSH config for .dev hostname after `vagrant up`
    config.trigger.after :up do |trigger|
      trigger.run = {
        path: "./bin/ssh-config-development.sh",
        args: [main_hostname, "#{ANSIBLE_PATH}", trellis_config.wordpress_sites.keys.first]
      }
    end

And the updated script:

# bin/ssh-config-development.sh
#!/bin/bash
host=$1
path=$2
site=$3

# add ssh-config for vagrant to ~/.ssh/config
sed "/^$/d;s/Host /$NL&/" ~/.ssh/config | sed "/^Host $host$/,/^$/d;"> config &&
cat config > ~/.ssh/config &&
rm config &&
vagrant ssh-config --host $host >> ~/.ssh/config

# add wp-cli.local.yml to project root if it doesn't exist with alias for @dev
cd $path/.. &&
if [ ! -f wp-cli.local.yml ]
then
  touch wp-cli.local.yml
fi

if ! grep -Fxq "@dev" wp-cli.local.yml
then

cat << EOF > wp-cli.local.yml
@dev:
  ssh: vagrant@$host/srv/www/$site/current
  path: web/wp
EOF

fi

A few caveats:

  • if you have more than one site in your wordpress_sites.yml it only creates an alias for the first one
  • the script assumes your ssh config is located at ~/.ssh/config
  • it only checks for the existence of a @dev alias in wp-cli.local.yml so if one already exists, it won’t do anything. this might mean the alias won’t work if you’ve run vagrant up then changed your site name or URL and run vagrant up again
  • by default, the alias will not work in the site/ directory
    – to fix, either add the alias to site/wp-cli.yml, delete site/wp-cli.yml, or add this to the configuration in site/wp-cli.yml:
_:
  inherit: ../wp-cli.local.yml
1 Like