Class: EasyType::ResourceTask

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_type/resource_task.rb

Overview

This class is an easy way to create a Puppet task that can:

- list
- get the current status of a named resource
- create a resource
- remove a resouce

Instance Method Summary collapse

Constructor Details

#initialize(type, name_attribute = :name) ⇒ ResourceTask

Returns a new instance of ResourceTask.



15
16
17
18
19
20
21
22
23
# File 'lib/easy_type/resource_task.rb', line 15

def initialize(type, name_attribute = :name )
  @params        = JSON.parse(STDIN.read)
  @action        = @params.fetch('action') {'list'}
  @name          = @params[name_attribute]
  @type          = type
  @resource_type = Puppet::Type.type(type)
  @properties    = @params.fetch('properties') {{}}
  @properties.merge!(:name => @name)
end

Instance Method Details

#all_resourcesObject

Get all resources of the named type



28
29
30
# File 'lib/easy_type/resource_task.rb', line 28

def all_resources
  @resource_type.instances.collect { |e| to_data(e) }
end

#executeObject

Execute the requested action



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/easy_type/resource_task.rb', line 48

def execute
  case @action
  when 'list'
    all_resources
  when 'status'
    to_data(resource)
  when 'create'
    instance = @resource_type.new({ensure: :present}.merge(@properties))
    instance.provider.create
    to_data(resource)
  when 'remove'
    instance = resource
    instance.provider.destroy
    "#{instance} removed."
  else
    fail 'Invalid action specified. Valid values are list, status, create and remove.'
  end
end

#resourceObject

Get the resource who’s name is equal to the specfied name

Raises:

  • (Puppet::Error)


35
36
37
38
39
# File 'lib/easy_type/resource_task.rb', line 35

def resource
  value = @resource_type.instances.find {|e| e.to_hash[:name] == @name }
  raise Puppet::Error, "Resource #{@type}[#{@name}] not found." if value.nil?
  value
end

#to_data(value) ⇒ Object



41
42
43
# File 'lib/easy_type/resource_task.rb', line 41

def to_data(value)
  value.to_resource.to_hash.delete_if { |_k, v| v == :absent } 
end