本节书摘来自异步社区《Puppet实战手册》一书中的第2章,第2.11节,作者:【英】John Arundel著,更多章节内容可以访问云栖社区“异步社区”公众号查看
in运算符可以用来测试一个字符串中是否包含另一个字符串,下面是一个例子。
if 'spring' in 'springfield'如果字符串spring是springfield的子字符串(事实上是这样的),则上面表达式的值为true。in运算符也可以用于数组的包含关系测试,如下:
if $crewmember in ['Frank', 'Dave', 'HAL' ]当in运算符同散列一起使用时,它会测试当前字符串是否是散列的键。
$interfaces = { 'lo' => '127.0.0.1', 'eth0' => '192.168.0.1' } if 'eth0' in $interfaces { notify { "eth0 has address ${interfaces['eth0']}": } }操作步骤下面的步骤将展示如何使用in运算符。
1. 将下面的代码加入到清单文件中。
if $::operatingsystem in [ 'Ubuntu', 'Debian' ] { notify { 'Debian-type operating system detected': } } elsif $::operatingsystem in [ 'RedHat', 'Fedora', 'SuSE', 'CentOS' ] { notify { 'RedHat-type operating system detected': } } else { notify { 'Some other operating system detected': } }2. 运行Puppet:
ubuntu@cookbook:~/puppet$ papply Notice: Debian-type operating system detected Notice: /Stage[main]/Admin::Test/Notify[Debian-type operating system detected]/message: defined 'message' as 'Debian-type operating system detected' Notice: Finished catalog run in 0.08 seconds更多参考in表达式的返回值是布尔值(true或false),因此,可以将它赋值给一个变量。
$debianlike = $::operatingsystem in [ 'Debian', 'Ubuntu' ] if $debianlike { notify { 'You are in a maze of twisty little packages, all alike': } }