From 10655d4c30a630dbcf0bf92017dc7add873735b8 Mon Sep 17 00:00:00 2001 From: Fabio Rehm Date: Sat, 2 Mar 2013 16:38:53 -0300 Subject: [PATCH] Add support for running scripts after container creation --- lib/vagrant-lxc/container.rb | 21 ++++++++++++++++++--- spec/unit/container_spec.rb | 23 ++++++++++++++++++++++- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/lib/vagrant-lxc/container.rb b/lib/vagrant-lxc/container.rb index 7279e45..d13235e 100644 --- a/lib/vagrant-lxc/container.rb +++ b/lib/vagrant-lxc/container.rb @@ -16,6 +16,8 @@ module Vagrant # an UUID. class NotFound < StandardError; end + CONTAINERS_PATH = '/var/lib/lxc' + attr_reader :name def initialize(name) @@ -30,13 +32,26 @@ module Vagrant def create(metadata = {}) # FIXME: Ruby 1.8 users dont have SecureRandom # @logger.info('Creating container...') - name = SecureRandom.hex(6) + @name = SecureRandom.hex(6) public_key = Vagrant.source_root.join('keys', 'vagrant.pub').expand_path.to_s # TODO: Handle errors - lxc :create, '--template', metadata['template-name'], '--name', name, '--', '-S', public_key, '-T', metadata['tar-cache'] + lxc :create, '--template', metadata['template-name'], '--name', @name, '--', '-S', public_key, '-T', metadata['tar-cache'] - @name = name + @name + end + + def run_after_create_script(script) + private_key = Vagrant.source_root.join('keys', 'vagrant').expand_path.to_s + + @logger.debug 'Running after-create-script from box metadata' + cmd = [ + script, + '-r', "#{CONTAINERS_PATH}/#{@name}/rootfs", + '-k', private_key, + '-i', dhcp_ip + ] + execute *cmd end def start diff --git a/spec/unit/container_spec.rb b/spec/unit/container_spec.rb index 887a23b..bccb1ee 100644 --- a/spec/unit/container_spec.rb +++ b/spec/unit/container_spec.rb @@ -82,7 +82,7 @@ describe Vagrant::LXC::Container do let(:public_key_path) { Vagrant.source_root.join('keys', 'vagrant.pub').expand_path.to_s } before do - subject.stub(:lxc) + subject.stub(lxc: true) SecureRandom.stub(hex: name) subject.create 'template-name' => template_name, 'tar-cache' => tar_cache_path end @@ -99,6 +99,27 @@ describe Vagrant::LXC::Container do end end + describe 'after create script execution' do + let(:name) { 'random-container-name' } + let(:after_create_path) { '/path/to/after/create' } + let(:execute_cmd) { @execute_cmd } + let(:priv_key_path) { Vagrant.source_root.join('keys', 'vagrant').expand_path.to_s } + let(:ip) { '10.0.3.234' } + + before do + subject.stub(dhcp_ip: ip) + subject.stub(:execute) { |*args| @execute_cmd = args.join(' ') } + subject.run_after_create_script after_create_path + end + + it 'runs after-create-script when present passing required variables' do + execute_cmd.should include after_create_path + execute_cmd.should include "-r /var/lib/lxc/#{name}/rootfs" + execute_cmd.should include "-k #{priv_key_path}" + execute_cmd.should include "-i #{ip}" + end + end + describe 'destruction' do let(:name) { 'container-name' }