LoginSignup
1
0

More than 5 years have passed since last update.

Sinatra の Inline Template 機能を使って 1 ファイルで完結する Vagrantfile を作る

Posted at

Sinatra に Inline Template という機能があり、こんな感じで __END__ 以下に複数ファイルを埋め込める。

require 'sinatra'

get '/' do
  haml :index
end

__END__

@@ layout
%html
  = yield

@@ index
%div.title Hello world.

これを Vagrantfile でも使えたら便利だろうなと思い、試したらいけたのでメモしておく。

事前準備

  • vagrant が使えるようにしておく
  • vagrant plugin install sinatra しておく

Vagrantfile

こんな感じになった。Ubuntu のボックスをベースに、インラインテンプレートから読み込んだファイル内容を、/home/ubuntu/.profile, /etc/ssh/ssh_config, /etc/ssh/private_key に書きこむ例。Docker っぽく add というメソッドでファイルを追加できるようにしてみた。

# coding:utf-8
require "sinatra/base"

Vagrant.configure("2") do |config|
  @config = config

  config.vm.box = "ubuntu/xenial64"

  # インラインテンプレートを読み込み TEMPLATES 定数へ格納
  Sinatra::Base.inline_templates = "./Vagrantfile"
  TEMPLATES = Hash[Sinatra::Base.templates.map{|k, v| [k, v.first]} ]

  # 指定された文字列をコマンドとして実行するメソッド
  def run(command)
    @config.vm.provision "shell", inline: command
  end

  # 指定されたファイル内容を指定されたパスへ配置するメソッド
  def add(content, path, options={})
    run ["cat << EOF > #{path}", content, "EOF"].join("\n")
    run "chmod #{options[:mode]} #{path}" if options[:mode]
    run "chown #{options[:owner]} #{path}" if options[:owner]
  end

  # 必要なファイルを仮想マシンへ配置するための記述
  add TEMPLATES[:dot_profile], "/home/ubuntu/.profile", owner: "ubuntu"
  add TEMPLATES[:ssh_config], "/etc/ssh/ssh_config", mode: "777"
  add TEMPLATES[:private_key], "/etc/ssh/private_key", mode: "777"
end

__END__
@@ dot_profile
export HTTP_PROXY=http://proxy.example.com:8080
export http_proxy=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
export https_proxy=http://proxy.example.com:8080

@@ ssh_config
Host yoursshhost
  HostName 172.0.0.1
  IdentityFile /etc/ssh/private_key

@@ private_key
-----BEGIN RSA PRIVATE KEY-----
(略)
-----END RSA PRIVATE KEY-----

まとめ

Vagrantfile 1 つだけで完結するので、ポータビリティが高いところが便利なんじゃないかと思う。が、config.vm.synced_folder "C:\\", "/c" すればホスト Windows 上のファイルがすべて見えるようになるので、こっちを使ったほうがいいなと気づき、個人的にはボツとなった。

参考資料

1
0
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
1
0