Использование boto3 для создания и подключения тома EBS к экземпляру EC2 - PullRequest
0 голосов
/ 08 апреля 2020

У меня есть существующий экземпляр EC2 с двумя подключенными томами EBS. Я хочу добавить третий том EBS к этому экземпляру EC2, используя boto3.

Вот что я думаю:

  • Создайте том, используя ec2.create_volume
  • Получите идентификатор тома сверху, а затем используйте ec2.attach_volume , чтобы присоединить новый том.

Или есть более простой способ сделать это ? В boto3 есть функция, которую я могу использовать для добавления нового тома EBS в существующий экземпляр EC2?

Спасибо и будьте в безопасности.

Ответы [ 2 ]

1 голос
/ 09 апреля 2020

Попробуйте это ...

 '''
 Creation State:
 'State': 'creating'|'available'|'in-use'|'deleting'|'deleted'|'error'

 Attachment State:
 'State': 'attaching'|'attached'|'detaching'|'detached'
 '''

 #create_and_attach_volume
def create_and_attach_volume(ec2_client, availability_zone, DryRunFlag, device, 
instance_id):
try:
    response= ec2_client.create_volume(
        AvailabilityZone=availability_zone,
        Encrypted=False,
        #Iops=100,
        #KmsKeyId='string',
        Size=10,
        #SnapshotId='string',
        VolumeType='gp2',    #standard'|'io1'|'gp2'|'sc1'|'st1',
        DryRun=DryRunFlag
        )
    #pprint(response)

    if response['ResponseMetadata']['HTTPStatusCode']== 200:
        volume_id= response['VolumeId']
        print('***volume:', volume_id)

        ec2_client.get_waiter('volume_available').wait(
            VolumeIds=[volume_id],
            DryRun=DryRunFlag
            )
        print('***Success!! volume:', volume_id, 'created...')

except Exception as e:
        print('***Failed to create the volume...')
        print(type(e), ':', e)

#botocore.exceptions.ClientError:
#An error occurred (InvalidParameterCombination) when calling the CreateVolume 
operation: The parameter iops is not supported for gp2 volumes.
if volume_id:
    try:
        print('***attaching volume:', volume_id, 'to:', instance_id)
        response= ec2_client.attach_volume(
            Device=device,
            InstanceId=instance_id,
            VolumeId=volume_id,
            DryRun=DryRunFlag
            )
        #pprint(response)

        if response['ResponseMetadata']['HTTPStatusCode']== 200:
            ec2_client.get_waiter('volume_in_use').wait(
                VolumeIds=[volume_id],
                DryRun=False
                )
            print('***Success!! volume:', volume_id, 'is attached to instance:', 
  instance_id)

    except Exception as e:
        print('***Error - Failed to attach volume:', volume_id, 'to the instance:', instance_id)
        print(type(e), ':', e)

#botocore.exceptions.ClientError:
#An error occurred (IncorrectState) when calling the AttachVolume operation: vol- 
0fcc7c3319a885513 is not 'available'.
#An error occurred (InvalidParameterValue) when calling the AttachVolume operation: 
Invalid value '/dev/sdc' for unixDevice. Attachment point /dev/sdc is already in use

#__main__
session= boto3.session.Session()
region_name= session.region_name
#region_name='ap-south-1'
availability_zone='ap-south-1a'
bdm='/dev/sdc'
instance_id='i-08364669ada3804d3'

start= -perf_counter()
ec2_client= boto3.client('ec2', region_name=region_name)
create_and_attach_volume(ec2_client, availability_zone, DryRunFlag=False, bdm, 
instance_id)
print('***duration:', (start+ perf_counter()), 'secs')

Надеюсь, это поможет ...
r0ck

1 голос
/ 08 апреля 2020

Не существует "единого вызова API", объединяющего оба действия.

Вы правильно создаете том, а затем присоединяете его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...