MItamaeでのcookbookの取り込みを少し見やすくする

MItamaeを使っていく中でディレクトリ構成などはItameのBest Practice · itamae-kitchen/itamae Wiki · GitHubを参考にしている

.
├── cookbooks
│   └── nginx
│       ├── default.rb
│       ├── files
│       └── templates
│   └── fluentd
│       ├── default.rb
│       ├── files
│       └── templates
└── roles
    └── web.rb

こんなディレクトリ構成になる
例えば roles/web.rb は下記のようにcookbook内のレシピをincludeする

include_recipe "../cookbooks/nginx"
include_recipe "../cookbooks/fluentd"

実行自体は出来るのだがちょっと見た目を綺麗にしたい
そんな時は helpers/recipe_helper.rb を作成して

module RecipeHelper
  def include_cookbook(name)
    path = File.expand_path("../../cookbooks/#{name}", @recipe.path)
    include_recipe(path)
  end
end

MItamae::RecipeContext.send(:include, RecipeHelper)

それをincludeしてあげると

# これが
include_recipe '../cookbooks/nginx'
include_recipe '../cookbooks/fluentd'

# こうかける
include_recipe '../helpers/recipe_helper'
include_cookbook 'nginx'
include_cookbook 'fluentd'

すこしスッキリした

これはinclude_recipemethodなどのレシピのパスなどをとりあつかっているMItamae::RecipeContextにたいしてRecipeHelperをincludeしてあげることで実行しているレシピの絶対パス@recipe.pathで取得して使うことが出来るのでそれを使うことで本来include_recipe '../cookbooks/nginx'とかくところをinclude_cookbook 'nginx'で済ませるようになる