Using a variable inside a Chef recipe

前端 未结 4 910
终归单人心
终归单人心 2021-01-14 09:48

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

In

相关标签:
4条回答
  • 2021-01-14 10:23

    I used node.run_state['variable'] for the same purpose and was successfully able to do it. Please find basic sample code below.

    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
    

    I hope it will help.

    0 讨论(0)
  • 2021-01-14 10:27

    Please follow this link http://lists.opscode.com/sympa/arc/chef/2015-03/msg00266.html you can use node.run_state[:variables] for parsing one variable to another recipe

    Here is my code :: file.rb

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

    and in other copy.rb file put following code ::

    copy.rb

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

    0 讨论(0)
  • 2021-01-14 10:28

    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.

    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
    
    0 讨论(0)
  • 2021-01-14 10:47

    I found this in the Chef docs. I ran into a similar issue. I am going to try the node.run_state. This information is found at the bottom of this page https://docs.chef.io/recipes.html

    Use node.run_state to stash transient data during a chef-client run. This data may be passed between resources, and then evaluated during the execution phase. run_state is an empty Hash that is always discarded at the end of the chef-client run.

    For example, the following recipe will install the Apache web server, randomly choose PHP or Perl as the scripting language, and then install that scripting language:

    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
    
    0 讨论(0)
提交回复
热议问题