aws describe_instances returns 不正确的值

aws describe_instances returns incorrect values

我想要一个快速而肮脏的停止和启动实例,所以我写下了下面的内容,它完全从 describe_instances 得到了奇怪的答案,并显示我的实例是 运行,而实际上它是停止并且不会停止或开始任何事情。

有人指出我明显的错误吗?

#!/bin/ruby

require 'rubygems'
require 'bundler/setup'
require 'aws-sdk'
require 'uuid'
require 'pp'


class InstanceManager
  def listInstances()
  ec2 = Aws::EC2::Client.new(region:  "eu-west-1")
  resp = ec2.describe_instances()
    resp.reservations.each do |res|
     res.instances.each do |inst|
      iid = inst[:instance_id]
      istate = inst[:state].name
      puts "#{iid} #{istate}"
     end
    end
  end
  def stop(iid)
    ec2 = Aws::EC2::Client.new(region:  "eu-west-1")
    inst = ec2.describe_instances(instance_ids: [iid]).reservations[0].instances[0]
    if ( inst[:state].name == "running" )
      puts "stopping #{iid}"
      res=ec2.stop_instances(dry_run: false, instance_ids: [iid],force: true)
      pp res
    else
      puts "#{iid} already stopped"
    end
    pp inst
  end
  def start(iid)
    ec2 = Aws::EC2::Client.new(region:  "eu-west-1")
    inst = ec2.describe_instances(instance_ids: [iid]).reservations[0].instances[0]
    if ( inst[:state].name == "stopped" )
      pp inst
      puts "starting #{iid}"
      res=ec2.start_instances(dry_run: false, instance_ids: [iid],force: true)
      pp res
    else
      puts "#{iid} already started"
    end
    pp inst
  end
end

if __FILE__ ==[=12=]
  z = InstanceManager.new
  z.listInstances()
#  z.stop("i-e122b106")
  z.start("i-e122b106")
end

我怀疑您 运行 陷入与 EC2 API 的最终一致性问题。这在使用 Amazon EC2 时非常常见。当您发出命令时,例如 #stop_instance#describe_instances 调用将在一段时间内继续返回状态,例如 运行,直到状态发生变化。这可能需要几分钟时间。