[英]Calling function from a module in python
我正在使用 python 腳本從另一個文件中調用一個文件中的變量。這是 IAM 用戶的 IAM 策略。 我有一個 function 在另一個文件文件中調用變量,其中 function 被命名為“template_utils.py”。 我想要 JSON 格式的 output。 我不確定是什么問題。
import sys
import json
import time
import meta_templates
from jinja2 import Template
def create_aws_iam_policy_template(**kwargs):
template_data = {}
template_data["region"] = kwargs.get('region')
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 = meta_template_json.format(template_data)
return template_json
template_json = create_aws_iam_policy_template(
region="us-east2",
instance_type="t2.micro",
ebs_volume_size=20,
meta_template_name="ec2_policy_meta_template"
)
打印(模板_json)
這是策略名為“meta_template.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}}"
}
}
}
]
}
tm = Template(json.dumps(ec2_policy_meta_template))
parsed_policy = tm.render(region='us-east-1', ebs_volume_size='12', instance_type='t2.micro')
print(parsed_policy)
這是我在運行“template_utils.py”時遇到的錯誤
{"Version": "2012-10-17", "Statement": [{"Sid": "VisualEditor0", "Effect": "Allow", "Action": "ec2:RunInstances", "Resource": ["arn:aws:ec2:us-east-1::instance/*", "arn:aws:ec2:us-east-1::network-interface/*", "arn:aws:ec2:us-east-1::key-pair/*", "arn:aws:ec2:us-east-1::security-group/*", "arn:aws:ec2:us-east-1::subnet/*", "arn:aws:ec2:us-east-1::volume/*", "arn:aws:ec2:us-east-1::image/ami-*"], "Condition": {"ForAllValues:NumericLessThanEquals": {"ec2:VolumeSize": "12"}, "ForAllValues:StringEquals": {"ec2:InstanceType": "t2.micro"}}}, {"Sid": "VisualEditor1", "Effect": "Allow", "Action": ["ec2:TerminateInstances", "ec2:StartInstances", "ec2:StopInstances"], "Resource": "arn:aws:ec2:us-east-1::instance/*", "Condition": {"ForAllValues:StringEquals": {"ec2:InstanceType": "t2.micro"}}}, {"Sid": "VisualEditor2", "Effect": "Allow", "Action": ["ec2:Describe*", "ec2:GetConsole*", "cloudwatch:DescribeAlarms", "iam:ListInstanceProfiles", "cloudwatch:GetMetricStatistics", "ec2:DescribeKeyPairs", "ec2:CreateKeyPair"], "Resource": "*", "Condition": {"DateGreaterThan": {"aws:CurrentTime": ""}, "DateLessThanEquals": {"aws:CurrentTime": ""}}}]}
Traceback (most recent call last):
File "/home/pranay/Desktop/work/template_utils.py", line 18, in <module>
template_json = create_aws_iam_policy_template(
File "/home/pranay/Desktop/work/template_utils.py", line 15, in create_aws_iam_policy_template
template_json = meta_template_json.format(template_data)
KeyError: '"Version"'
我認為你所有的問題是你混合兩種不同的方法來填充模板 - text.format()
和jinja2
text.format()
使用
{variable}
將值放入模板{{ }}
保持正常{ }
jinja2
使用
{{variable}}
將值放入模板{ }
保持正常{ }
而且您有{{region}}
來放置價值,因此您期望jinj2
方法,但您使用format()
,它使用其他方法並且它在您的模板中看到{"VERSION"...
並嘗試替換它。
您必須使用jinja2
- 它會更簡單然后更改模板format()
string formatting
'{"VERSION": "{{region}}" }'.format(region="us-east2")
結果:
KeyError: '"VERSION"'
jinja2
from jinja2 import Template
t = Template('{"VERSION": "{{region}}" }')
t.render(region="us-east2")
結果:
'{"VERSION": "us-east2" }'
編輯:
看來你還是不明白。
jinja2
不是string
的 function 而是您必須安裝的外部模塊
pip install Jinja2
並以特殊方式導入和使用。
對於您的示例,它可能是這樣的
from jinja2 import Template
template_json = Template(meta_template_json).render(template_data)
它使用帶有雙{{
和}}
的占位符 - 就像在您的模板{{region}}
中一樣。 當你有像'{"VERSION": ...}
這樣的單個{
}
時,它不會嘗試替換值。 因此它將以正確的方式與您的模板一起使用。
但是原始format()
以不同的方式工作 - 它使用帶有單個{
和}
的占位符 - 所以你有占位符'{"VERSION": ...}
並且它在template_data
中找不到變量"VERSION"
來替換它。 這會產生問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.