aws boto - how to create instance and return instance_id

这一生的挚爱 提交于 2020-06-29 11:28:20

问题


I want to create a python script where I can pass arguments/inputs to specify instance type and later attach an extra EBS (if needed).

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
        )

Now, can ec2.create_instances() return ID or do I have to do an iteration of reservations?

or do I do an ec2.create(instance_id) / return instance_id? The documentation isn't specifically clear here.


回答1:


in boto3, create_instances returns a list so to get instance id that was created in the request, following works:

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



回答2:


The docs state that the call to create_instances()

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

Returns list(ec2.Instance). So you should be able to get the instance ID(s) from the 'id' property of the object(s) in the list.




回答3:


you can the following

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

actually create_instances returns an ec2.instance instance



来源:https://stackoverflow.com/questions/40028223/aws-boto-how-to-create-instance-and-return-instance-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!