Class: Chef::DataBagItem

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Mixin::FromFile, Mixin::ParamsValidate
Defined in:
lib/chef/data_bag_item.rb

Constant Summary collapse

VALID_ID =
/^[\-[:alnum:]_]+$/.freeze

Instance Attribute Summary collapse

Attributes included from Mixin::FromFile

#source_file

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Mixin::ParamsValidate

#lazy, #set_or_return, #validate

Methods included from Mixin::FromFile

#class_from_file, #from_file

Constructor Details

#initialize(chef_server_rest: nil) ⇒ DataBagItem

Create a new Chef::DataBagItem


63
64
65
66
67
# File 'lib/chef/data_bag_item.rb', line 63

def initialize(chef_server_rest: nil)
  @data_bag = nil
  @raw_data = Mash.new
  @chef_server_rest = chef_server_rest
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *arguments, &block) ⇒ Object

delegate missing methods to the @raw_data Hash


49
50
51
52
53
54
# File 'lib/chef/data_bag_item.rb', line 49

def method_missing(method_name, *arguments, &block)
  @raw_data.send(method_name, *arguments, &block)
rescue
  # throw more sensible errors back at the user
  super
end

Instance Attribute Details

#raw_dataObject

Returns the value of attribute raw_data


60
61
62
# File 'lib/chef/data_bag_item.rb', line 60

def raw_data
  @raw_data
end

Class Method Details

.chef_server_restObject


73
74
75
# File 'lib/chef/data_bag_item.rb', line 73

def self.chef_server_rest
  Chef::ServerAPI.new(Chef::Config[:chef_server_url])
end

.from_hash(h) ⇒ Object


136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/chef/data_bag_item.rb', line 136

def self.from_hash(h)
  h.delete("chef_type")
  h.delete("json_class")

  item = new
  item.data_bag(h.delete("data_bag")) if h.key?("data_bag")
  if h.key?("raw_data")
    item.raw_data = h["raw_data"]
  else
    item.raw_data = h
  end
  item
end

.load(data_bag, name) ⇒ Object

Load a Data Bag Item by name via either the RESTful API or local data_bag_path if run in solo mode


151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/chef/data_bag_item.rb', line 151

def self.load(data_bag, name)
  if Chef::Config[:solo_legacy_mode]
    bag = Chef::DataBag.load(data_bag)
    raise Exceptions::InvalidDataBagItemID, "Item #{name} not found in data bag #{data_bag}. Other items found: #{bag.keys.join(", ")}" unless bag.include?(name)

    item = bag[name]
  else
    item = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("data/#{data_bag}/#{name}")
  end

  if item.is_a?(DataBagItem)
    item
  else
    item = from_hash(item)
    item.data_bag(data_bag)
    item
  end
end

.object_name(data_bag_name, id) ⇒ Object


111
112
113
# File 'lib/chef/data_bag_item.rb', line 111

def self.object_name(data_bag_name, id)
  "data_bag_item_#{data_bag_name}_#{id}"
end

.validate_id!(id_str) ⇒ Object


42
43
44
45
46
# File 'lib/chef/data_bag_item.rb', line 42

def self.validate_id!(id_str)
  if id_str.nil? || ( id_str !~ VALID_ID )
    raise Exceptions::InvalidDataBagItemID, "Data Bag items must have an id matching #{VALID_ID.inspect}, you gave: #{id_str.inspect}"
  end
end

Instance Method Details

#==(other) ⇒ Object


197
198
199
200
201
202
# File 'lib/chef/data_bag_item.rb', line 197

def ==(other)
  other.respond_to?(:to_h) &&
    other.respond_to?(:data_bag) &&
    (other.to_h == to_h) &&
    (other.data_bag.to_s == data_bag.to_s)
end

#chef_server_restObject


69
70
71
# File 'lib/chef/data_bag_item.rb', line 69

def chef_server_rest
  @chef_server_rest ||= Chef::ServerAPI.new(Chef::Config[:chef_server_url])
