【问题标题】:aws boto - how to create instance and return instance_idaws boto - 如何创建实例并返回 instance_id
【发布时间】:2017-02-23 00:05:45
【问题描述】:

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

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?文档在这里不是特别清楚。

【问题讨论】:

  • create_instance 将返回一个响应对象,这是您在创建后获取实例 ID 的地方。

标签: python amazon-ec2 boto boto3


【解决方案1】:

在 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

【讨论】:

    【解决方案2】:

    你可以如下

    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
    

    实际上create_instances 返回一个ec2.instance 实例

    【讨论】:

      【解决方案3】:

      文档声明对 create_instances() 的调用

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

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

      【讨论】:

      • 啊,谢谢丹。我完全没有看到那个o_O。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 2015-08-26
      • 2018-07-02
      相关资源
      最近更新 更多