과제
AWS SDK for Python (Boto3)로 Amazon EBS 볼륨 암호화하기
python encrypt.py --instance-id INSTANCE_ID Last updated
AWS SDK for Python (Boto3)로 Amazon EBS 볼륨 암호화하기
python encrypt.py --instance-id INSTANCE_ID Last updated
import argparse
import boto3
import time
ec2 = boto3.resource('ec2')
## Parse instance id
parser = argparse.ArgumentParser()
parser.add_argument("--instance-id")
args = parser.parse_args()
instance_id = args.instance_id
## Get the existing volume
instance = ec2.Instance(instance_id)
volume_id = instance.block_device_mappings[0]['Ebs']['VolumeId']
volume = ec2.Volume(volume_id)
## Create a snapshot
snapshot = volume.create_snapshot()
snapshot.wait_until_completed()
## Create an encrypted copy of the snapshot
resp = snapshot.copy(
Encrypted=True,
SourceRegion=boto3.session.Session().region_name
)
encrypted_snapshot = ec2.Snapshot(resp['SnapshotId'])
encrypted_snapshot.wait_until_completed()
## Create an encrypted volume
encrypted_volume = ec2.create_volume(
AvailabilityZone=instance.subnet.availability_zone,
SnapshotId=encrypted_snapshot.id
)
## Get the existing volume attachment info
device = volume.attachments[0]['Device']
## Stop EC2
instance.stop()
instance.wait_until_stopped()
## Detach the existing volume
volume.detach_from_instance()
while True:
volume.reload()
if volume.state == 'available':
break
time.sleep(15)
## Attach the encrypted volume
encrypted_volume.attach_to_instance(
Device=device,
InstanceId=instance.id
)
while True:
encrypted_volume.reload()
if encrypted_volume.state == 'in-use':
break
time.sleep(15)
## Start EC2
instance.start()
instance.wait_until_running()
## Delete the detached volume
volume.delete()