Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Chef | Attribute

概要

Attribute

詳細

Attributeについて。

AttributeはノードやResourceの属性で、固定的ではないものを定義するもの。
例えば、インストール対象のバージョンや設定値など。
DataBagはユーザー等、ノードやResourceに縛られないものを定義する点で異なる。

Attributeはcookbookのattributesのdefault.rbに値を設定しておくことでデフォルト値を
指定することが可能です。

サンプル

git cookbookを作成。
エディタとカラー表示の使用有無をAttributeで設定可能にします。

template/.gitconfig.erbに.gitconfigのテンプレートを作成

[core]
        editor = <%=node['git']['editor']%>
[color]
        ui = <%=node['git']['color']%>

recipe/default.rbにAttributeの作成を想定したrecipeを作成

package "git" do
  action :install
end

template ".gitconfig" do
  path "/home/vagrant/.gitconfig"
  source ".gitconfig.erb"
  owner "vagrant"
  group "vagrant"
  mode 0755
end

attributes/default.rbにデフォルト値を設定

node["git"]["editor"] = "vi"
node["git"]["color"] = "false"

nodes/xxx.jsonにattributeを指定しないで実行

$ git --version
git version 1.7.9.5
$ git config -l
$

attributeを指定して実行

nodes/xxx.jsonにattributeを指定する場合
{
  "git": {
    "editor": "nano",
    "color": "true"
  }
  ,
  "run_list":[" recipe [ rspec_piccolo ], recipe [ git ] "]
}
Vagrantfileにattributeを指定する場合
# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.provider :virtualbox do |vb|
    vb.name = "chef_sample"
    vb.customize ["modifyvm", :id, "--memory", 512]
  end

  config.vm.box = "ubuntu-12.04-x64"
  config.omnibus.chef_version = "11.6.0"

  config.vm.provision :chef_solo do |chef|
    chef.cookbooks_path = ["./cookbooks", "./site-cookbooks"]
    chef.add_recipe "git"
    chef.json = {
      "git" => {
        "editor" => "nano",
        "color" => "true"
      }
    }
  end
end

確認

デフォルトのままプロビジョニング後、確認

※Vagrantfileからchef.jsonを指定せずにプロビジョニングして、デフォルトが適用されることを確認

$ git --version
git version 1.7.9.5
vagrant@precise64:~$ git config -l
core.editor=vi
color.ui=false
Vagrantfileから指定してデフォルトを上書きしてプロビジョニング後、確認
$ git --version
git version 1.7.9.5
$ git config -l
core.editor=nano
color.ui=true