在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。