【问题标题】:How to use dynamic variables defined in chef recipe to replace the expression in template file如何使用厨师食谱中定义的动态变量来替换模板文件中的表达式
【发布时间】:2021-08-09 14:55:29
【问题描述】:

我遇到了一种情况,我创建了一个包含以下内容的模板/test.sh.erb 文件:

#!/bin/bash

ls -ltr <%= "#{tomcat_home}/instance1/bin" %>
ls -ltr <%= "#{tomcat_home}/instance1/conf" %>

对于这个 erb 文件,我想传递“tomcat_home”,它可以是“/opt/tomcat”或“/opt/apacheTomcat”。我正在使用 if else 条件解析此数据,该条件将我的 tomcat 返回此路径之一。

eg: tomcat_home="/opt/tomcat"

我想在服务器上的 /tmp 位置创建 test.sh 文件,我想在创建 test.sh 文件时动态替换 tomcat_home 变量。 模板资源逻辑:

    template "/tmp/test.sh" do
        source 'test.sh.erb' # <-- this is your directory in files/default/local_directory
        owner 'tomcat'                                                                 
        group 'tomcat'
        mode '0755'
        action :create                                                                   
    end    

当模板资源运行时我期望的输出:

#!/bin/bash

ls -ltr /opt/tomcat/instance1/bin
ls -ltr /opt/tomcat/instance1/conf

【问题讨论】:

    标签: ruby chef-infra


    【解决方案1】:

    对于Chef templates.erb 文件)中的变量插值,应使用&lt;%= %&gt; 标记。在您的情况下,只有 tomcat_home 变量应该在这些标记内,即 &lt;%= tomcat_home %&gt;

    另外,需要模板的文件应该在&lt;cookbook_name&gt;/templates/default 目录下。 files/ 目录用于存放静态文件,其中变量插值不会发生

    例子:

    templates/default/test.sh.erb:

    #!/bin/bash
    
    ls -ltr <%= @tomcat_home %>/instance1/bin
    ls -ltr <%= @tomcat_home %>/instance1/conf
    

    然后在配方中:

    template '/tmp/test.sh' do
      source 'test.sh.erb'
      owner 'tomcat'                                                                 
      group 'tomcat'
      mode '0755'
      variables(
        tomcat_home: '/opt/tomcat'
      )
    end
    

    注意:create 操作是template 资源的默认操作,所以我省略了它。此外,模板可以直接引用节点属性,例如:

    ls -ltr <%= node['cookbook_name']['tomcat_home'] %>/instance1/bin
    

    【讨论】:

    • 感谢 Seshadri。有效。我有另一个问题,我正在运行一个 shell 脚本,当我手动触发它时,我得到的退出代码为 4,但是当我用 bash resorce 触发它的执行脚本但抛出错误为“>>>> 由 Mixlib 引起:: ShellOut::ShellCommandFailed: 预期进程以 [0] 退出,但收到 '4'" 。任何帮助将不胜感激。
    • 由于命令以非零代码退出,因此被认为是失败的命令。您介意创建一个包含所需详细信息的新问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 2021-04-18
    相关资源
    最近更新 更多