deepak
deepak

Reputation: 8070

how to query attributes inside a role in chef?

I am using chef version 10.16.2
I have a role (in ruby format). I need to access an attrubute set in one of the cookbooks

eg.

name "basebox"
description "A basic box with some packages, ruby and rbenv installed"

deployers = node['users']['names'].find {|k,v| v['role'] == "deploy" }

override_attributes {
  {"rbenv" => {
      "group_users" => deployers
    }
  }
}

run_list [ 
          "recipe[users]",
          "recipe[packages]",
          "recipe[nginx]",
          "recipe[ruby]"
         ]

I am using chef-solo so i cannot use search as given on http://wiki.opscode.com/display/chef/Search#Search-FindNodeswithaRoleintheExpandedRunList

How do i access node attributes in a role definition ?

Upvotes: 3

Views: 2242

Answers (2)

jtimberman
jtimberman

Reputation: 8258

Roles are JSON data.

That is, when you upload the role Ruby file to the server with knife, they are converted to JSON. Consider this role:

name "gaming-system"
description "Systems used for gaming"
run_list(
  "recipe[steam::installer]",
  "recipe[teamspeak3::client]"
)

When I upload it with knife role from file gaming-system.rb, I have this on the server:

{
  "name": "gaming-system",
  "description": "Systems used for gaming",
  "json_class": "Chef::Role",
  "default_attributes": {
  },
  "override_attributes": {
  },
  "chef_type": "role",
  "run_list": [
    "recipe[steam::installer]",
    "recipe[teamspeak3::client]"
  ],
  "env_run_lists": {
  }
}

The reason for the Ruby DSL is that it is "nicer" or "easier" to write than the JSON. Compare the lines and syntax, and it's easy to see which is preferable to new users (who may not be familiar with JSON).

That data is consumed through the API. If you need to do any logic with attributes on your node, do it in a recipe.

Upvotes: 2

turtlebender
turtlebender

Reputation: 1907

Not sure if I 100% follow, but if you want to access an attribute which is set by a role from a recipe, then you just call it like any other node attribute. For example, in the case you presented, assuming the node has the basebox role in its run_list, you would just call:

node['rbenv']['group_users']

The role attributes are merged into the node.

HTH

Upvotes: 0

Related Questions