在 rub 中获取特定主机的 IP 地址

To get IP addres of the specific host machine in rub

我想找到其他系统的IP地址。例如,我正在从服务器 wevrs1234 执行我的代码,我想要服务器 apvrs1234 的 IP 地址并将其存储在变量中。请帮我弄到这个。

ip = IPSocket.getaddress(Socket.gethostname)

是我目前的代码。

根据建议,我编写了这段代码,但出现错误。请找到我的代码

 publish_vm = node['aem_dispatcher_cookbook']['publish'].to_s
  nodes = search(:node, 'hostname:publish_vm')
 node.default['aem_dispatcher_cookbook']['ip_address'] = 'nodes.first['ipaddress']'

  template node['aem_dispatcher_cookbook']['owner']['home'] + '/conf.d/publish_farm.any' do
    source   'publish_farm.any.erb'
    owner    node['aem_dispatcher_cookbook']['owner']['user']
    group    node['aem_dispatcher_cookbook']['owner']['group']
    mode     '0755'
    variables(
      publish_host: node['aem_dispatcher_cookbook']['publish'],
      publish_port: node['aem_dispatcher_cookbook']['publish_port'],
      ip_addr: node['aem_dispatcher_cookbook']['ip_address']
    )
  end

错误

[2020-05-20T06:09:52-05:00] DEBUG: Node wevrd64501.uhc.com loading cookbook aem_dispatcher_cookbook's attribute file /root/.chef/local-mode-cache/cache/cookbooks/aem_dispatcher_cookbook/attributes/default.rb

================================================================================
Recipe Compile Error in /root/.chef/local-mode-cache/cache/cookbooks/aem_dispatcher_cookbook/recipes/default.rb
================================================================================

SyntaxError
-----------
/root/.chef/local-mode-cache/cache/cookbooks/aem_dispatcher_cookbook/recipes/default.rb:333: syntax error, unexpected tIDENTIFIER, expecting keyword_end
...ess'] = 'nodes.first['ipaddress']'
...                      ^~~~~~~~~

System Info:

您用 [chef] 和 [chef-recipe] 标记了问题,所以我知道您正试图在 recipe 中获取另一台机器的 IP 地址。如果另一台机器也注册了 Chef Server,最简单的是 search。您可以通过某些属性搜索在 Chef 服务器上注册的任何机器,在您的例子中是主机名。

nodes = search(:node, 'hostname:<another_vm_hostname>')
p nodes.first['ipaddress']

更新:

您的第 3 行有误。不要用引号将 nodes.first['ipaddess'] 括起来。

 node.default['aem_dispatcher_cookbook']['ip_address'] = nodes.first['ipaddress']
publish_vm = node['aem_dispatcher_cookbook']['publish'].to_s
  ruby_block 'get_ip_from_publish' do
    block do
      Chef::Resource::RubyBlock.send(:include, Chef::Mixin::ShellOut)
      command1 = "nslookup #{publish_vm} |grep '^Address' | awk '{print }'| tail -1"
      command_out = shell_out(command1)
      node.run_state['master_ip'] = command_out.stdout
    end
    action :run
  end

这段代码帮助我获取了所需主机的 IP 地址