LoginSignup
6
10

More than 5 years have passed since last update.

Macbook Pro 2016にVagrantをインストール、その上にRuby on Rails5環境を構築し、GitHubと連携させる

Last updated at Posted at 2017-04-30

はじめに

私が実際に自己プロダクト開発で使用している開発環境の構築方法を備忘録で書きます。開発環境は「全て仮装環境で行い、ローカルは汚さないように」を目標に構築しています。

環境

今回構築できる環境は以下。

ホストOS: macOS Sierra
└ VirtualBox: 5.1.12
  └ Vagrant: 1.9.1
    └ CentOS: 7.2
      └ rbenv: 1.1.0-2-g4f8925a
        └ Ruby: 2.4.0
      └ Gem: 2.6.8
          └ Rails: 5.0.2
      └ PostgreSQL: 9.5
      └ Git: 1.8.3.1 (To connect with GitHub)

自分のMacにVirtualBoxを立てて、その上にVagrantを使ってCentOSを乗せます。そしてそこにRuby on Rails環境を構築していきます。

Vagrant環境の構築

まずは土台づくりから。
Vagrant環境を構築していきます。

VirtualBoxのインストール

仮想環境ソフトウェアは「VirtualBox」を使用します。バージョンは"5.1.12"。

VirtualBox – Oracle

Vagrantのインストール

VagrantはGUIでポチポチとやっていけばインストールできます。

以下のリンクからダウンロードできます。

Vagrant

正常にインストールされたかを確認するには以下のコマンドで確認。

Terminal
$ vagrant -v
Vagrant 1.9.1

バージョンが返ってくれば正常にインストールされています。

Boxを使用してCentOSをインストール

BoxとはVagrant上で動作する仮想マシンのディスクイメージとメタデータを「.box」形式で格納しているファイルです。

以下からそのファイルを拝借してきます。

A list of base boxes for Vagrant – Vagrantbox.es

VagrantにOSをインストールするために、VagrantにBoxを追加します。
Boxの追加方法は vagrant box add コマンドを使用し、add の後にBox名を指定します。Box名はお好きな名前で。

Terminal
$ vagrant box add centos72 https://github.com/CommanderK5/packer-centos-template/releases/download/0.7.2/vagrant-centos-7.2.box

追加したBoxは、最小構成のMinimal CentOSでバージョンは"7.2"。

Vagrantの初期化

追加したBoxを初期化します。
この初期化でBoxのイメージがVirtualBoxにマウントされます。
初期化には vagrant init コマンドを使用し、init の後にBox名を指定します。

Terminal
$ vagrant init centos72

初期化に成功すると Vagrantfile というRubyファイルが生成されます。

次項の「Vagrantfileの設定」で開発に必要なVagrantの設定を行います。

Vagrantfileの設定

開発をし易くするにするため、Vagrantfileの設定を弄ってホストOSからの通信を許容させます。

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

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
:
(中略)
:
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
# config.vm.synced_folder "../data", "/vagrant_data"
config.vm.network :forwarded_port, guest: 3000, host: 3000 // 追加
:
(中略)
:

Vagrantの起動

次項の「Ruby on Rails5環境の構築」のために、Vagrantを起動させ、Boxから構築したCentOSにログインしておきます。

Terminal
$ vagrant up
$ vagrant ssh

Vagrantの環境構築おわり!

Ruby on Rails5環境の構築

ではRuby on Rails環境を構築していきます。バージョンは最新版を(執筆時の最新バージョンは5.0.2)を選択。

yumのアップデート

Vagrant
$ yum check-update
$ sudo yum update

必要なパッケージのインストール

Vagrant
$ sudo yum -y install curl curl-devel gcc gcc-c++ git openssl-devel httpd-devel readline-devel tk-devel make zlib-devel libffi-devel

rbenvのインストール

rbenvはGitHubからインストールします。
シェルは個人的にbashが好きなのでパスは .bash_profile に通します。

Vagrant
$ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
$ git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
$ sudo ~/.rbenv/plugins/ruby-build/install.sh
$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
$ exec $SHELL -l
$ source ~/.bash_profile
$ rbenv --version
rbenv 1.1.0-2-g4f8925a

Rubyのインストール

バージョンは"2.4.0"を選択。

Vagrant
$ rbenv install -l
$ rbenv install -v 2.4.0
$ rbenv versions
$ rbenv global 2.4.0
$ ruby -v

Railsのインストール

バージョン指定は無し。その場合はGemが指定しているデフォルトのバージョンがインストールされる仕組みです。Railsのバージョンを指定したい場合はオプション付けてね(参考)。

Vagrant
$ gem update --system
$ gem install rails --no-ri --no-rdoc
$ rbenv rehash
$ rails -v
$ Rails 5.0.2

PostgreSQLのインストール

PostgreSQLのインストールをしていきます。バージョンは"9.5"を選択。

yumリポジトリの設定

