在厨师食谱中使用变量 [英] Using a variable inside a Chef recipe

查看:60
本文介绍了在厨师食谱中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Chef-cookbook-hostname cookbook设置节点的主机名。我不希望我的主机名被硬编码在属性文件中(默认['set_fqdn'])。

I'm using chef-cookbook-hostname cookbook to setup node's hostname. I don't want my hostname to be hard coded in the attribute file (default['set_fqdn']).

相反,将从虚拟机定义XML文件中读取主机名。我想出了以下默认配方,但显然变量fqdn没有给出值。有什么主意为什么会发生这种情况或更好地完成我的任务?

Instead the hostname will be read from a VM definition XML file. I come up with the following default recipe but apparently the variable fqdn is not given value. Is there any idea why this happens or any better to achieve my task?

ruby_block "Find-VM-Hostname" do
   block do
     require 'rexml/document'
     require 'net/http'
     url = 'http://chef-workstation/services.xml'
     file = Net::HTTP.get_response(URI.parse(url)).body
     doc = REXML::Document.new(file)
     REXML::XPath.each(doc, "service_parameters/parameter") do |element|
     if element.attributes["name"].include?"Hostname"
        fqdn = element.attributes["value"]  #this statement does not give value to fqdn
     end
     end
    end
    action :nothing
end
if fqdn
  fqdn = fqdn.sub('*', node.name)
  fqdn =~ /^([^.]+)/
  hostname = Regexp.last_match[1]

  case node['platform']
   when 'freebsd'
    directory '/etc/rc.conf.d' do
      mode '0755'
    end

    file '/etc/rc.conf.d/hostname' do
      content "hostname=#{fqdn}\n"
      mode '0644'
      notifies :reload, 'ohai[reload]'
     end
   else
    file '/etc/hostname' do
       content "#{hostname}\n"
       mode '0644'
       notifies :reload, 'ohai[reload]', :immediately
    end
   end


推荐答案

问题源是您在ruby_b范围内设置变量fqdn锁定,并在编译阶段尝试引用该变量。使用ruby_block资源可以在收敛阶段运行ruby代码。

The source of the problem here is that you are setting the variable fqdn inside the scope of a ruby_block and are attempting to make reference to that variable at the compilation phase. The ruby_block resources allows the ability to run ruby code during the convergence phase.

鉴于您似乎正在使用fqdn来设置资源集,看起来您好像可以从红宝石代码周围删除红宝石块。例如

Given that you appear to be using the fqdn to setup the resource set, it looks as though you can remove the ruby block from around the ruby code. e.g.

fqdn = // logic to get fqdn

file '/tmp/file' do
  content "fqdn=#{fqdn}"
end

这篇关于在厨师食谱中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