과제
AWS SDK for Python (Boto3)로 Amazon EBS 볼륨 암호화하기
핀테크 스타트업 A사는 ISMS-P 인증을 받기 위해서 AWS 인프라에 대한 보안점검을 하던 중에 수백대의 EC2 인스턴스의 EBS 루트 볼륨이 암호화되어 있지 않은걸 발견했습니다. 수동적인 반복 작업을 최소화하고 인적 오류를 예방하고자 인프라 운영팀에서는 AWS SDK를 사용해서 암호화 되지 않은 EBS 루트 볼륨들을 암호화하려고 합니다. 기존 인스턴스를 대체할 신규 인스턴스를 생성할 경우에는 기존 인스턴스에 부여된 EIP를 새 인스턴스에 부여하고 기존 인스턴스는 삭제해야합니다. 아래의 명령어를 실행하면 EC2 인스턴스의 루트볼륨이 암호화되는 코드를 작성하세요
python encrypt.py --instance-id INSTANCE_ID 새로운 인스턴스를 생성할 경우
EBS Snapshot 생성
위에서 생성한 EBS Snapshot을 암호화된 Snapshot으로 복사
암호화된 Snapshot으로 AMI 생성
AMI로 EC2 생성
기존 인스턴스에 부여된 EIP를 신규 인스턴스에 부여
기존 인스턴스 삭제
기존 인스턴스를 유지할 경우
EBS Snapshot 생성
위에서 생성한 EBS Snapshot을 암호화된 Snapshot으로 복사
암호화된 Snapshot으로 EBS 볼륨 생성
기존 인스턴스 중지
기존 인스턴스에 붙어있는 EBS 루트볼륨 Detach
새로 생성한 암호화된 EBS 볼륨 Attach
인스턴스 구동
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()Last updated
Was this helpful?