awwwd
awwwd

Reputation: 121

Execute classes based on condition in puppet

I want to execute some classes only if a specific rpm version is absent.

For example:

class base{
  if specified_rpm_absent {
    include base::class1
    include base::class2
  }
  else {
    notify {"Already there":}
  }
}

Upvotes: 1

Views: 1900

Answers (1)

Alex Harvey
Alex Harvey

Reputation: 15472

What you can do is define a custom fact that returns true or false depending on the presence or absence of this RPM and then use it in your conditional logic, i.e.

Fact code:

Facter.add(:specified_rpm_absent) do
  setcode do
    # Some Ruby code to return true or false depending on RPM package
    # Facter::Core::Execution.exec() can be used to execute a shell
    # command.
  end
end

Puppet 4

class base {
  if $facts['specified_rpm_absent'] {
    include base::class1
    include base::class2
  }
  else {
    notify {"Already there":}
  }
}

Puppet 3

class base {
  if $::specified_rpm_absent {
    include base::class1
    include base::class2
  }
  else {
    notify {"Already there":}
  }
}

The OP has argued below that it is better to use a puppet function here, and functions also allow arguments.

The problem is that Functions execute on the Puppet master. They do not execute on the Puppet agent. Hence they only have access to the commands and data available on the Puppet master host.

If using Masterless Puppet, however, which is not supported by Puppet, functions could be used for this purpose, and this use-case is described in Jussi Heinonen's book Learning Puppet (2015).

I would not recommend this approach for a few reasons:

  • It is not supported by Puppet, and therefore there is no guarantee that a future version of Puppet will not make this impossible.
  • The code will not be portable. That is, the code can not be shared on the Puppet Forge, and it can not be migrated to a conventional Master/Puppet set up.
  • It is not idiomatic and will confuse people who know Puppet, i.e. violates the Principle of Least Astonishment.

Finally, it should be pointed out that there is probably something more fundamentally wrong with a design that involves making decisions based on whether or not an RPM is installed. Why doesn't Puppet already know if the RPM is installed?

Upvotes: 3

Related Questions