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
}
]
)
'IT > 클라우드' 카테고리의 다른 글
AWS Route53 외부도메인 등록 방법 (0) | 2025.02.18 |
---|---|
AWS RDS EC2에서 접속하기 (0) | 2025.02.18 |
AWS 인스턴스 생성시 (httpd php mysql)부트스크랩 (스크립트 포함) (0) | 2025.02.18 |
AWS EC2 생성 과정 (0) | 2025.02.18 |
AWS 보안그룹 생성 & 설정 (0) | 2025.02.18 |