如何为从boto旋转的ec2实例启用DeleteOnTermination

时间:2015-10-14 18:46:28

标签: python amazon-ec2 boto

我想启动一个ec2实例,然后终止它并希望确保在终止实例时也删除了EBS存储,所以我需要设置DeleteOnTermination标志。 我尝试使用boto:

 1: try
 2:     begin transaction;
 3:     query the database;
 4:     update memory;
 5:     update the database;
 6:     commit transaction;
 7: catch (exception E)
 8:     rollback transaction;
 9:     throw E;
10: end try

上面代码的最后一行是我使用的技巧。它适用于某些情况,但对于我想要使用的实例,我收到此错误:

conn = boto.ec2.connect_to_region('us-east',\
    aws_access_key_id=os.getenv('aws_access_key_id'),\
    aws_secret_access_key=os.getenv('aws_secret_access_key'))

groups = conn.get_all_security_groups(filters={'group-name': ['xxx']})

reservation = conn.run_instances(
    ami,
    key_name=os.getenv('key_name'),
    instance_type=instance_type,
    security_groups=groups)

tag = os.getenv('BUILD_NUMBER', None)
instance = reservation.instances[0]
# Note: setting boto.ec2.blockdevicemapping.BlockDeviceType().delete_on_termination = True
# does not help.
instance.modify_attribute('blockDeviceMapping', ['/dev/sda1=1'])

任何想法如何实现我所描述的。

更新的 我跑了:

Traceback (most recent call last):
  File "ec2_api.py", line 173, in <module>
    instance_id, ip_address = spinup_instance(params.ami, params.type)
  File "ec2_api.py", line 83, in spinup_instance
    instance.modify_attribute('blockDeviceMapping', ['/dev/sda1=1'])
  File "/home/x/python2.7/site-packages/boto/ec2/instance.py", line 557, in modify_attribute
    dry_run=dry_run
  File "/home/x/python2.7/site-packages/boto/ec2/connection.py", line 1274, in modify_instance_attribute
    return self.get_status('ModifyInstanceAttribute', params, verb='POST')
  File "/home/x/python2.7/site-packages/boto/connection.py", line 1227, in get_status
    raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidInstanceAttributeValue</Code><Message>No device is currently mapped at /dev/sda1</Message></Error></Errors><RequestID>xxx</RequestID></Response>

所以块设备是正确的。

1 个答案:

答案 0 :(得分:0)

我已经得到了并想分享:

from boto.ec2.blockdevicemapping import BlockDeviceType, BlockDeviceMapping

def set_ebs_termination(conn, instance_id, attempts=15):
    """
    @conn: ec2 connection
    @instance_id: string
    """
    for iter in range(attempts):
        block = conn.get_instance_attribute(instance_id=instance_id,\
            attribute='blockDeviceMapping')['blockDeviceMapping']

        if '/dev/sda1' in block and\
            (block['/dev/sda1']).status == 'attached':
            break
        logging.info('Waiting for the EBS to get attached.')
        time.sleep(30)

    if (block['/dev/sda1']).status != 'attached':
        raise Exception('The EBS was not attached'\
            'after {} iterations.'.format(attempts))
    logging.info('Setting the block device termination.')
    bdm = BlockDeviceMapping()
    bdm['/dev/sda1'] = BlockDeviceType(delete_on_termination=True)
    conn.modify_instance_attribute(instance_id, "BlockDeviceMapping", bdm)