本文整理汇总了Python中boto.ec2.blockdevicemapping.EBSBlockDeviceType类的典型用法代码示例。如果您正苦于以下问题:Python EBSBlockDeviceType类的具体用法?Python EBSBlockDeviceType怎么用?Python EBSBlockDeviceType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了EBSBlockDeviceType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _register_image
def _register_image(self, snapshot_id):
conn = self.platform.new_ec2_conn()
instance_id = self.platform.get_instance_id()
instance = conn.get_all_instances([instance_id])[0].instances[0]
block_device_map = BlockDeviceMapping(conn)
root_vol = EBSBlockDeviceType(snapshot_id=snapshot_id)
root_vol.delete_on_termination = True
# Adding ephemeral devices
for eph, device in EPH_STORAGE_MAPPING[linux.os['arch']].items():
bdt = EBSBlockDeviceType(conn)
bdt.ephemeral_name = eph
block_device_map[device] = bdt
root_partition = instance.root_device_name[:-1]
if root_partition in self.platform.get_block_device_mapping().values():
block_device_map[root_partition] = root_vol
else:
block_device_map[instance.root_device_name] = root_vol
return conn.register_image(
name=self.image_name,
root_device_name=instance.root_device_name,
block_device_map=block_device_map,
kernel_id=instance.kernel,
virtualization_type=instance.virtualization_type,
ramdisk_id=self.platform.get_ramdisk_id(),
architecture=instance.architecture)
示例2: register_snap
def register_snap(self, snap_id, arch, name, aki=None, desc=None, ari=None,
pub=True, disk=False):
"""
Register an EBS volume snapshot as an AMI. Returns the AMI ID. An arch,
snapshot ID, and name for the AMI must be provided. Optionally
a description, AKI ID, ARI ID and billing code may be specified too.
disk is whether or not we are registering a disk image.
"""
self.logger.info('Registering snap: %s' % (snap_id))
snap = self.conn.get_all_snapshots([snap_id])[0]
#Makes block device map
ebs = EBSBlockDeviceType()
ebs.snapshot_id = snap_id
block_map = BlockDeviceMapping()
if aki == None:
raise Fedora_EC2Error('Need to specify an AKI')
if disk:
disk = '/dev/sda=%s' % snap_id
root = '/dev/sda'
else:
disk = '/dev/sda1=%s' % snap_id
root = '/dev/sda1'
block_map[root] = ebs
ami_id = self.conn.register_image(name=name, description=desc,
image_location = '', architecture=arch, kernel_id=aki,
ramdisk_id=ari,root_device_name=root, block_device_map=block_map)
if not ami_id.startswith('ami-'):
self._log_error('Could not register an AMI')
self.logger.info('Registered an AMI: %s' % ami_id)
return ami_id
示例3: create_node
def create_node(self, name, distribution, metadata={}):
size = self._default_size
disk_size = 8
with start_action(
action_type=u"flocker:provision:aws:create_node",
name=name,
distribution=distribution,
image_size=size,
disk_size=disk_size,
metadata=metadata,
):
metadata = metadata.copy()
metadata["Name"] = name
disk1 = EBSBlockDeviceType()
disk1.size = disk_size
disk1.delete_on_termination = True
diskmap = BlockDeviceMapping()
diskmap["/dev/sda1"] = disk1
images = self._connection.get_all_images(filters={"name": IMAGE_NAMES[distribution]})
# Retry several times, no sleep between retries is needed.
instance = poll_until(
lambda: self._get_node(images[0].id, size, diskmap, metadata), repeat(0, 10), lambda x: None
)
return AWSNode(name=name, _provisioner=self, _instance=instance, distribution=distribution)
示例4: launch_instance
def launch_instance(self):
if not self.verify_settings():
return
is_instance_store = self.conn.get_all_images(self.config['ec2_ami_id'], filters={'root-device-type': 'instance-store'})
if is_instance_store:
block_map = None
else:
block_map = BlockDeviceMapping()
root_device = self.config['ec2_root_device']
block_map[root_device] = EBSBlockDeviceType()
if self.config['ec2_size']:
block_map[root_device].size = self.config['ec2_size']
block_map[root_device].delete_on_termination = True
reservation = self.conn.run_instances(
self.config['ec2_ami_id'],
key_name=self.config['ec2_key_name'],
security_groups=self.config['ec2_security_groups'] or [self.config['ec2_security_group']],
instance_type=self.config['ec2_instance_type'],
placement=self.config['ec2_zone'],
placement_group=self.config['ec2_placement_group'],
monitoring_enabled=self.config['ec2_monitoring_enabled'],
block_device_map=block_map,
user_data=self.user_data)
self.instance = reservation.instances[0]
secs = RUN_INSTANCE_TIMEOUT
rest_interval = 5
while secs and not self.instance.state == 'running':
time.sleep(rest_interval)
secs = secs - rest_interval
try:
self.instance.update()
except boto.exception.EC2ResponseError:
pass
if secs <= 0:
errmsg = "run instance {0} failed after {1} seconds".format(
self.instance.id, RUN_INSTANCE_TIMEOUT)
LOG.error(errmsg)
else:
if self.config['hostname']:
self.assign_name_tag()
msg1 = "Started Instance: {0}\n".format(self.instance.id)
LOG.info(msg1)
print msg1
p = int(self.config['ssh_port'])
port = "-p {0} ".format(p) if p and not p == 22 else ''
## change user to 'root' for all non-Ubuntu systems
user = self.config['sudouser'] if self.config['sudouser'] and self.config['ssh_import'] else 'ubuntu'
#XXX - TODO: replace public dns with fqdn, where appropriate
msg2 = "To access: ssh {0}{1}@{2}\n".format(
'-p {0} '.format(port) if port else '',
user,
self.instance.public_dns_name)
msg3 = "To terminate: shaker-terminate {0}".format(
self.instance.id)
LOG.info(msg2)
LOG.info(msg3)
print msg2
print msg3
示例5: launch_instance
def launch_instance(skip_updates=False):
'''
Launch an Oracle database instance.
'''
# Assume the keypair name is based on our env.key_filename.
instance_key_name = os.path.basename(env.key_filename).replace('.pem', '')
# Check that we have a security group configured already.
security_group_list = ec2_connection.get_all_security_groups()
security_group_found = False
for security_group in security_group_list:
if security_group.name == security_group_name:
security_group_found = True
break
# If we didn't find it, create it.
if not security_group_found:
create_security_group()
# We want a larger EBS root volume, so override /dev/sda1.
# Create an EBS device with 40GB allocated.
dev_root = EBSBlockDeviceType()
dev_root.size = 40
# Create the mapping.
dev_mapping = BlockDeviceMapping()
dev_mapping['/dev/sda1'] = dev_root
reservation = ec2_connection.run_instances(ami_id,
instance_type=instance_type, key_name=instance_key_name,
security_groups=[security_group_name],
block_device_map = dev_mapping)
# This is hacky but (mostly) works.
instance = reservation.instances[0]
print(green("Launching instance on reservation {}.".format(instance, reservation)))
'''
Wait for instance state to change;
if it doesn't change to running, then fail.
'''
print(yellow('Waiting for instance to start...'))
set_tags = False
while instance.state == u'pending':
# Try to set tags.
if set_tags == False:
try:
ec2_connection.create_tags([instance.id], {"Name": instance_name})
set_tags = True
print(green("Instance {} tagged.".format(instance)))
except EC2ResponseError, e:
print(red("Tagging failed; sleeping, updating instance, and trying again."))
# Check up on its status every so often
time.sleep(10)
instance.update()
示例6: launch_instance
def launch_instance(self):
if not self.verify_settings():
return
block_map = BlockDeviceMapping()
root_device = self.config["ec2_root_device"]
block_map[root_device] = EBSBlockDeviceType()
if self.config["ec2_size"]:
block_map[root_device].size = self.config["ec2_size"]
block_map[root_device].delete_on_termination = True
for num, device_location in enumerate(self.config["ec2_ephemeral_devices"]):
device = BlockDeviceType()
device.ephemeral_name = "ephemeral%d" % num
block_map[device_location] = device
reservation = self.conn.run_instances(
self.config["ec2_ami_id"],
key_name=self.config["ec2_key_name"],
security_groups=self.config["ec2_security_groups"] or [self.config["ec2_security_group"]],
instance_type=self.config["ec2_instance_type"],
placement=self.config["ec2_zone"],
monitoring_enabled=self.config["ec2_monitoring_enabled"],
block_device_map=block_map,
user_data=self.user_data,
)
self.instance = reservation.instances[0]
secs = RUN_INSTANCE_TIMEOUT
rest_interval = 5
while secs and not self.instance.state == "running":
time.sleep(rest_interval)
secs = secs - rest_interval
try:
self.instance.update()
except boto.exception.EC2ResponseError:
pass
if secs <= 0:
errmsg = "run instance %s failed after %d seconds" % (self.instance.id, RUN_INSTANCE_TIMEOUT)
LOG.error(errmsg)
else:
if self.config["hostname"]:
self.assign_name_tag()
msg1 = "Started Instance: {0}\n".format(self.instance.id)
LOG.info(msg1)
print msg1
p = int(self.config["ssh_port"])
port = "-p {0} ".format(p) if p and not p == 22 else ""
## change user to 'root' for all non-Ubuntu systems
user = self.config["sudouser"] if self.config["sudouser"] and self.config["ssh_import"] else "ubuntu"
# XXX - TODO: replace public dns with fqdn, where appropriate
msg2 = "To access: ssh {0}{1}@{2}\n" "To terminate: shaker-terminate {3}".format(
port, user, self.instance.public_dns_name, self.instance.id
)
LOG.info(msg2)
print msg2
示例7: run_encryptor_instance
def run_encryptor_instance(aws_svc, encryptor_image_id, snapshot, root_size,
guest_image_id, sg_id, update_ami=False):
bdm = BlockDeviceMapping()
guest_unencrypted_root = EBSBlockDeviceType(
volume_type='gp2',
snapshot_id=snapshot,
delete_on_termination=True)
# Use gp2 for fast burst I/O copying root drive
bdm['/dev/sda4'] = guest_unencrypted_root
if not update_ami:
log.info('Launching encryptor instance with snapshot %s', snapshot)
# They are creating an encrypted AMI instead of updating it
# Use gp2 for fast burst I/O copying root drive
guest_encrypted_root = EBSBlockDeviceType(
volume_type='gp2',
delete_on_termination=True)
guest_encrypted_root.size = 2 * root_size + 1
bdm['/dev/sda5'] = guest_encrypted_root
else:
log.info('Launching encryptor instance for updating %s',
guest_image_id)
guest_encrypted_root = EBSBlockDeviceType(
volume_type='gp2',
snapshot_id=snapshot,
delete_on_termination=True)
guest_encrypted_root.size = root_size
bdm['/dev/sda5'] = guest_encrypted_root
instance = aws_svc.run_instance(encryptor_image_id,
security_group_ids=[sg_id],
block_device_map=bdm)
aws_svc.create_tags(
instance.id,
name=NAME_ENCRYPTOR,
description=DESCRIPTION_ENCRYPTOR % {'image_id': guest_image_id}
)
instance = _wait_for_instance(aws_svc, instance.id)
log.info('Launched encryptor instance %s', instance.id)
# Tag volumes.
bdm = instance.block_device_mapping
if not update_ami:
aws_svc.create_tags(
bdm['/dev/sda5'].volume_id, name=NAME_ENCRYPTED_ROOT_VOLUME)
aws_svc.create_tags(
bdm['/dev/sda2'].volume_id, name=NAME_METAVISOR_ROOT_VOLUME)
aws_svc.create_tags(
bdm['/dev/sda1'].volume_id, name=NAME_METAVISOR_GRUB_VOLUME)
aws_svc.create_tags(
bdm['/dev/sda3'].volume_id, name=NAME_METAVISOR_LOG_VOLUME)
return instance
示例8: launch_instance
def launch_instance(self):
if not self.verify_settings():
return
is_instance_store = self.conn.get_all_images(self.config['ec2_ami_id'], filters={'root-device-type': 'instance-store'})
if is_instance_store:
block_map = None
else:
block_map = BlockDeviceMapping()
root_device = self.config['ec2_root_device']
block_map[root_device] = EBSBlockDeviceType()
if self.config['ec2_size']:
block_map[root_device].size = self.config['ec2_size']
block_map[root_device].delete_on_termination = True
opts = {
'key_name': self.config['ec2_key_name'],
'security_groups': self.config['ec2_security_groups'] or [self.config['ec2_security_group']],
'instance_type': self.config['ec2_instance_type'],
'placement': self.config['ec2_zone'],
'placement_group': self.config['ec2_placement_group'],
'monitoring_enabled': self.config['ec2_monitoring_enabled'],
'block_device_map': block_map,
'user_data': self.user_data
}
if self.config.get('ec2_subnet_id',False):
# when providing subnet_id, must use security_group_ids and not
# named security_groups or API call will fail.
opts.pop('security_groups',None)
opts['security_group_ids'] = self.config['ec2_security_group_ids'] or [self.config['ec2_security_group_id']]
if not opts['security_group_ids']:
raise AssertionError('Must specify ec2_security_group_id or ec2_security_group_ids with subnet_id')
opts['subnet_id'] = self.config['ec2_subnet_id']
reservation = self.conn.run_instances(self.config['ec2_ami_id'], **opts)
self.instance = reservation.instances[0]
secs = RUN_INSTANCE_TIMEOUT
rest_interval = 5
while secs and not self.instance.state == 'running':
time.sleep(rest_interval)
secs = secs - rest_interval
try:
self.instance.update()
except boto.exception.EC2ResponseError:
pass
if secs <= 0:
errmsg = "run instance {0} failed after {1} seconds".format(
self.instance.id, RUN_INSTANCE_TIMEOUT)
LOG.error(errmsg)
else:
if self.config['hostname']:
self.assign_name_tag()
示例9: get_block_device
def get_block_device(instance_type, ebs_vol_size):
block_map = BlockDeviceMapping()
if ebs_vol_size > 0:
device = EBSBlockDeviceType()
device.size = ebs_vol_size
device.delete_on_termination = True
block_map['/dev/sdv'] = device
for i in range(get_num_disks(instance_type)):
dev = BlockDeviceType()
dev.ephemeral_name = 'ephemeral%d' % i
# The first ephemeral drive is /dev/sdb.
name = '/dev/sd' + string.ascii_letters[i + 1]
block_map[name] = dev
return block_map
示例10: startInstance
def startInstance(ec2connection, hardwareProfile, ARCH, RHEL, AMI, SSHKEYNAME):
conn_region = ec2connection
map = BlockDeviceMapping()
t = EBSBlockDeviceType()
t.size = "15"
# map = {'DeviceName':'/dev/sda','VolumeSize':'15'}
map["/dev/sda1"] = t
# blockDeviceMap = []
# blockDeviceMap.append( {'DeviceName':'/dev/sda', 'Ebs':{'VolumeSize' : '100'} })
if ARCH == "i386" and RHEL == "6.1":
reservation = conn_region.run_instances(
AMI, instance_type=hardwareProfile, key_name=SSHKEYNAME, block_device_map=map
)
elif ARCH == "x86_64" and RHEL == "6.1":
reservation = conn_region.run_instances(
AMI, instance_type=hardwareProfile, key_name=SSHKEYNAME, block_device_map=map
)
elif ARCH == "i386":
reservation = conn_region.run_instances(
AMI, instance_type=hardwareProfile, key_name=SSHKEYNAME, block_device_map=map
)
elif ARCH == "x86_64":
reservation = conn_region.run_instances(
AMI, instance_type=hardwareProfile, key_name=SSHKEYNAME, block_device_map=map
)
else:
print "arch type is neither i386 or x86_64.. will exit"
exit(1)
myinstance = reservation.instances[0]
time.sleep(5)
while not myinstance.update() == "running":
time.sleep(5)
print myinstance.update()
instanceDetails = myinstance.__dict__
pprint(instanceDetails)
# region = instanceDetails['placement']
# print 'region =' + region
publicDNS = instanceDetails["public_dns_name"]
print "public hostname = " + publicDNS
# check for console output here to make sure ssh is up
return publicDNS
示例11: create_server
def create_server():
"""
Creates EC2 Instance and saves it state in a local json file
"""
# looks for an existing 'data.json' file, so that we don't start
# additional ec2 instances when we don't need them.
#
if is_there_state():
return True
else:
conn = connect_to_ec2()
print(_green("Started..."))
print(_yellow("...Creating EC2 instance..."))
# we need a larger boot device to store our cached images
dev_sda1 = EBSBlockDeviceType()
dev_sda1.size = 120
bdm = BlockDeviceMapping()
bdm['/dev/sda1'] = dev_sda1
# get an ec2 ami image object with our choosen ami
image = conn.get_all_images(env.ec2_ami)[0]
# start a new instance
reservation = image.run(1, 1,
key_name=env.ec2_key_pair,
security_groups=env.ec2_security,
block_device_map = bdm,
instance_type=env.ec2_instancetype)
# and get our instance_id
instance = reservation.instances[0]
# add a tag to our instance
conn.create_tags([instance.id], {"Name": env.ec2_instance_name})
# and loop and wait until ssh is available
while instance.state == u'pending':
yellow("Instance state: %s" % instance.state)
sleep(10)
instance.update()
wait_for_ssh(instance.public_dns_name)
green("Instance state: %s" % instance.state)
green("Public dns: %s" % instance.public_dns_name)
# finally save the details or our new instance into the local state file
save_state_locally(instance.id)
示例12: register_ebs_ami
def register_ebs_ami(self, snapshot_id, arch = 'x86_64', default_ephem_map = True,
img_name = None, img_desc = None):
# register against snapshot
try:
aki=PVGRUB_AKIS[self.region.name][arch]
except KeyError:
raise Exception("Unable to determine pvgrub hd00 AKI for region (%s) arch (%s)" % (self.region.name, arch))
if not img_name:
rand_id = random.randrange(2**32)
# These names need to be unique, hence the pseudo-uuid
img_name='EBSHelper AMI - %s - uuid-%x' % (snapshot_id, rand_id)
if not img_desc:
img_desc='Created directly from volume snapshot %s' % (snapshot_id)
self.log.debug("Registering snapshot (%s) as new EBS AMI" % (snapshot_id))
ebs = EBSBlockDeviceType()
ebs.snapshot_id = snapshot_id
ebs.delete_on_termination = True
block_map = BlockDeviceMapping()
block_map['/dev/sda'] = ebs
# The ephemeral mappings are automatic with S3 images
# For EBS images we need to make them explicit
# These settings are required to make the same fstab work on both S3 and EBS images
if default_ephem_map:
e0 = EBSBlockDeviceType()
e0.ephemeral_name = 'ephemeral0'
e1 = EBSBlockDeviceType()
e1.ephemeral_name = 'ephemeral1'
block_map['/dev/sdb'] = e0
block_map['/dev/sdc'] = e1
result = self.conn.register_image(name=img_name, description=img_desc,
architecture=arch, kernel_id=aki,
root_device_name='/dev/sda', block_device_map=block_map)
return str(result)
示例13: startInstance
def startInstance(self, ami, ec2_keyName, sec_group, hwp):
map = BlockDeviceMapping()
t = EBSBlockDeviceType()
t.size = '15'
#map = {'DeviceName':'/dev/sda','VolumeSize':'15'}
map['/dev/sda1'] = t
reservation = self.connection.run_instances(ami,
instance_type=hwp, key_name=ec2_keyName,
security_groups=sec_group, block_device_map=map)
myinstance = reservation.instances[0]
time.sleep(5)
while(not myinstance.update() == 'running'):
time.sleep(5)
print myinstance.update()
#pprint(instanceDetails)
return myinstance
示例14: parse_block_device_args
def parse_block_device_args(self, block_device_maps_args):
block_device_map = BlockDeviceMapping()
for block_device_map_arg in block_device_maps_args:
parts = block_device_map_arg.split('=')
if len(parts) > 1:
device_name = parts[0]
block_dev_type = EBSBlockDeviceType()
value_parts = parts[1].split(':')
if value_parts[0].startswith('snap'):
block_dev_type.snapshot_id = value_parts[0]
else:
if value_parts[0].startswith('ephemeral'):
block_dev_type.ephemeral_name = value_parts[0]
if len(value_parts) > 1:
block_dev_type.size = int(value_parts[1])
if len(value_parts) > 2:
if value_parts[2] == 'true':
block_dev_type.delete_on_termination = True
block_device_map[device_name] = block_dev_type
return block_device_map
示例15: launch_instance
def launch_instance(self):
if not self.verify_settings():
return
is_instance_store = self.conn.get_all_images(self.config['ec2_ami_id'], filters={'root-device-type': 'instance-store'})
if is_instance_store:
block_map = None
else:
block_map = BlockDeviceMapping()
root_device = self.config['ec2_root_device']
block_map[root_device] = EBSBlockDeviceType()
if self.config['ec2_size']:
block_map[root_device].size = self.config['ec2_size']
block_map[root_device].delete_on_termination = True
reservation = self.conn.run_instances(
self.config['ec2_ami_id'],
key_name=self.config['ec2_key_name'],
security_groups=self.config['ec2_security_groups'] or [self.config['ec2_security_group']],
instance_type=self.config['ec2_instance_type'],
placement=self.config['ec2_zone'],
placement_group=self.config['ec2_placement_group'],
monitoring_enabled=self.config['ec2_monitoring_enabled'],
block_device_map=block_map,
user_data=self.user_data)
self.instance = reservation.instances[0]
secs = RUN_INSTANCE_TIMEOUT
rest_interval = 5
while secs and not self.instance.state == 'running':
time.sleep(rest_interval)
secs = secs - rest_interval
try:
self.instance.update()
except boto.exception.EC2ResponseError:
pass
if secs <= 0:
errmsg = "run instance {0} failed after {1} seconds".format(
self.instance.id, RUN_INSTANCE_TIMEOUT)
LOG.error(errmsg)
else:
if self.config['hostname']:
self.assign_name_tag()