chefでカスタムリソースを作る
自分独自のResourceを作成します。
作成したファイルは以下の通り
├── providers
│ └── test.rb
├── recipes
│ └── default.rb
├── resources
│ └── test.rb
* resources
カスタムResourceのAttributeの設定。
* providers
定義したResourceの実際の処理の部分。
resources
# resources/test.rb # ここで利用出来るアクションの設定 # actions :action_name1, :action_name2, :action_name... actions :foo, :bar # actionが何も指定されなかったとき、実行するアクション # default_action :action_name1 default_action :foo # Attributeの設定 # attribute :attribute_name, :kind_of => value, :validation_parameter => value attribute :name, :kind_of => String, :name_attribute => true attribute :type, :kind_of => String, :default => "bar"
:name_attribute => trueとは、リソースの後に追加される文字列のこと
以下では”test foo”が該当する。
custom_resource_test "test foo" do end
providers
new_resource.attribute_nameでresources/test.rbに
設定している
# providers/test.rb # resources/test.rbで定義したアクションの処理を記述 # new_resource.nameは以下の “test foo”の部分と一致する # custom_resource_test "test foo" do # end action :foo do p "#{new_resource.name}" p "#{new_resource.type}" end action :bar do p "#{new_resource.name}" p "#{new_resource.type}" bash "test" do user "root" code <<-EOH echo #{new_resource.type} EOH end end
recipes
COOKBOOKNAME_FILENAMEがリソース名となる。
FILENAMEがdefault.rbの場合、COOKBOOKNAMEがリソース名。
今回は、custom_resourceがCOOKBOOKNAMEで
providers/test.rbとresources/test.rbがあるため
リソース名は`custom_resource_test`となる
# recipes/default.rb custom_resource_test "test foo" do end custom_resource_test "test bar" do action :bar type "bar type" end
Chefのバージョンによってdefault_actionの書き方が異なるので 注意 。
ただ現状はif defined?(default_action)がなくても動く。
actions :create, :destroy default_action :create if defined?(default_action) # Chef > 10.8 # Default action for Chef <= 10.8 def initialize(*args) super @action = :create end