Tbpgr Blog

Recruiting Operations tbpgr(てぃーびー) のブログ

Chef | cookbook | virtualbox向けcookbookの作成

概要

virtualbox向けcookbookの作成

詳細

virtualbox向けcookbookの作成をします。
VagrantからChefを使ってUbuntuVirtualBoxをインストールします。

手順

# kitchenの作成
mkdir virtualbox
cd virtualbox
knife solo init .

# Vagrantfile生成
vagrant init

# Vagrantfile編集 ※詳細は後述
vi Vagrantfile

# cookbookのテンプレート生成
knife cookbook create virtualbox -o site-cookbooks/

# レシピの編集 ※詳細は後述

# vagrant起動
vagrant up
vagrant provision

# 動作確認
vagrant ssh

# vagrantのインストールバージョン確認
vagrant@precise64:~$ vagrant -v
Vagrant 1.3.5

Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :

# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.provider :virtualbox do |vb|
    vb.name = "virtualbox"
    vb.customize ["modifyvm", :id, "--memory", 512]
  end

  config.vm.box = "ubuntu-12.04-x64"
  config.omnibus.chef_version = "11.6.0"
  config.vm.network :private_network, ip: "192.168.33.22"
  
  config.vm.provision :chef_solo do |chef|
    chef.cookbooks_path = ["./cookbooks", "./site-cookbooks"]
    chef.add_recipe "virtualbox"
  end
end

site-cookbooks/virtualbox/libraries/helper.rb

class Chef
  class Recipe
    def execute_with_log(name, &block)
      log "start #{name}"
      block.call
      log "end   #{name}"
    end
  end
end

site-cookbooks/virtualbox/recipe/default.rb

execute_with_log("add oracle_vbox to apt-list") do
  bash "add oracle_vbox to apt-list" do
    user "root"
    code <<-EOS
    wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | sudo apt-key add -
    sudo sh -c 'echo "deb http://download.virtualbox.org/virtualbox/debian precise contrib" >> /etc/apt/sources.list'
    EOS
  end
end

execute_with_log("update apt-get") do
  execute "update package index" do
    command "apt-get update"
  end.run_action(:run)
end

%w{virtualbox-4.2 linux-headers-3.2.0-23-generic}.each do |each_package|
  execute_with_log("install #{each_package}") do
    package "#{each_package}" do
      action :install
      options "--force-yes"
    end
  end
end

execute_with_log("virtual box setup") do
  bash "virtual box setup" do
    user "root"
    code <<-EOS
    sudo /etc/init.d/vboxdrv setup
    EOS
  end
end