AWS Lambda,boto3-启动实例,测试时出错(无法追踪)



我正在尝试创建一个Lambda函数来自动启动/停止/重新启动一些实例(将来还会有一些额外的任务(。

我用一个策略创建了IAM角色:

{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"ec2:StartInstances",
"ec2:StopInstances",      
"ec2:RebootInstances"
],
"Condition": {
"StringEquals": {
"ec2:ResourceTag/critical":"true"
}
},
"Resource": [
"arn:aws:ec2:*:<12_digits>:instance/*"
],
"Effect": "Allow"
}
]
}

Lambda函数已被授予访问正确的VPC、子网和安全组的权限。

我把这个角色分配给了一个新的Lambda函数(Python 3.9(:

import boto3
from botocore.exceptions import ClientError
# instance IDs copied from my AWS Console 
instances = ['i-xx1', 'i-xx2', 'i-xx3', 'i-xx4']
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
print(str(instances))
try:
print('The break occurs here u2193')
response = ec2.start_instances(InstanceIds=instances, DryRun=True)
except ClientError as e:
print(e)
if 'DryRunOperation' not in str(e):
print("You don't have permission to reboot instances.")
raise
try:
response = ec2.start_instances(InstanceIds=instances, DryRun=False)
print(response)
except ClientError as e:
print(e)
return response

由于测试输出中没有关于错误位置的消息,我找不到任何信息。我原以为这是时间问题,然后我将时间限制设置为5分钟,以确定这是否是时间问题。例如:

Test Event Name
chc_lambda_test1
Response
{
"errorMessage": "2022-07-30T19:15:40.088Z e037d31d-5658-40b4-8677-1935efd3fdb7 Task timed out after 300.00 seconds"
}
Function Logs
START RequestId: e037d31d-5658-40b4-8677-1935efd3fdb7 Version: $LATEST
['i-xx', 'i-xx', 'i-xx', 'i-xx']
The break occurs here ↓
END RequestId: e037d31d-5658-40b4-8677-1935efd3fdb7
REPORT RequestId: e037d31d-5658-40b4-8677-1935efd3fdb7  Duration: 300004.15 ms  Billed Duration: 300000 ms  Memory Size: 128 MB Max Memory Used: 79 MB  Init Duration: 419.46 ms    
2022-07-30T19:15:40.088Z e037d31d-5658-40b4-8677-1935efd3fdb7 Task timed out after 300.00 seconds
Request ID
e037d31d-5658-40b4-8677-1935efd3fdb7

我也尝试过增加Lambda内存,但没有成功(事实并非如此,因为使用的最大内存为79MB(。

出现此问题的主要原因是无法访问分配给Lambda函数的子网。我在专有网络中添加了一个端点(正如Ervin Szilagyi所建议的((分配给子网和安全组(。

下一步是提供授权-由于这个想法,在使用Boto3启动具有IAM角色的EC2实例时会出现未经授权的操作错误,我在客户端调用中添加了IAM访问密钥和密钥。

ec2 = boto3.client(
'ec2',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
)

但是,请小心安全设置,我是一个新用户(目前正在处理我的私人项目(,因此,您不应该认为此解决方案是安全的。

最新更新