我创建了一个 python 脚本,将最新快照从一个区域移动到另一个区域。该脚本使用我计算机上的本地凭据来移动 EC2 实例 ID,不确定这是否适用于下面的情况。
代码:
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'])
我发现这个链接说我可以使用系统管理器( https://docs.aws.amazon.com/systems-manager/latest/userguide/integration-remote-scripts.html#integration-github-python )从 AWS 运行 github 中的 python 代码。查找标题“从 GitHub 运行 Python 脚本” '。
指南中有以下命令用于在 github 中执行代码:
{"owner":"owner_name", "repository": "repository_name", "path": "path_to_scripts_or_directory", "tokenInfo":"{{ssm-secure:SecureString_parameter_name}}" }
我是否可以在上面的代码中添加一个计时器,以便我的 python 脚本按照计时器运行?
接受所有远程运行 python 脚本的建议。
提前谢谢您。
编辑:
我可以通过代码输入 API key 以避免在其他地方配置凭据吗?
编辑2:
尝试将代码放入 lambda 函数中。将 AWS_Backup.py
压缩为 AWS_Backup.py.zip
。 AWS 中的处理程序信息 AWS_Backup.handler
也发生了更改。
代码更新:
from __future__ import print_function
def lambda_handler(event, context):
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'])
错误:“errorMessage”:“模块“AWS_Backup”上缺少处理程序“handler””
解决方案:
change the lambda handler in AWS console from 'AWS_Backup.handler' to AWS_Backup.lambda_handler. Plus some role permissions were added to give me more access to IAM role.
最佳答案
太酷了,我不知道你可以使用 SSM 直接从 github 执行代码。
如果您没有采用纯粹的 SSM 解决方案,您可以合并 lambda
两个选项。
- 使用 Lambda 和 CloudWatch Events。将您的代码放入 Lambda 中,然后使用 用于触发 Lambda 函数的 Cloud Watch Events。
- 使用 Lambda 和 CloudWatch Events 按预先确定的时间间隔调用 SSM。本质上是一个执行远程调用的垫片。
关于python - 如何添加计时器参数以从AWS在github上执行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50450994/