Ask Your Question
0

Custom types: How to make a property mandatory

asked 2015-04-13 08:10:25 -0500

Arney gravatar image

updated 2015-04-13 16:20:17 -0500

In the following minimal example I tried to make the address property mandatory

# lib/puppet/type/customer.rb
Puppet::Type.newtype(:customer) do
  ensurable

  newparam(:name)
  newproperty(:address)

  validate do
    fail("Address is mandatory.") if self[:address].nil?
  end
end

Using the dummy provider

# lib/puppet/provider/customer/company.rb
Puppet::Type.type(:customer).provide(:company, parent: Puppet::Provider) do
  mk_resource_methods

  def self.instances
    instances = []
    instances << new(name: 'Peter', ensure: 'present', address: 'New York')
    instances
  end

  def exists?
    @property_hash[:ensure] == :present
  end

  def create
    true # Method stubbed
  end
end

I get the following:

  • Applying this manifest passes

    customer { 'Paul': ensure  => present, address => 'Alabama', }
    
  • Applying this manifest fails as intended

    customer { 'Paul': ensure  => present, }
    
  • Problem: puppet resource customer also fails with "Address is mandatory." despite address being provided.

Did I make an error or is that an error in Puppet (I'm using 3.7.4 on Ruby 1.9.3)?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2015-04-13 17:36:10 -0500

Arney gravatar image

updated 2015-04-13 17:59:31 -0500

As Frank Felix points out

"this is a very unusual structure. Properties that are not assigned a desired value will just be left as is by the agent."

So the important question to ask is why should this property be mandatory? When do we actually need it?

In my case, the property is mandatory for the creation of the resource, so the way to go is to fail during creation:

# lib/puppet/provider/customer/company.rb
Puppet::Type.type(:customer).provide(:company, parent: Puppet::Provider) do
  mk_resource_methods

  def self.instances
    instances = []
    instances << new(name: 'Peter', ensure: 'present', address: 'New York')
    instances
  end

  def exists?
    @property_hash[:ensure] == :present
  end

  def create
    fail("Address is mandatory.") if resource[:address].nil?

    true # Method stubbed
  end
end

The type can now be reduced to

# lib/puppet/type/customer.rb
Puppet::Type.newtype(:customer) do
  ensurable

  newparam(:name)
  newproperty(:address)
end
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2015-04-13 08:10:25 -0500

Seen: 443 times

Last updated: Apr 13 '15