如何通过boto python代码创建EC2实例

时间:2015-07-08 10:02:31

标签: amazon-ec2 boto aws-ec2

requests = [conn.request_spot_instances(price = 0.0034,image_id ='ami-6989a659',count = 1,type ='one-time',instance_type ='m1.micro')]

我使用以下代码..但它不工作..

2 个答案:

答案 0 :(得分:1)

使用以下代码从python命令行创建实例。

 import boto.ec2
 conn = boto.ec2.connect_to_region("us-west-2",
 aws_access_key_id='<aws access key>',
 aws_secret_access_key='<aws secret key>')
 conn = boto.ec2.connect_to_region("us-west-2")
 conn.run_instances('<ami-image-id>',key_name='myKey', 
 instance_type='t2.micro',
 security_groups=['your-security-group-here'])

答案 1 :(得分:0)

要在AWS上使用Python创建EC2实例,您需要具有“ aws_access_key_id_value”和“ aws_secret_access_key_value”。 您可以将此类变量存储在config.properties中,并将代码写入create-ec2-instance.py文件

创建一个config.properties并将以下代码保存在其中。

aws_access_key_id_value='YOUR-ACCESS-KEY-OF-THE-AWS-ACCOUNT'
aws_secret_access_key_value='YOUR-SECRETE-KEY-OF-THE-AWS-ACCOUNT'
region_name_value='region'
ImageId_value = 'ami-id'
MinCount_value = 1
MaxCount_value = 1
InstanceType_value = 't2.micro'
KeyName_value = 'name-of-ssh-key'

创建create-ec2-instance.py并将以下代码保存在其中。

import boto3

def getVarFromFile(filename):
    import imp
    f = open(filename)
    global data
    data = imp.load_source('data', '', f)
    f.close()


getVarFromFile('config.properties')

ec2 = boto3.resource(
'ec2',
    aws_access_key_id=data.aws_access_key_id_value,
    aws_secret_access_key=data.aws_secret_access_key_value,
    region_name=data.region_name_value
)

instance = ec2.create_instances(
    ImageId = data.ImageId_value,
    MinCount = data.MinCount_value,
    MaxCount = data.MaxCount_value,
    InstanceType = data.InstanceType_value,
    KeyName = data.KeyName_value)
print (instance[0].id)

使用以下命令执行python代码。

python create-ec2-instance.py