Ruby:解析API响应

时间:2013-02-18 02:20:19

标签: ruby amazon-ec2 hosts

我正在尝试运行这个脚本:http://dysinger.net/2008/10/13/using-amazon-ec2-metadata-as-a-simple-dns但是dosnt有效,因为它使用了一个旧的亚马逊sdk版本,我重新编写它以使用新版本:

#!/usr/bin/env ruby

require "rubygems"
require "aws-sdk"

%w(optparse rubygems aws-sdk resolv pp).each {|l| require l}
options = {}
parser = OptionParser.new do |p|
  p.banner = "Usage: hosts [options]"
  p.on("-a", "--access-key USER", "The user's AWS access key ID.") do |aki|
    options[:access_key_id] = aki
  end
  p.on("-s",
       "--secret-key PASSWORD",
       "The user's AWS secret access key.") do |sak|
    options[:secret_access_key] = sak
  end
  p.on_tail("-h", "--help", "Show this message") {
    puts(p)
    exit
  }
  p.parse!(ARGV) rescue puts(p)
end
if options.key?(:access_key_id) and options.key?(:secret_access_key)
  puts "127.0.0.1 localhost"
   AWS.config(options)
    AWS::EC2.new(options)
    answer = AWS::EC2::Client.new.describe_instances
    answer.reservationSet.item.each do |r|
    r.instancesSet.item.each do |i|
      if i.instanceState.name =~ /running/
        puts(Resolv::DNS.new.getaddress(i.privateDnsName).to_s +
             " #{i.keyName}.ec2 #{i.keyName}")
      end
    end
  end
else
  puts(parser)
  exit(1)
end

这应该做的是输出一个包含ec2实例的新/ etc / hosts文件。

我得到一个响应= D,但答案是哈希,因此我得到了

error undefined method `reservationSet' for #<Hash:0x7f7573b27880>.

这是我的问题,因为我根本不懂Ruby(我所做的只是阅读亚马逊文档并玩游戏,所以我得到了答案)。不知何故,在原始的例子中,这似乎有效。我想那时候,API并没有返回哈希值,无论如何...我怎么能迭代上面的哈希值才能让它工作?

1 个答案:

答案 0 :(得分:0)

此代码可以帮助您:

answer = AWS::EC2::Client.new.describe_instances
reservations = answer[:reservation_set]
reservations.each do |reservation|
  instances = reservation[:instances_set]
  instances.each do |instance|
    if instance[:instance_state][:name] == "running"
      private_dns_name = instance[:private_dns_name]
      key_name = instance[:key_name]
      address = Resolv::DNS.new.getaddress(private_dns_name)
      puts "{address} #{key_name}.ec2 #{key_name}"
    end
  end
end

通常会将您的代码更改为使用带有名称的方法,例如item.fooBarBaz使用哈希,例如item[:foo_bar_baz]

当您学习Ruby时,“pp”命令对于漂亮打印变量非常有用,例如:

pp reservations

pp instances

pp private_dns_name