如何创建实例并返回实例

2024-10-01 15:34:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个python脚本,在这里我可以传递参数/输入来指定实例类型,然后附加一个额外的eb(如果需要)。在

ec2 = boto3.resource('ec2','us-east-1')
hddSize = input('Enter HDD Size if you want extra space ')
instType = input('Enter the instance type ')

def createInstance():
    ec2.create_instances(
        ImageId=AMI, 
        InstanceType = instType,  
        SubnetId='subnet-31d3ad3', 
        DisableApiTermination=True,
        SecurityGroupIds=['sg-sa4q36fc'],
        KeyName='key'
     )
return instanceID; ## I know this does nothing

def createEBS():
    ebsVol = ec2.Volume(
        id = instanceID,
        volume_type = 'gp2', 
        size = hddSize
        )

现在,ec2.create_instances()是否可以返回ID,或者我是否必须执行保留的迭代?在

或者我要执行ec2.create(instance_id)/return instance_id?文档在这里并不明确。在


Tags: instancesinstance脚本idinput参数returndef
3条回答

文档声明调用create\u instances()

https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances

返回列表(ec2.Instance)。因此,您应该能够从列表中对象的“ID”属性获取实例ID。在

你可以以下列

def createInstance():
    instance = ec2.create_instances(
        ImageId=AMI, 
        InstanceType = instType,  
        SubnetId='subnet-31d3ad3', 
        DisableApiTermination=True,
        SecurityGroupIds=['sg-sa4q36fc'],
        KeyName='key'
     )
     # return response
     return instance.instance_id

实际上,^{}返回一个^{}实例

在boto3中,create_instances返回一个列表,以便获取请求中创建的实例id,具体操作如下:

ec2_client = boto3.resource('ec2','us-east-1')
response = ec2_client.create_instances(ImageId='ami-12345', MinCount=1, MaxCount=1)
instance_id = response[0].instance_id

相关问题 更多 >

    热门问题