【问题标题】:How to set dynamic variable once it is identified to all recipes in a cookbook一旦识别到食谱中的所有食谱,如何设置动态变量
【发布时间】:2021-10-07 16:03:03
【问题描述】:

我需要帮助才能在厨师食谱中设置全局变量。 我有以下系列食谱:

  1. 从路径变量/attibutes/default.rb 中发现tomcat: 默认['tomcat_cookbook']['tomcathome']="['/home/tomcat','/home/ApacheTomcat']" 这个秘籍将识别 tomcat 安装,因为这两个目录中的任何一个目录都可以在服务器上使用。

可以说,如果它将 tomcathome 设置为目录“/home/tomcat”,我还有一些后续配方,例如启动/停止/重启 tomcat。

目前,对于每个配方,我都在停止/启动配方中运行发现逻辑,同时知道在特定服务器上,tomcathome 设置为“/home/tomcat”。

有什么方法可以删除 tomcat home 发现的重复代码,并将已识别的 tomcathome 变量用于剩余的食谱。 请提出建议。

【问题讨论】:

  • 您显示为从路径发现tomcat,是属性,选择其中之一的逻辑是什么/在哪里?您应该使用相关代码更新问题以使其可回答。

标签: ruby chef-infra


【解决方案1】:

我认为这会很好地利用库。我假设食谱名称是tomcat_cookbook。在食谱的libraries 文件夹中,创建一个名为path.rb 的文件。

将以下代码添加到path.rb 文件中。我更喜欢命名我的库以使用 CookbookName::ModuleName 格式组织我的方法。

库/path.rb:

module TomcatCookbook
  module Path
    
    def install_path
      node['tomcat_cookbook']['tomcathome'].each do |path|
        return path if ::Dir.exist?(path)
      end
    end

  end
end

在任何配方中,您都可以包含此模块并使用其中的方法:

# Use this include for use in the recipe
Chef::Recipe.send(:include, TomcatCookbook::Path)

# Use this include for using methods in the directory resource itself
Chef::Resource::Directory.send(:include, TomcatCookbook::Path)

Chef::Log.info("Install Path: #{install_path}")

directory "tomcat_install_path" do
  path install_path
  action :create
end

在某些情况下,我需要创建一个通用食谱,其中仅包含我可以在多个食谱中使用的库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多