Read the original article on X-Team.com
One pitfall I’ve recently encountered with Vagrant and WP-CLI was the lack of an easy way to use my local WP-CLI installation to send a command to my Vagrant box.
X-Team’s Weston Ruter first developed an incredible tool called vassh, which basically removes the pain of having to manually SSH into the Vagrant box and run the command from the project root. While vassh is really useful, it only works for Vagrant and not for remote servers.
After working closely with the WP-CLI team and refactoring multiple times, we finally came up with something called “WP-CLI SSH” which facilitates running WP-CLI commands on other servers, while invoking WP-CLI normally as if it was on your own system.
Here is the workflow before using WP-CLI SSH:
# Querying vagrant
$ cd ~/Sites/vvv/www/example.com/
$ vagrant ssh
$ cd /www/example.com/
$ wp plugin status
$ exit;
# Querying staging server
$ ssh [email protected]
$ cd /www/example.com/
$ wp plugin status
$ exit;
Not very practical and very redundant (not to mention the fact that you need to remember the path and the SSH server name).
With WP-CLI SSH (and WP-CLI >= 0.13) you can automate your workflow with only a few lines of code.
First install WP-CLI SSH with composer:$ cd ~/.wp-cli && composer require x-team/wp-cli-ssh
Then add one (or many) SSH servers to your wp-cli.local.yml
or wp-cli.yml
file:
ssh:
vagrant:
# The %pseudotty% placeholder gets replaced with -t or -T depending on whether you're piping output
# The %cmd% placeholder is replaced with the originally-invoked WP-CLI command
cmd: vagrant ssh-config > /tmp/vagrant_ssh_config && ssh -q %pseudotty% -F /tmp/vagrant_ssh_config default %cmd%
# Passed to WP-CLI on the remote server via --url
url: local-www.yourawesomewebsite.com
# We cd to this path on the remote server before running WP-CLI
path: /your/vvv/path/
staging:
cmd: ssh %pseudotty% util.example.com %cmd%
url: staging.example.com
path: /var/www/staging.example.com/current/docroot
# WP-CLI over SSH will stop if one of these are provided
disabled_commands:
- db drop
- db reset
- plugin install
- core multisite-convert
Now you can invoke WP-CLI on your Vagrant machine over SSH simply by:$ wp ssh plugin status --host=vagrant
To invoke WP-CLI on the staging server (even via an intermediary SSH jump server), you similarly can run:$ wp ssh plugin status --host=staging
Another very useful trick might be to compare the output of the same command from 2 different servers :diff <(wp ssh plugin status --host=vagrant) <(wp ssh plugin status --host=staging) -y
Read more about configuring WP-CLI SSH.
Bonus
An easy way to specify a default server is to create a bash alias for your machine user :alias wpssh='wp ssh --host=vagrant'