- 新しい順
- 投票が多い順
- コメントが多い順
Lambda is limited (15 minutes max), and this may not be enough for a backup copy. Please consider using AWS Backup and Backup policies
I made an article about it https://www.automat-it.com/multi-account-backup-copy-in-aws/
Hi,
Why don't you just use the existing Cross-Account Snapshot Copy Policies: see https://docs.aws.amazon.com/ebs/latest/userguide/event-policy.html
They do exactly what you want with full automation.
Best,
Didier
Question mentions snapshot but does not explicitly say EBS. Snapshots could also be created for several databases and below answer is for EBS.
import boto3
import os
def lambda_handler(event, context):
# Get the account number from an environment variable
target_account = os.getenv('TARGET_ACCOUNT')
# Initialize the EC2 client
ec2 = boto3.client('ec2')
# Get the snapshot ID from the event input
snapshot_id = event.get('snapshot_id')
if not snapshot_id:
print("Error: No snapshot ID provided in the event")
return {
'statusCode': 400,
'body': 'Error: No snapshot ID provided in the event'
}
try:
# Share the snapshot with the target account
response = ec2.modify_snapshot_attribute(
SnapshotId=snapshot_id,
Attribute='createVolumePermission',
OperationType='add',
UserIds=[target_account]
)
print(f"Shared snapshot {snapshot_id} with account {target_account}")
return {
'statusCode': 200,
'body': 'Snapshot shared successfully'
}
except Exception as e:
print(f"Error sharing snapshot: {e}")
return {
'statusCode': 500,
'body': f"Error sharing snapshot: {e}"
}
Here's how the code works:
-
The function first retrieves the target account number from an environment variable named
TARGET_ACCOUNT
. This assumes that you have set this environment variable in your Lambda function configuration. -
You'll need to replace
'your-snapshot-id'
with the actual ID of the snapshot you want to share. -
The
modify_snapshot_attribute
method is used to share the snapshot with the target account. TheAttribute
parameter is set to'createVolumePermission'
, which allows the target account to create volumes from the shared snapshot. TheOperationType
parameter is set to'add'
to grant the permission, and theUserIds
parameter is a list containing the target account ID. -
If the operation is successful, the function returns a success response with a status code of 200 and a message indicating that the snapshot was shared successfully.
-
If an exception occurs during the process, the function returns an error response with a status code of 500 and the error message.
Make sure to replace the 'your-snapshot-id'
placeholder with the actual ID of the snapshot you want to share, and ensure that the TARGET_ACCOUNT
environment variable is set correctly in your Lambda function configuration.
関連するコンテンツ
- AWS公式更新しました 2年前
- AWS公式更新しました 1年前
please accept the answer if it was useful