【问题标题】:Creating EC2 instances with key pairs in Boto2在 Boto2 中使用密钥对创建 EC2 实例
【发布时间】:2016-09-24 13:22:10
【问题描述】:

我有以下代码使用 boto.ec2 从 python 连接到 Amazon EC2,但我正在努力处理 .pem 文件。如果我将 None 作为键名传递给 run_instances 调用,我可以毫无问题地创建实例。但是,如果我传递任何键名(无论我是使用控制台创建它,还是如下手动创建它),当我尝试运行实例时,我会系统地收到以下错误

EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidKeyPair.NotFound</Code><Message>The key pair 'newkey.pem' does not exist</Message></Error></Errors><RequestID>e4da5b1e-a8ec-42fb-b3ce-20aa883a0615</RequestID></Response>

当我在控制台上检查相应区域时,确实创建了密钥(它也在我的主目录中创建,但我仍然得到密钥不存在错误)

有什么想法吗?

下面是我目前的 Python 测试代码

 try:
    key_res = conn.get_all_key_pairs(keynames=[key])[0]
    print key_res
    print "Key pair found"
   except boto.exception.EC2ResponseError, e:
    print e
    if e.code == 'InvalidKeyPair.NotFound':
     print 'Creating keypair: %s' % key
     # Create an SSH key to use when logging into instances.
     key_aws = conn.create_key_pair(key)
     # AWS will store the public key but the private key is
     # generated and returned and needs to be stored locally.
     # The save method will also chmod the file to protect
     # your private key.
     key_aws.save(".")
    else:
      raise
    print "Creating instances"
    try: 
      conn.run_instances(ami[c.region.name], key_name=key,instance_type=instance,security_groups=[security_group])
    except Exception as e:
                print e
                print "Failed to create instance in " + c.region.name

【问题讨论】:

  • 我似乎记得密钥名称以.pem 结尾的问题,尝试删除.pem 并将密钥称为newkey
  • 我传入“newkey”只有错误返回“newkey.pem”

标签: python amazon-web-services amazon-ec2 boto


【解决方案1】:

这段代码(来自你的)对我有用:

>>> import boto.ec2
>>> conn = boto.ec2.connect_to_region('ap-southeast-2')
>>> key_res = conn.get_all_key_pairs(keynames=['class'])[0]
>>> key_res
KeyPair:class
>>> key_res.name
u'class'
>>> conn.run_instances('ami-ced887ad', key_name=key_res.name, instance_type='t1.micro', security_group_ids=['sg-94cb39f6'])
Reservation:r-0755a9700e3886841

然后我尝试了您的密钥创建代码:

>>> key_aws = conn.create_key_pair('newkey')
>>> key_aws.save(".")
True
>>> conn.run_instances('ami-ced887ad', key_name=key_aws.name,instance_type='t1.micro',security_group_ids=['sg-93cb39f6'])
Reservation:r-07f831452bf869a14
>>> conn.run_instances('ami-ced887ad', key_name='newkey',instance_type='t1.micro',security_group_ids=['sg-93cb39f6'])
Reservation:r-0476ef041ed26a52f

它似乎工作正常!

【讨论】:

  • 您确定您运行的是最新版本的 boto 吗?您是否尝试过我上面使用的代码 (key_name=key_aws.name)?
猜你喜欢
  • 2017-04-03
  • 2020-10-07
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 2013-07-18
  • 2013-05-13
  • 2011-12-14
  • 1970-01-01
相关资源
最近更新 更多