根据 puppet 中的条件执行 类

Execute classes based on condition in puppet

我只想在缺少特定 rpm 版本的情况下执行一些 类。

例如:

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

您可以做的是根据此 RPM 的存在与否定义 custom fact returns true 或 false,然后在您的条件逻辑中使用它,即

事实代码:

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

人偶 4

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

人偶 3

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

OP 在下面争论说最好在这里使用 puppet 函数,而且函数也允许参数。

问题是 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.

但是,如果使用 Puppet 不支持的 Masterless Puppet,函数可以用于此目的,Jussi Heinonen 的书 Learning Puppet (2015) 中描述了这个用例。

出于以下几个原因,我不推荐这种方法:

  • Puppet 不支持它,因此不能保证 Puppet 的未来版本不会使这成为不可能。
  • 代码不可移植。也就是说,代码无法在 Puppet Forge 上共享,也无法迁移到常规 Master/Puppet 设置。
  • 这不是惯用语,会让了解 Puppet 的人感到困惑,即违反了 Principle of Least Astonishment

最后,应该指出的是,涉及根据是否安装 RPM 做出决定的设计可能存在更根本的错误。为什么 Puppet 不知道 RPM 是否已安装?