27

我正在使用 boto/python 启动一个从 EBS 卷启动的新 EC2 实例。在我启动实例时,我想覆盖引导 EBS 卷的默认大小。

我没有发现可能适合我的启动代码的 boto 方法或参数:

ec2 = boto.connect_ec2( ACCESS_KEY, SECRET_KEY, region=region )

reservation = ec2.run_instances( image_id=AMI_ID, 
                                 key_name=EC2_KEY_HANDLE, 
                                 instance_type=INSTANCE_TYPE,
                                 security_groups = [ SECGROUP_HANDLE, ] )

此网页显示如何使用命令行工具增加正在运行的 EC2 实例的 EBS 卷的大小,但我想在指定 EC2 实例时使用 boto:

4

3 回答 3

43

您必须先创建块设备映射:

dev_sda1 = boto.ec2.blockdevicemapping.EBSBlockDeviceType()
dev_sda1.size = 50 # size in Gigabytes
bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
bdm['/dev/sda1'] = dev_sda1 

在此之后,您可以在run_instances调用中提供块设备映射:

reservation = ec2.run_instances( image_id=AMI_ID, 
                                 key_name=EC2_KEY_HANDLE, 
                                 instance_type=INSTANCE_TYPE,
                                 security_groups = [ SECGROUP_HANDLE, ],
                                 block_device_mappings = [bdm])

不幸的是,这并没有很好的记录,但是可以在源代码中找到该示例。

于 2012-11-28T11:43:04.793 回答
0

您还可以使用CloudFormation,它用于记录和自动化您的环境。您可以在以下位置检查 ESB 定义的模板:https ://s3.amazonaws.com/cloudformation-templates-us-east-1/EC2WithEBSSample.template

 "Resources" : {
    "Ec2Instance" : {
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "AvailabilityZone" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "TestAz" ]},
        "SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" } ],
        "KeyName" : { "Ref" : "KeyName" },
        "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]},
        "Volumes" : [ 
          { "VolumeId" : { "Ref" : "NewVolume" },
            "Device" : "/dev/sdk"
          }
        ]
      }
    },

    ...

    "NewVolume" : {
      "Type" : "AWS::EC2::Volume",
      "Properties" : {
        "Size" : "100",
        "AvailabilityZone" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "TestAz" ]}
      }
    }

然后,您可以使用Boto CloudFormation API来部署您的环境。

于 2012-11-28T14:15:55.057 回答
0

这是使用boto3“一切都是资源”方法的代码版本。另请注意如何避免硬编码磁盘名称:

import boto3

ec2 = boto3.resource('ec2')


def ec2_one_by_key_and_value(collection: str, key: str, value: str):
    handler = getattr(ec2, collection)
    return list(handler.filter(Filters=[{'Name': key, 'Values': [value]}]))[0]


image = ec2_one_by_key_and_value('images', 'name', 'ubuntu/images/hvm-ssd/...')
root_disk = None
for block_device in image.block_device_mappings:
    if block_device['DeviceName'] == image.root_device_name:
        root_disk = block_device
        assert root_disk['Ebs']
        root_disk['Ebs']['VolumeSize'] = 16 # New disk 
        break
assert root_disk
instances = ec2.create_instances(MinCount=1, ..., ImageId=image.id,
                                 BlockDeviceMappings=image.block_device_mappings)

于 2021-11-10T11:19:26.047 回答