企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### 书写强大的条件语句 生活充满选择。Puppet 的 if 语句允许基于变量或表达式的值应用不同的配置代码。 使用 if 语句,你可以根据当前节点的实际情况应用不同的资源或参数值,例如: 操作系统或内存大小。举例来说,数据中心A中的节点和数据中心B中的节点可能需要使用不同的 DNS 服务器;对 Ubuntu 系统和其他系统可能需要执行不同类的集合。 #### 操作步骤 在你的配置清单中添加如下的代码: ``` if $lsbdistid == "Ubuntu" { notice("Running on Ubuntu") } else { notice("Non-Ubuntu system detected. Please upgrade to Ubuntu immediately.") } ``` #### 工作原理 Puppet 对 if 关键字之后的内容视为表达式并对其进行评估。若表达式的值为 true, Puppet 将执行大括号内的代码。 另外,你还可以使用 else 分支,它将在表达式的值为 false 时执行。 #### 更多用法 虽然你可以在 Puppet 中写出很复杂的 if 语句,但是我不建议你这么做。 很多时候,改变你的设计思路(例如,使用模板)比使用 if 语句要好。 从我用于生产环境的一些配置清单实例来看,我惊讶地发现,在所有的几千行代码中都没有使用 if 语句。尽管如此,你的里程可能会有所不同,所以下面给出一些使用 if 的技巧。 ##### elsif 你可以添加 elsif 关键字进行进一步的测试,例如: ``` if $lsbdistid == "Ubuntu" { notice("Running on Ubuntu") } elsif $lsbdistid == "Debian" { notice("Close enough…") } else { notice("Non-Ubuntu system detected. Please upgrade to Ubuntu immediately.") } ``` ##### 比较 你可以使用 == 语法检查两个值是否相同,例如: ``` if $lsbdistid == "Ubuntu" { ... } ``` 或者使用 != 语法检查两个值是否不同,例如: ``` if $lsbdistid != "CentOS" { ... } ``` 你也可以使用 &lt; 和 &gt; 比较两个数值,例如: ``` if $uptime_days > 365 { notice("Really .. there have been kernel security patches out there for ages, you will so be 0wned!") } ``` 还可以使用 &lt;= 或 &gt;= 对数值进行比较: ``` if $lsbmajdistrelease <= 9 { ... } ``` ##### 复杂表达式 你可以把上述代码片段中的一些简单表达式组合成更复杂的逻辑表达式, 逻辑表达式使用与(and)、或(or)和非(not)连接简单表达式,例如: ``` if ($uptime_days > 365) and ($lsbdistid == "Ubuntu") { ... } if ($role == "webserver") and ( ($datacenter == "A") or ($datacenter == "B") ) { ... } ``` #### 参见本书 * 第 3 章的 [在 if 语句中使用正则表达式](#ch03sec08) 一节 * 第 3 章的 [检测字符串中是否包含指定的值](#ch03sec10) 一节 * 第 3 章的 [使用选择器和 case 语句](#ch03sec09) 一节