Ruby ハッシュが入力されない
概要
私は Chef で作業しており、nmcli によって設定されたネットワーク デバイス情報を含む Ruby ハッシュを作成/設定しようとしています。 VS Codeは文句を言っていないので、コードは正しいと思います。chef-shell -zでも問題なく動作しているようですが、期待どおりにRubyハッシュをクエリできません。実際に始めています。正気を失うこと。
新鮮な目と専門家の助けをいただければ幸いです。ありがとうございます!
interfaces = Hash.new
#DEVICE,TYPE
dev = Mixlib::ShellOut.new("nmcli -terse -field device,type device").run_command.stdout.split(/\n/)
dev.each do |output|
if "#{output.split(":")[1]}" == 'ethernet'
interfaces["ethernet" => "#{output.split(":")[0]}"]
elsif "#{output.split(":")[1]}" == 'wifi'
interfaces["wifi" => "#{output.split(":")[0]}"]
else
Chef::Log.debug("Interface #{output.split(":")} is not supported")
end
end
chef (17.6.18)>
=> ["wlp61s0:wifi", "enp0s31f6:ethernet", "lo:loopback"]
node[interfaces] #nil
node[:interfaces] #nil
node['interfaces'] #nil
node["interfaces"] #nil
BroiSatse が提案したように、コードを編集しようとすると
そこでそれを試してみましたが、ハッシュからはまだ nil の応答が返されます。 Chef の出力/エラーは次のとおりです。
chef (17.6.18)> interfaces = Hash.new
chef > #DEVICE,TYPE
chef (17.6.18)> dev = Mixlib::ShellOut.new("nmcli -terse -field device,type device").run_command.stdout.split(/\n/)
=> ["wlp61s0:wifi", "enp0s31f6:ethernet", "lo:loopback"]
chef > dev.each do |output|
chef > if "#{output.split(":")[1]}" == 'ethernet'
chef > interfaces["ethernet"] = "#{output.split(":")[0]}"
chef > elsif "#{output.split(":")[1]}" == 'wifi'
chef > interfaces["wifi"] = "#{output.split(":")[0]}"
chef > else
chef > Chef::Log.debug("Interface #{output.split(":")} is not supported")
chef > end
chef (17.6.18)> end
=> ["wlp61s0:wifi", "enp0s31f6:ethernet", "lo:loopback"]
chef (17.6.18)> node[interfaces] #nil
=> nil
chef (17.6.18)> node[:interfaces][:ethernet] #nil
(irb):95:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
from /opt/chef/embedded/lib/ruby/gems/3.0.0/gems/chef-17.6.18/lib/chef/shell.rb:93:in `block in start'
from /opt/chef/embedded/lib/ruby/gems/3.0.0/gems/chef-17.6.18/lib/chef/shell.rb:92:in `catch'
from /opt/chef/embedded/lib/ruby/gems/3.0.0/gems/chef-17.6.18/lib/chef/shell.rb:92:in `start'
from /opt/chef/embedded/lib/ruby/gems/3.0.0/gems/chef-bin-17.6.18/bin/chef-shell:31:in `<top (required)>'
from /usr/bin/chef-shell:158:in `load'
from /usr/bin/chef-shell:158:in `<main>'
chef (17.6.18)> node['interfaces'] #nil
chef (17.6.18)> node["interfaces"] #nil
=> nil
chef (17.6.18)>
更新: 2022年5月2日月曜日 12:08 PST
このコマンドを実行すると、ハッシュにデータがあることがわかります…しかし、実際にデータをクエリしようとする試みはすべて失敗します…何が間違っているのかわかりません。
chef (17.6.18)> puts "#{interfaces}"
{"wifi"=>"wlp61s0", "ethernet"=>"enp0s31f6"}
=> nil
chef (17.6.18)>
解決策
ただ電話してください
interfaces["ethernet"]
または
interfaces["wifi"]
interfaces = {}
dev =
Mixlib::ShellOut.new("nmcli -terse -field device,type device").
run_command.
stdout.
lines(chomp: true)
dev.each do |output|
device, type_device = output.split(":")
case type_device
when "ethernet", "wifi"
interfaces[type_device] = device
else
Chef::Log.debug("Interface #{output} is not supported")
end
end
注: 主要な Wi-Fi とイーサネットは 1 つだけです。したがって、さらに多くのデバイスがある場合は、最後の値だけが使用されます