Boto3没有将快照复制到其他区域,还有其他选项吗?

时间:2018-05-18 15:00:12

标签: python amazon-web-services amazon-ec2 snapshot amazon-ebs

[非常适合AWS]

嗨,

我正在尝试跨区域移动我的EBS卷快照副本。我一直在尝试使用Boto3来移动快照。我的目标是每天自动将最新快照从us-east-2区域移至us-east-1区域。

我在终端中使用了aws configure命令来设置我的安全凭据并将区域设置为us-east-2

我正在使用pandas使用此代码获取最新的snapshot-id:

import boto3
import pandas as pd
from pandas.io.json.normalize import nested_to_record    
import boto.ec2


    client = boto3.client('ec2')
    aws_api_response = client.describe_snapshots(OwnerIds=['self'])
    flat = nested_to_record(aws_api_response)
    df = pd.DataFrame.from_dict(flat)
    df= df['Snapshots'].apply(pd.Series)
    insert_snap = df.loc[df['StartTime'] == max(df['StartTime']),'SnapshotId']
    insert_snap = insert_snap.reset_index(drop=True)

insert_snap会返回类似snap-1234ABCD

的快照ID

我尝试使用此代码将快照从us-east-2移至您s-east-1

client.copy_snapshot(SourceSnapshotId='%s' %insert_snap[0],
                     SourceRegion='us-east-2',
                     DestinationRegion='us-east-1',
                     Description='This is my copied snapshot.')

快照正在使用上面的行复制到同一区域。

我还尝试在终端中通过aws configure命令切换区域,同一问题发生在同一区域中复制快照的地方。

Boto3中存在一个错误,即在copy_snapshot()代码中跳过目标参数。此处的信息:https://github.com/boto/boto3/issues/886

我已尝试将此代码插入lambda管理器,但不断收到错误"errorMessage": "Unable to import module 'lambda_function'"

region = 'us-east-2'
ec = boto3.client('ec2',region_name=region)

def lambda_handler(event, context):
    response=ec.copy_snapshot(SourceSnapshotId='snap-xxx',
                     SourceRegion=region,
                     DestinationRegion='us-east-1',
                     Description='copied from Ohio')
    print (response)

我没有选择,我可以做些什么来自动转移aws中的快照?

1 个答案:

答案 0 :(得分:2)

根据CopySnapshot - Amazon Elastic Compute Cloud

  

CopySnapshot将快照副本发送到您向其发送HTTP请求的区域端点,例如ec2.us-east-1.amazonaws.com(在AWS CLI中,使用--region参数指定或AWS配置文件中的默认区域。)

因此,您应该将copy_snapshot()命令发送到us-east-1,并将源区域设置为us-east-2

如果您想移动最新的快照,可以运行:

import boto3

SOURCE_REGION = 'us-east-2'
DESTINATION_REGION = 'us-east-1'

# Connect to EC2 in Source region
source_client = boto3.client('ec2', region_name=SOURCE_REGION)

# Get a list of all snapshots, then sort them
snapshots = source_client.describe_snapshots(OwnerIds=['self'])
snapshots_sorted = sorted([(s['SnapshotId'], s['StartTime']) for s in snapshots['Snapshots']], key=lambda k: k[1])
latest_snapshot = snapshots_sorted[-1][0]

print ('Latest Snapshot ID is ' + latest_snapshot)

# Connect to EC2 in Destination region
destination_client = boto3.client('ec2', region_name=DESTINATION_REGION)

# Copy the snapshot
response = destination_client.copy_snapshot(
    SourceSnapshotId=latest_snapshot,
    SourceRegion=SOURCE_REGION,
    Description='This is my copied snapshot'
    )

print ('Copied Snapshot ID is ' + response['SnapshotId'])