使用YAML参数

时间:2015-08-31 14:10:14

标签: yaml

我有以下YAML。我想解析它并相应地创建对象。 正如您所看到的,应用程序的一个参数是主机的ip。是否可以使用某种参数而不写ip的硬编码?

hosts:
-
  name: host_A
  ip: 1.1.1.1
  applications:
  -
    name: xyz
    args:
    - --connect_to=2.2.2.2

-
  name: host_B
  ip: 2.2.2.2
  applications:
  -
    name: xyz
    args:
    - --connect-to=1.1.1.1

据我所知,使用& ip / * ip是不可能的,因为两个主机共享此参数。

所以基本上,我想做类似的事情:

hosts:
-
  name: host_A
  ip: 1.1.1.1
  applications:
  -
    name: xyz
    args:
    - --connect_to=&host_B.ip

-
  name: host_B
  ip: 2.2.2.2
  applications:
  -
    name: xyz
    args:
    - --connect-to=&host_A.ip

1 个答案:

答案 0 :(得分:0)

您可以使用参数创建Hash和YAML文件(在示例中使用带有ip的数组),如果在从YAML加载后枚举Hash,则可以执行以下操作。我冒昧地使用哈希哈希而不是哈希数组,我相信你可以适应,因为你无法控制YAML结构。

require 'yaml'

$hosts = {}
ip = ["1.1.1.1", "2.2.2.2", "3.3.3.3"]
$hosts['host_A'] = {"ip"=>"#{ip[0]}", "applications"=>[{"name"=>"xyz", "args"=>["--connect_to=host_B"]}]}
$hosts['host_B'] = {"ip"=>"#{ip[1]}", "applications"=>[{"name"=>"xyz", "args"=>["--connect_to=host_A"]}]}
$hosts['host_C'] = {"ip"=>"#{ip[2]}", "applications"=>[{"name"=>"xyz", "args"=>["--connect_to=host_B"]}]}
# Pass through YAML file
File.open('parameter.yaml', 'w') {|f| f.write $hosts.to_yaml }
$hosts = YAML.load_file('parameter.yaml')
p $hosts
#{"host_A"=>{"ip"=>"1.1.1.1", "applications"=>[{"name"=>"xyz", "args"=>["--connect_to=host_B"]}]}, "host_B"=>{"ip"=>"2.2.2.2", "applications"=>[{"name"=>"xyz", "args"=>["--connect_to=host_A"]}]}, "host_C"=>{"ip"=>"3.3.3.3", "applications"=>[{"name"=>"xyz", "args"=>["--connect_to=host_B"]}]}}


def ip host
  $hosts[host]['ip']
end

$hosts.each do |k, v|
  host = v['applications'].first['args'].first[/(host_.?)/]
  ip = ip(host)
  v['applications'].first['args'].first.gsub!(/(host_.?)/,ip)
end
p $hosts
# {"host_A"=>{"ip"=>"1.1.1.1", "applications"=>[{"name"=>"xyz", "args"=>["--connect_to=2.2.2.2"]}]}, "host_B"=>{"ip"=>"2.2.2.2", "applications"=>[{"name"=>"xyz", "args"=>["--connect_to=1.1.1.1"]}]}, "host_C"=>{"ip"=>"3.3.3.3", "applications"=>[{"name"=>"xyz", "args"=>["--connect_to=2.2.2.2"]}]}}