在python中运行函数时,在运行时填充占位符



我正在编写一个python脚本,以便在运行函数后打印IAM策略;start_time";以及";end_time";在运行时填充。这是我的功能:

import json
import meta_templates
from jinja2 import Template
start_time_1 = input("What's the start time")
end_time1 = input("What's the end time")
def create_aws_iam_policy_template(**kwargs):
template_data = {}
template_data["region"] = kwargs.get('region')
template_data["start_time"] = kwargs.get('end_time')
template_data["end_time"] = kwargs.get('start_time')
template_data["instance_types"] = kwargs.get('instance_type')
template_data["ebs_volume_size"] = kwargs.get('ebs_volume_size')
template_data["meta_template_name"] = kwargs.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)
template_json = create_aws_iam_policy_template(
region="us-east-2",
instance_type="t2.micro",
ebs_volume_size="20",
meta_template_name="ec2_policy_meta_template",
start_time = "start_time_1",
end_time = "end_time1"
)
print(template_json)

这是我的IAM策略模板:

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}}"
}
}
}
]
}

如何填写";start_time";以及";end_time";

您的template_json = create_aws_iam_policy_template缺少逗号。应该是:

template_json = create_aws_iam_policy_template(
region="us-east-2",
instance_type="t2.micro",
ebs_volume_size="20",
meta_template_name="ec2_policy_meta_template",
start_time = "start_time_1",
end_time = "end_time1"
)

更新:

您还在create_aws_iam_policy_template中错误地返回,因此它将始终返回null

return template_json

最新更新