【问题标题】:How to read a file content at execution time? Chef reads at compile time如何在执行时读取文件内容? Chef 在编译时读取
【发布时间】:2013-03-19 17:19:04
【问题描述】:

因为我遇到了已报告给 Mixlib 团队的 MIXLIB-11 错误,我需要找到一个替代方案,即 Mixlib::Shellout 的替代方案。

简单介绍一下问题:

Here 是一个声明“*毫不奇怪——读取发生在编译时,但 remote_file 资源实际上是在执行时创建的。**”

由于此功能,Mixlib::Shellout.new("ls", :cwd => '/opt/cubrid/share/webmanager') 会引发“No such file or directory”错误,即使该目录是由当前配方中包含的先前配方在执行时创建的。

有没有办法在执行时读取文件/目录?

【问题讨论】:

    标签: ruby io chef-infra


    【解决方案1】:

    找到答案:将代码包装在ruby_block中,运行时执行。

    ruby_block "Check if CURBID Web Manager needs installation" do
      block do
        version = ""
    
        if File.exists?("#{CWM_HOME_DIR}/appLoader.js")
          # Read the CWM version from file.
          f = File.open("#{CWM_HOME_DIR}/appLoader.js")
    
          pattern = /Ext\.cwm\.prodVersion = '(\d+\.\d+\.\d+\.\d+)'/
    
          f.each {|line|
            if match = pattern.match(line)
              version = match[1]
              break
            end
          }
    
          f.close
        end
      end
    end
    

    现在版本已从上一个配方中创建的文件正确填充。

    【讨论】:

      【解决方案2】:

      如果使用自定义资源,可以使用load_current_value 方法。

      action :some_action do
      
        load_current_value do
          if File.exist?('/var/www/html/index.html')
            homepage IO.read('/var/www/html/index.html')
          end
          if File.exist?('/var/www/html/404.html')
            page_not_found IO.read('/var/www/html/404.html')
          end
        end
      
      end
      

      https://docs.chef.io/dsl_custom_resource.html

      【讨论】:

        【解决方案3】:

        我个人更喜欢在执行过程中使用type命令将文件读入变量中。

        简单的将文件读入变量,可以试试

        ruby_block 'Read IP file into v_ip variable' do
           block do
               if File.exists?("#{v_ip_folder}\\ip.txt")
                  v_ip = %x(type "#{v_ip_folder}\\ip.txt")
                  Chef::Log.info("#{v_ip}")
               end
           end
        end 
        

        %x(type "#{v_ip_folder}\\ip.txt") 将在命令提示符下运行type 命令并将输出返回到指定的v_ip 变量。

        【讨论】:

        • type 命令是一个特定于 windows 的命令,在 unix 上具有完全不同的行为。因此,您应该使用 ruby​​ 文件 i/o 命令而不是执行系统实用程序。
        【解决方案4】:

        考虑remote_file。它在执行(运行)时执行,也可以与本地文件一起使用,例如:

        remote_file "Copy file" do
          path "file:///opt/destination.txt"
          source "file:///opt/source.txt"
          owner 'root'
          group 'root'
          mode 0755
        end
        

        所以使用remote_file 是很好的解决方法。编写自定义代码需要时间并且容易出错。 另见this answer。

        【讨论】:

        • remote_file 用于传输(或复制)文件,而不是用于读取。
        • 您的解决方案没有回答问题
        猜你喜欢
        • 2014-04-19
        • 2011-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-12
        • 1970-01-01
        相关资源
        最近更新 更多