Using Phing to SSH into a Vagrant box
Now that I’ve started using migrations, I’ve discovered a minor irritant.
I run this project on a Vagrant VM and have discovered that I keep forgetting to ssh into the vagrant box before running the migrations script. The obvious solution is to automate this and I decided to use Phing to do so.
Firstly, I needed to install the PHP ssh2 extension:
$ brew install libssh2 $ sudo pecl install pecl.php.net/ssh2-beta
I’m on OS X, so installed libssh2 via homebrew and as the PECL ssh2 extension is marked as beta, so we have to specify that. We can accept the default for auto-detecting the libssh2 prefix.
Then add extension=ssh2.so to your /etc/php.ini file.
Once this is done, we can now use Phing’s SshTask in our build scripts.
This is a simple build.xml file to check it all works:
<?xml version="1.0"?> <project name="sshtest" default="testssh"> <target name="testssh"> <ssh username="vagrant" password="vagrant" host="192.168.123.456" command="pwd" property="pwd" display="false" /> <echo>The current working directory is ${pwd}</echo> </target> </project>
The output looks like:
$ phing Buildfile: /www/19ft/projectname/build.xml sshtest > testssh: [echo] The current working directory is /home/vagrant BUILD FINISHED Total time: 0.3923 seconds
Now that it works, we can write a target that does something useful:
<target name="migrate" > <ssh username="vagrant" password="vagrant" host="192.168.123.456" command="cd /vagrant; php bin/migrations.php migrate" /> </target>
Now, I simply run `phing migrate` and the MySQL in my Vagrant box is migrated as I expect.
Obviously Phing isn’t the only way to do this, but it worked for me.
In order to install beta extansion, it's not necessary to reference the exact version. It's enough to add -beta suffix:
pecl install pecl.php.net/ssh2-beta
.phing seems like overkill for a task like that (although obviously it works). Could you not just add an alias for the command to ssh in and run the migration?
http://www.cyberciti.biz/faq/unix-linux-execute-command-using-ssh/
Something like
alias migrate="ssh [vagrant details] 'cd /vagrant; php bin/migrations.php migrate'"
Also, why can't you use something like below?
vagrant exec 'php /vagrant/bin/migrations.php migrate'
That uses the vagrant-exec plugin, right?
Seems like that plugin is mostly a wrapper for
vagrant ssh -c
, so you could perform the migrations as:vagrant ssh -c 'cd /vagrant; php bin/migrations.php migrate'
Just thinking out loud… :D
The main trouble with using vagrant-exec or vagrant ssh-c is more typing and more variance between projects.
i.e the main thing that using phing gives me is consistency and as a bonus, I type less.