3

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']).

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
4

4 回答 4

14

这里问题的根源是您将变量 fqdn 设置在 ruby​​_block 的范围内,并试图在编译阶段引用该变量。ruby_block 资源允许在收敛阶段运行 ruby​​ 代码。

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

fqdn = // logic to get fqdn

file '/tmp/file' do
  content "fqdn=#{fqdn}"
end
于 2014-05-08T20:15:08.637 回答
11

我在 Chef 文档中找到了这个。我遇到了类似的问题。我要试试node.run_state。此信息位于本页底部https://docs.chef.io/recipes.html

用于node.run_state在 chef-client 运行期间存储瞬态数据。该数据可以在资源之间传递,然后在执行阶段进行评估。run_state是一个空的哈希,总是在厨师客户端运行结束时被丢弃。

例如,以下配方将安装 Apache Web 服务器,随机选择 PHP 或 Perl 作为脚本语言,然后安装该脚本语言:

package "httpd" do
  action :install
end

ruby_block "randomly_choose_language" do
  block do
    if Random.rand > 0.5
      node.run_state['scripting_language'] = 'php'
    else
      node.run_state['scripting_language'] = 'perl'
    end
  end
end

package "scripting_language" do
  package_name lazy { node.run_state['scripting_language'] }
  action :install
end
于 2014-11-02T20:24:33.740 回答
1

请点击此链接 http://lists.opscode.com/sympa/arc/chef/2015-03/msg00266.html 您可以使用 node.run_state[:variables] 将一个变量解析为另一个配方

这是我的代码:: file.rb

node.run_state[:script_1] = "foo" include_recipe 'provision::copy'

并在其他 copy.rb 文件中放入以下代码::

复制.rb

filename = node.run_state[:script_1] puts "Name is #{filename}"

于 2017-02-03T07:05:58.593 回答
1

我用于node.run_state['variable']相同的目的并成功地做到了。请在下面找到基本示例代码。

ruby_block "resource_name" do
   block do
     node.run_state['port_value'] = 1432
   end
end

ruby_block "resource_name2" do
   block do
      num = node.run_state['variable']
   end
end

我希望它会有所帮助。

于 2017-10-30T06:58:47.750 回答