ページ ツリー
メタデータの末尾にスキップ
メタデータの先頭に移動

このページの古いバージョンを表示しています。現在のバージョンを表示します。

現在のバージョンとの相違点 ページ履歴を表示

« 前のバージョン バージョン 3 次のバージョン »

Attribute による Recipe の制御

Attribute とは

Recipe にパラメータを与える仕組みです。
Attribute は Key-Value 形式のデータで、プロビジョニング時に指定しておくと、Recipe からその値を自由に参照できます。
それにより、Recipe をより柔軟に記述できるようになります。

 

Attribute に値を指定する

Attibute の指定方法はプロビジョニングの方法により異なります。

Kitchen の場合

.kitchen.yml の attributes に YAML 形式で指定します。

.kitchen.yml
attributes:
  application:
    version: ‘2.0.0’

Vagrant の場合

Vagrantfile の chef.json に Hash で指定します。

Vagrantfile
config.vm.provision :chef_solo do |chef|  chef.json = {
    application: {
      version: ‘2.0.0’
    }
  }

Knife の場合

knife node edit コマンドを実行し、Json ファイルを直接編集して指定します。

"normal": {
  "application": {
    "version": "2.0.0"
  }
}

※ knife での運用はしていないので、間違っているかもしれません。

 

Attribute の値を Recipe で使用する

Recipe から Attribute の値を参照するには、node オブジェクトを使用します。

Attribute の指定

.kitchen.yml
attributes:
  application:
    version: '2.0.0'

Recipe で Attribute の値を参照

./recipes/default.rb
application_version = node[‘application’][‘version’] # application_version == '2.0.0'

 

Attribute にデフォルト値を設定する

Attribute には、値が指定されなかった場合のデフォルト値をあらかじめ指定しておくことができます。

デフォルト値は専用のファイルに記述します。
このファイルは chef コマンドで生成できます。

chef generate attribute ./ default

./attributes/default.rb というファイルが生成されますので、以下のようにデフォルト値を定義します。

./attributes/default.rb
default[‘application’][‘version’] = ‘1.0.0’

 

jenkins Cookbook を Attribute に対応させる

何を Attribute にするか

Cookbook の設計次第で何を Attribute にするかは変わりますが、
今回は次の項目を Attribute にしてみましょう。 

Jenkins のバージョン

特定のバージョンの Jenkins をインストールしたくなったときに、Recipe を直したくない
同じ Recipe で複数のバージョンの Jenkins をインストールできるようにしておきたい 

Jenkins の rpm ファイルの URL

将来的に rpm ファイルの URL が変更されたときに、Recipe を直したくない

Jenkins の実行ユーザー

プロビジョン先のサーバーによっては実行ユーザーを変えないといけないかもしれない

 

ヒント

Attribute の名前

一般的には、以下のように node[<Cookbook 名>][<任意の Attribute 名>] とすることが多いようです。

.kitchen.yml
attributes:
  <Cookbook 名>:
    <任意の Attribute 名>:

Recipe では cookbook_name Method [ http://docs.opscode.com/dsl_recipe_method_cookbook_name.html ] を用いることで、自身の Cookbook 名を取得することもできます。

value = node[cookbook_name]['attribute']

※ ./attribute/default.rb では cookbook_name Method を使用できません。

 

Kitchen で確認

Attribute への対応が完了したら、.kitchen.yml を編集し、Kitchen インスタンスで動作チェックをしてみましょう。

 

 

  • ラベルがありません