2016-09-23 95 views
0

我有以下代碼使用boto.ec2從python連接到Amazon EC2,但我正在努力處理.pem文件。如果我將None作爲密鑰名稱傳遞給run_instances調用,則可以創建實例,而不會有任何問題。然而,如果我通過任意鍵名(使用它的控制檯,或低於手動是否我創建),我係統地收到以下錯誤,當我嘗試當我檢查的運行實例使用Boto2中的密鑰對創建EC2實例

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 
+1

我似乎記得鍵名以'.pem'結尾的問題,嘗試刪除'.pem',只是將鍵引用爲'newkey'。 – AChampion

+0

我通過「newkey」只有錯誤返回「newkey.pem」 – user1018513

回答

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 

它似乎工作正常!

+0

它爲我失敗,同樣的錯誤:( – user1018513

+0

你確定你運行的是boto的最新版本嗎?你嘗試了像我上面使用的代碼('KEY_NAME = key_aws.name')? –