1

我正在尝试运行此脚本: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

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

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

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

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

4

1 回答 1

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
于 2013-02-18T08:13:59.183 回答