【发布时间】:2021-04-14 08:54:29
【问题描述】:
我正在为我的 python 函数开发 AWS Lambda 函数。我有一个 python 函数,它从文件中调用 IAM 策略并使用该函数填充它。这是我的函数,文件名是 template_utils.py":
import sys
import json
import time
import meta_templates
from jinja2 import Template
def lambda_handler(event,context):
template_data = {}
template_data["region"] = event.get('region')
template_data["instance_types"] = event.get('instance_type')
template_data["ebs_volume_size"] = event.get('ebs_volume_size')
template_data["meta_template_name"] = event.get('meta_template_name')
meta_template_dict = getattr(meta_templates, template_data["meta_template_name"])
meta_template_json = json.dumps(meta_template_dict)
template_json = Template(meta_template_json).render(template_data)
return template_json
template_json = lambda_handler(
region="us-east-2",
instance_type="t2.micro",
ebs_volume_size="20",
meta_template_name="ec2_policy_meta_template"
)
print(template_json)
这是我的名为“meta_templates.py”的策略文件
import json
from jinja2 import Template
ec2_policy_meta_template = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "ec2:RunInstances",
"Resource": [
"arn:aws:ec2:{{region}}::instance/*",
"arn:aws:ec2:{{region}}::network-interface/*",
"arn:aws:ec2:{{region}}::key-pair/*",
"arn:aws:ec2:{{region}}::security-group/*",
"arn:aws:ec2:{{region}}::subnet/*",
"arn:aws:ec2:{{region}}::volume/*",
"arn:aws:ec2:{{region}}::image/ami-*"
],
"Condition": {
"ForAllValues:NumericLessThanEquals": {
"ec2:VolumeSize": "{{ebs_volume_size}}"
},
"ForAllValues:StringEquals": {
"ec2:InstanceType": "{{instance_type}}"
}
}
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"ec2:TerminateInstances",
"ec2:StartInstances",
"ec2:StopInstances"
],
"Resource": "arn:aws:ec2:{{region}}::instance/*",
"Condition": {
"ForAllValues:StringEquals": {
"ec2:InstanceType": "{{instance_type}}"
}
}
},
{
"Sid": "VisualEditor2",
"Effect": "Allow",
"Action": [
"ec2:Describe*",
"ec2:GetConsole*",
"cloudwatch:DescribeAlarms",
"iam:ListInstanceProfiles",
"cloudwatch:GetMetricStatistics",
"ec2:DescribeKeyPairs",
"ec2:CreateKeyPair"
],
"Resource": "*",
"Condition": {
"DateGreaterThan": {
"aws:CurrentTime": "{{start_time}}"
},
"DateLessThanEquals": {
"aws:CurrentTime": "{{end_time}}"
}
}
}
]
}
我想创建一个与函数“template_utils.py”执行相同操作的 lambda 处理程序。我是新手,不知道如何继续。我收到此错误:
Traceback (most recent call last):
File "/home/pranay/Desktop/work/lambda_handler.py", line 18, in <module>
template_json = lambda_handler(
TypeError: lambda_handler() got an unexpected keyword argument 'region'
【问题讨论】:
-
lambda_handler需要一个事件和上下文,你给它一个区域 - 这显然不会起作用。 -
删除了所有与 AWS 相关的标签,因为这不是 AWS 特定的,而是一个常规的 python 问题?
-
这是一个 aws-lambda 函数,因此我将使用它来调用 AWS 上的函数,因此我认为包含这些标签可能会提供更好的外展服务
标签: python python-3.x amazon-web-services aws-lambda boto3