E.Z.
E.Z.

Reputation: 159

aws boto - how to create instance and return instance_id

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.

Upvotes: 1

Views: 4595

Answers (3)

Vishal
Vishal

Reputation: 2173

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

Upvotes: 3

Frederic Henri
Frederic Henri

Reputation: 53713

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

Upvotes: 0

Daniel Scott
Daniel Scott

Reputation: 7913

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.

Upvotes: 1

Related Questions