Ruby 和 Chef:解析和替换哈希中的值
我正在使用 opscode Chef 来自动化 MySQL 集群的部署。我想将所需的主机放入 JSON 文件中,然后让 Chef 将这些主机名解析为内部 IP 地址,然后将 IP 地址设置为变量。
我有一个简单的散列,如下所示:
[data_bag_item["dbclstr", "dbclstr",
{
"id"=>"dbclstr",
"nodes"=>{"sql1"=>"cdb1.ex.net",
"sql2"=>"cdb2.ex.net",
"mgmnt"=>"cdb1.ex.net",
"db1"=>"cdb1.ex.net",
"db2"=>"cdb2.ex.net"
}}]]
我想基本上获取节点键,然后遍历散列中的所有键值,获取每个键/值,然后通过返回 IP 地址的搜索函数解析该值,然后分配该值到那个键。
dbclstr = search(:dbclstr).first # Loads json into hash
privip = dbclstr["nodes"] # grabs node hash from hash (turns into a mash?)
privip = privip.to_hash # turn mash to hash
privip.map { |key,value| # maps the keys and values of the hash.
item = search(:node,"name:value") #loads machine data from chef into object
value = "#{item[0][:cloud][:private_ips]}" # extracts ip address from object and sets it as value, done?
}
嗯,这是行不通的。
我可以单独将主机名解析为 IP 地址,但我并不真正了解如何获取每个键和值、解析该值,然后将其替换为解析后的值。
I am using opscode chef to automate the deployment of MySQL cluster. I want to put the desired hosts into a JSON file, then let chef resolve those hostnames to internal IP addresses, then set the IP addresses as variables.
I have a simple hash that looks like this:
[data_bag_item["dbclstr", "dbclstr",
{
"id"=>"dbclstr",
"nodes"=>{"sql1"=>"cdb1.ex.net",
"sql2"=>"cdb2.ex.net",
"mgmnt"=>"cdb1.ex.net",
"db1"=>"cdb1.ex.net",
"db2"=>"cdb2.ex.net"
}}]]
I want to basically grab the nodes key then go through all the key values in the hash grab each key/value then parse the value through my search function that returns the ip address then assign the value to that key.
dbclstr = search(:dbclstr).first # Loads json into hash
privip = dbclstr["nodes"] # grabs node hash from hash (turns into a mash?)
privip = privip.to_hash # turn mash to hash
privip.map { |key,value| # maps the keys and values of the hash.
item = search(:node,"name:value") #loads machine data from chef into object
value = "#{item[0][:cloud][:private_ips]}" # extracts ip address from object and sets it as value, done?
}
Well this doesn't work.
Individually I can resolve hostnames to IP addresses, but I don't really understand how to grab each key and value, resolve the value, then replace it with the resolved value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Ruby 中,当您有一个哈希并想要更新所有键/值对以获取新值时,您有多种选择:
如果值是字符串或数组,并且您想要新的字符串或数组
< strong>如果值是字符串,并且您想要替换文本,就地更新它们
其他情况(更通用)
In Ruby, when you have a Hash and want to update all key/value pairs to have new values, you have several options:
If the values are strings or arrays, and you want new strings or arrays
If the values are strings, and you want to replace text, updating them in-place
Other Cases (more generic)