

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 模板
<a name="workingcookbook-installingcustom-components-templates"></a>

**重要**  
该 AWS OpsWorks Stacks 服务于 2024 年 5 月 26 日终止，新客户和现有客户均已禁用。我们强烈建议客户尽快将其工作负载迁移到其他解决方案。如果您对迁移有疑问，请通过 re [AWS : Post 或通过 Pre](https://repost.aws/) mium Su [AWS pp](https://aws.amazon.com/support) ort 与 AWS 支持 团队联系。

您通过创建配置文件并将它放置在合适的目录中来配置许多程序包。您可以在说明书中包含一个配置文件并将它复制到合适的目录中，但更为灵活的方法是让您的配方从一个模板创建配置文件。模板的一个优势是，您可以使用属性来定义模板的值。例如，这允许您通过使用自定义 JSON 覆盖相应的属性值来修改配置文件，而不用接触到说明书。

模板与关联的文件具有基本相同的内容和结构。下面给出了一个示例文件 `httpd.conf`。

```
ServerRoot "<%= node[:apache][:dir] %>"
<% if node[:platform] == "debian" || node[:platform] == "ubuntu" -%>
  LockFile /var/lock/apache2/accept.lock
<% else -%>
   LockFile logs/accept.lock
<% end -%>
PidFile <%= node[:apache][:pid_file] %>
Timeout <%= node[:apache][:timeout] %>
KeepAlive <%= node[:apache][:keepalive] %>
MaxKeepAliveRequests <%= node[:apache][:keepaliverequests] %>
KeepAliveTimeout <%= node[:apache][:keepalivetimeout] %>
<IfModule mpm_prefork_module>
    StartServers          <%= node[:apache][:prefork][:startservers] %>
    MinSpareServers       <%= node[:apache][:prefork][:minspareservers] %>
    MaxSpareServers       <%= node[:apache][:prefork][:maxspareservers] %>
    ServerLimit           <%= node[:apache][:prefork][:serverlimit] %>
    MaxClients            <%= node[:apache][:prefork][:maxclients] %>
    MaxRequestsPerChild   <%= node[:apache][:prefork][:maxrequestsperchild] %>
</IfModule>
...
```

以下示例是一个为 Ubuntu 实例生成的 `httpd.conf` 文件：

```
ServerRoot "/etc/httpd"
LockFile logs/accept.lock
PidFile /var/run/httpd/httpd.pid
Timeout 120
KeepAlive Off
MaxKeepAliveRequests 100
KeepAliveTimeout 3
<IfModule mpm_prefork_module>
    StartServers          16
    MinSpareServers       16
    MaxSpareServers       32
    ServerLimit           400
    MaxClients            400
    MaxRequestsPerChild   10000
</IfModule>
...
```

此模板的许多文本只是简单地从模板复制到 `httpd.conf` 文件。但是，`<%= ... %>` 内容的处理方式如下所示：
+ Chef 将 `<%= node[:attribute][:sub_attribute][:...]%>` 替换为属性的值。

  例如，`StartServers <%= node[:apache][:prefork][:startservers] %>` 变为 `httpd.conf` 中的 `StartServers 16`。
+ 您可以使用 `<%if-%>, <%else-%>, and <%end-%>` 来有条件地选择一个值。

  该示例根据平台为 `accept.lock` 设置了一个不同的文件路径。

**注意**  
您并非仅限于使用说明书的属性文件中的属性。您可以使用实例的节点对象中的任何属性。例如，由名为 [Ohai](https://docs.chef.io/ohai.html) 的 Chef 工具生成且合并到节点对象中。有关属性的更多信息，请参阅[覆盖属性](workingcookbook-attributes.md)。

有关模板的更多信息，包括如何合并 Ruby 代码，请参阅[关于模板](http://docs.chef.io/templates.html)。