Generating rails environment using Vagrant-Librarian-Chef + self-cookbook

The tutorial below provides a clear instruction for using Vagrant in your Rails development environment.

https://gorails.com/guides/using-vagrant-for-rails-development

Even though it required me to do a few things in the remote machine.

$ cd /vagrant
$ gem install bundler
$ rbenv rehash
$ bundle install
$ bin/rails server -b 0.0.0.0
# why not "rails s" ? Check out this here

You configure “Cheffile” to pull out cookbooks with dependencies. And you configure “Vagrantfile” for vagrant provisions. (From my understanding, this means that you specify “tasks” that you want to make on the remote server.)

For example, if you wanna add “nginx”, in the cheffile you write

cookbook ‘nginx’

This will install /cookbooks/nginx.

And in the Vagrantfile, add

chef.add_recipe 'nginx'

This will trigger an action specified in rails-project-path/cookbooks/nginx/recipes/default.rb, which does installing and starting nginx server.

Pretty convenient. However, typing the commands above was kinda annoying, and it won’t set up nginx.conf neither.

Therefore, I decided to create my own cookbook for them and make it automatic.

How to make a self-cookbook

First , you need to install Chef.

$ sudo gem i chef --no-ri --no-rdoc
$ rbenv rehash

Now you can also use “knife” command. Create a cookbook by typing

$ knife cookbook create my_cookbook -o site-cookbooks/

Now you are ready to define tasks. In this tutorial, we will modify a nginx.conf. Go to site-cookboooks/my_cookbook/recipes/default.py and add

template “nginx.conf” do
path “/etc/nginx/nginx.conf”
source “nginx.conf.erb”
owner “root”
group “root”
mode 0644
notifies :reload,’service[nginx]’
end

Create “nginx.conf.erb” on the same directory

user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server {
listen 3000;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
}

All set, this should configure nginx.conf so that the server will listen to 3000 port.

In order to use this cookbook in Cheffile, you need to have a git repository for this.

$ cd site-cookbooks/my_cookbook
$ git init
$ git add .
$ git commit -m “my original cookbook”
$ git-push-to-your-remote-repository

And in the cheffile, add

cookbook ‘my_cookbook’, git: ‘your-remote-repository'

In the vagrantfile, add

chef.add_recipe “my_cookbook”

Now reload vagrant!!

vagrant provision

That’s it. Now you should be able to see nginx server working on the port 3000.