木偶如何判断是否设置了变量

Ale*_*hen 5 puppet

在a类中,应该如何测试是否设置了变量?现在,我只是在检查变量是否未定义:

if $http_port != undef {
  $run_command = "$run_command --http-port $http_port"
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来检查变量是否已声明?

小智 7

如果要测试变量是否为undef,则方法是正确的。写作

if $http_port {
  $run_command = "$run_command --http-port $http_port"
}
Run Code Online (Sandbox Code Playgroud)

将完成几乎相同的操作。如果$ http_port为undef或false,它将不会运行该命令。

如果要测试是否已定义var,则应该执行以下操作:

if defined('$http_port') {
  $run_command = "$run_command --http-port $http_port"
}
Run Code Online (Sandbox Code Playgroud)

请参阅https://docs.puppet.com/puppet/4.10/function.html#defined

如果var是一个类变量,则可以执行以下操作:

class your_class (
Optional[Integer[0, 65535]] $http_port = undef,
) {
    if $http_port {
      notify { "got here with http_port=${http_port}": }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,仅当使用http_port设置为0到65535之间的整数声明该类时,它才会运行notify。

  • @Jimadine 仅当“$http_port”为“已定义”且设置为“true”时,“if $http_port”才被视为“true”。在所有其他情况下,此条件均不满足(为假)。另一方面,“if Defined('$http_port')”仅验证变量“$http_port”是否设置为任何值(由值定义)。在所有其他情况下,此条件都将失败。 (2认同)