end

#createObject

Create this Data Bag Item via RESTful API


192
193
194
195
# File 'lib/chef/data_bag_item.rb', line 192

def create
  chef_server_rest.post("data/#{data_bag}", self)
  self
end

#data_bag(arg = nil) ⇒ Object


91
92
93
94
95
96
97
# File 'lib/chef/data_bag_item.rb', line 91

def data_bag(arg = nil)
  set_or_return(
    :data_bag,
    arg,
    regex: /^[\-[:alnum:]_]+$/
  )
end

#destroy(data_bag = self.data_bag, databag_item = name) ⇒ Object


170
171
172
# File 'lib/chef/data_bag_item.rb', line 170

def destroy(data_bag = self.data_bag, databag_item = name)
  chef_server_rest.delete("data/#{data_bag}/#{databag_item}")
end

#idObject


217
218
219
# File 'lib/chef/data_bag_item.rb', line 217

def id
  @raw_data["id"]
end

#inspectObject


209
210
211
# File 'lib/chef/data_bag_item.rb', line 209

def inspect
  "data_bag_item[#{data_bag.inspect}, #{raw_data["id"].inspect}, #{raw_data.inspect}]"
end

#nameObject


99
100
101
# File 'lib/chef/data_bag_item.rb', line 99

def name
  object_name
end

#object_nameObject


103
104
105
106
107
108
109
# File 'lib/chef/data_bag_item.rb', line 103

def object_name
  raise Exceptions::ValidationFailed, "You must have an 'id' or :id key in the raw data" unless raw_data.key?("id")
  raise Exceptions::ValidationFailed, "You must have declared what bag this item belongs to!" unless data_bag

  id = raw_data["id"]
  "data_bag_item_#{data_bag}_#{id}"
end

#pretty_print(pretty_printer) ⇒ Object


213
214
215
# File 'lib/chef/data_bag_item.rb', line 213

def pretty_print(pretty_printer)
  pretty_printer.pp({ "data_bag_item('#{data_bag}', '#{id}')" => to_hash })
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)

56
57
58
# File 'lib/chef/data_bag_item.rb', line 56

def respond_to_missing?(method_name, include_private = false)
  @raw_data.respond_to?(method_name, include_private) || super
end

#save(item_id = @raw_data["id"]) ⇒ Object

Save this Data Bag Item via RESTful API


175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/chef/data_bag_item.rb', line 175

def save(item_id = @raw_data["id"])
  r = chef_server_rest
  begin
    if Chef::Config[:why_run]
      Chef::Log.warn("In why-run mode, so NOT performing data bag item save.")
    else
      r.put("data/#{data_bag}/#{item_id}", self)
    end
  rescue Net::HTTPClientException => e
    raise e unless e.response.code == "404"

    r.post("data/#{data_bag}", self)
  end
  self
end

#to_hObject Also known as: to_hash


115
116
117
118
119
120
# File 'lib/chef/data_bag_item.rb', line 115

def to_h
  result = raw_data.dup
  result["chef_type"] = "data_bag_item"
  result["data_bag"] = data_bag.to_s
  result
end

#to_json(*a) ⇒ Object

Serialize this object as a hash


125
126
127
128
129
130
131
132
133
134
# File 'lib/chef/data_bag_item.rb', line 125

def to_json(*a)
  result = {
    "name" => object_name,
    "json_class" => self.class.name,
    "chef_type" => "data_bag_item",
    "data_bag" => data_bag,
    "raw_data" => raw_data,
  }
  Chef::JSONCompat.to_json(result, *a)
end

#to_sObject

As a string


205
206
207
# File 'lib/chef/data_bag_item.rb', line 205

def to_s
  "data_bag_item[#{id}]"
end

#validate_id!(id_str) ⇒ Object


77
78
79
# File 'lib/chef/data_bag_item.rb', line 77

def validate_id!(id_str)
  self.class.validate_id!(id_str)
end