Vagrant
$ sudo vi /etc/yum.repos.d/CentOS-Base.repo
:
[base]
name=CentOS-$releasever - Base
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
exclude=postgresql*  // 追記

[updates]
name=CentOS-$releasever - Updates
mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6
exclude=postgresql*  // 追記
:

PostgreSQL9.5用のリポジトリを追加

Vagrant
$ sudo yum install -y https://download.postgresql.org/pub/repos/yum/9.5/redhat/rhel-7-x86_64/pgdg-centos95-9.5-2.noarch.rpm

PostgreSQL9.5のインストールと初期化〜起動まで

Vagrant
$ sudo yum install -y postgresql95 postgresql95-server postgresql95-libs postgresql95-contrib postgresql95-devel
$ sudo /usr/pgsql-9.5/bin/postgresql95-setup initdb
$ sudo systemctl start postgresql-9.5

PostgreSQLの初期起動を設定

Vagrant
$ sudo systemctl enable postgresql-9.5

外部サーバーからのアクセスを許可する

Vagrant
$ sudo vi /var/lib/pgsql/9.5/data/postgresql.conf

:
listen_addresses = '*'  // localhost から変更
:

クライアントの認証設定

Vagrant
$ sudo vi /var/lib/pgsql/9.5/data/pg_hba.conf
:
# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust  // ident から変更
# IPv6 local connections:
host    all             all             ::1/128                 trust  // ident から変更
:

PostgreSQL9.5のパスを通す

Vagrant
$ export PATH=/usr/pgsql-9.5/bin:$PATH
$ export PGDATA=/var/lib/pgsql/9.5/data
$ source ~/.bash_profile

再起動

Vagrant
$ sudo systemctl restart postgresql-9.5

vagrantユーザを追加する

Vagrant
$ sudo su - postgres
PostgreSQL
-bash-4.1$ createuser --superuser vagrant
-bash-4.1$ exit
logout

Githubとの連携

ソースコードの運用はGitHubで行うため、VagrantとGitHubを連携させる必要があります。

SSH Keyの作成

Vagrant - GitHub お互いを連携するために必要な認証用の鍵を作成します。

Vagrant
$ ssh-keygen -t rsa -C "YOUR_EMAIL" // Githubで使用しているEmail
Generating public/private rsa key pair.
Enter file in which to save the key (/home/vagrant/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/vagrant/.ssh/id_rsa.
Your public key has been saved in /home/vagrant/.ssh/id_rsa.pub.
The key fingerprint is:
************************* YOUR_EMAIL
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|         .   .   |
|        +     o  |
|       . o   = . |
|        S . B +  |
|           B oE. |
|          o o ...|
|           oo. ..|
|            .=+o*|
+-----------------+

SSH Keyの保存

Vagrant
$ eval "$(ssh-agent -s)"
Agent pid 27250
$ ssh-add ~/.ssh/id_rsa
Identity added: /home/vagrant/.ssh/id_rsa (/home/vagrant/.ssh/id_rsa)

SSH Keyの登録

Vagrant
$ cat ~/.ssh/id_rsa.pub >> /home/vagrant/.ssh/authorized_keys
$ chmod 600 /home/vagrant/.ssh/authorized_keys
$ chmod 600 ~/.ssh/id_rsa
$ cat ~/.ssh/id_rsa.pub
※ 公開鍵が表示される // 次項「生成された公開鍵をGitHubに登録」で使用する

生成された公開鍵をGitHubに登録

上項の「SSH Keyの登録」で実行した cat コマンドで表示された公開鍵をGitHubに設定する必要があります。設定はGitHubのSSH Keyの設定ページで行います。

GitHubにログインするためのスクリプトを作成

Vagrant
$ vi ~/.ssh/config
Host github
    HostName        github.com
    IdentityFile    ~/.ssh/id_rsa
    User            git

$ chmod 600 ~/.ssh/config

GitHubと通信できるか確認

先ほど作ったスクリプトからGitHubと通信できるか確認。

Vagrant
$ ssh github
Warning: Permanently added the RSA host key for IP address '192.30.253.112' to the list of known hosts.
PTY allocation request failed on channel 0
Hi seiyamaeda! You've successfully authenticated, but GitHub does not provide shell access.
Connection to github.com closed.
hub.com closed.

おわり

Enjoy your own development!!!

投稿後記

CentOS 7は以前のバージョン6からの変更点が多く、対処するのに時間がかかりました。システム起動処理とサービス管理、ネットワーク回りの変更が目立ちますね。

リリース日が2015年、ロンチしてから結構経ってた。OSのキャッチアップは全くできていない私。

CentOS 7は業界のニーズに合った新機能追加や機能修正があるようなので、興味があれば弄ってみるのも楽しそう。

主な変更点 - CentOS-7 (1503) リリースノート

と、OSのバージョンの話をしましたが、ローカル開発はOSのバージョンはあまり気にしなくても良いかも。動けばよろし。

参考記事

6
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
10