본문 바로가기
IT/클라우드

AWS AMI 이미지 백업 (스크립트)

by JGSHIN 2025. 2. 18.
SMALL

import boto3

from datetime import datetime

session = boto3.Session()

ec2_client = session.client('ec2')

ec2_response = ec2_client.describe_instances()

for instances in ec2_response['Reservations']:

    for instance in instances['Instances']:

        instance_id = instance['InstanceId']

       

        # Check Latest Backup

        response = ec2_client.describe_images(

            Filters=[

                {'Name': 'tag:Instance', 'Values': [instance_id]}

            ],

            Owners=['self']

        )

        tmp = sorted(response['Images'], key=lambda x: x['CreationDate'], reverse=True)

        if len(tmp) != 0:

            if tmp[0]['State'] != 'available':

                print(f'{instance_id}에 대한 이전 백업이 완료되지 않았습니다.')

                continue

        # Get Instance Nam

        instance_name = ''

        for tag in instance['Tags']:

            if tag['Key'] == 'Name':

                instance_name = tag['Value']

                break

       

        if instance_name == '':

            instance_name = instance['PrivateDnsName']

        backup_time = datetime.now().strftime('%Y%m%d%H%M')

        ami_name = f'{instance_name}_{backup_time}'

 

        # backup instance

        ami_response = ec2_client.create_image(

            InstanceId = instance_id,

            Name = ami_name,

            NoReboot = True

        )

       

        ami_id = ami_response['ImageId']

        # AMI Set Name Tag

        ec2_client.create_tags(

            Resources = [ami_id],

            Tags = [

                {

                    'Key': 'Name',

                    'Value': ami_name

                },

                {

                    'Key':'Instance',

                    'Value': instance_id

                }

            ]

        )

LIST
📧 이메일 문의
by @ 2025 JGSHIN