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

Boto3 not copying snapshot to other regions, other options?

[AWS 新手]

嗨,

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

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

我正在使用 pandas 使用此代码获取最新的快照 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 returns 类似于 snap-1234ABCD

的快照 ID

我正在尝试使用此代码将快照从 us-east-2 移动到 us-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 中的快照?

根据CopySnapshot - Amazon Elastic Compute Cloud

CopySnapshot sends the snapshot copy to the regional endpoint that you send the HTTP request to, such as ec2.us-east-1.amazonaws.com (in the AWS CLI, this is specified with the --region parameter or the default region in your AWS configuration file).

因此,您应该将 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'])